TExcelTAD
Home › Calculus Essentials › Numerical Solutions: Euler and RK4

Numerical Solutions: Euler and RK4

Most differential equations in real programs have no formula solution, so computers solve them step by step: start at the known value, use the equation to estimate the slope, take a small step, repeat. This lesson builds Euler's method and the classic fourth-order Runge–Kutta method (RK4) from scratch, measures how their errors shrink with the step size, and compares them with SciPy's solve_ivp.

Euler's method

For y′=f(t,y)y' = f(t, y) with y(t0)=y0y(t_0) = y_0 and step size hh, the derivative is the slope of the tangent line, so walk along the tangent:

yn+1=yn+h⋅f(tn,yn)tn+1=tn+h\begin{aligned} y_{n+1} &= y_n + h \cdot f(t_n, y_n) \\ t_{n+1} &= t_n + h \end{aligned}

This is the linear approximation used over and over. Each step makes an error of order h2h^2 (the Taylor term that is dropped), and reaching a fixed end time takes 1/h1/h steps, so the total error is of order hh. Euler is a first-order method: halve hh and the error roughly halves.

RK4

RK4 samples the slope four times per step, at the start, twice in the middle and at the end, and takes a weighted average:

k1=f(t,y)k2=f(t+h/2, y+hk1/2)k3=f(t+h/2, y+hk2/2)k4=f(t+h, y+hk3)yn+1=yn+h6(k1+2k2+2k3+k4)\begin{aligned} k_1 &= f(t, y) \\ k_2 &= f(t + h/2,\ y + hk_1/2) \\ k_3 &= f(t + h/2,\ y + hk_2/2) \\ k_4 &= f(t + h,\ y + hk_3) \\ y_{n+1} &= y_n + \frac{h}{6}(k_1 + 2k_2 + 2k_3 + k_4) \end{aligned}

The weights 1, 2, 2, 1 are those of Simpson's rule. RK4 is fourth order: halve hh and the error shrinks about 24=162^4 = 16 times.

The accuracy table

Test both on y′=yy' = y, y(0)=1y(0) = 1, whose exact value at t=1t = 1 is e≈2.718281828e \approx 2.718281828.

python · try it yourself
import math

def euler(f, t, y, h, n):
    for _ in range(n):
        y += h * f(t, y)
        t += h
    return y

def rk4(f, t, y, h, n):
    for _ in range(n):
        k1 = f(t, y)
        k2 = f(t + h / 2, y + h * k1 / 2)
        k3 = f(t + h / 2, y + h * k2 / 2)
        k4 = f(t + h, y + h * k3)
        y += h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
        t += h
    return y

f = lambda t, y: y
print("   h     Euler error   ratio    RK4 error    ratio")
prev = None
for n in [10, 20, 40, 80]:
    eE = abs(euler(f, 0, 1.0, 1 / n, n) - math.e)
    eR = abs(rk4(f, 0, 1.0, 1 / n, n) - math.e)
    r = f"{prev[0] / eE:5.2f}  {'':4}{eR:.3e}  {prev[1] / eR:6.2f}" if prev else f"{'':5}  {'':4}{eR:.3e}"
    print(f"{1 / n:.4f}  {eE:.3e}  {r}")
    prev = (eE, eR)
   h     Euler error   ratio    RK4 error    ratio
0.1000  1.245e-01             2.084e-06
0.0500  6.498e-02   1.92      1.358e-07   15.35
0.0250  3.322e-02   1.96      8.666e-09   15.67
0.0125  1.680e-02   1.98      5.473e-10   15.83

The ratio columns tell the story: every halving of hh divides Euler's error by about 2 and RK4's by about 16. With h=0.1h = 0.1 (10 steps, 40 slope evaluations) RK4 is already about as accurate as Euler would be with a million steps (Euler's error is roughly 1.36h1.36h here).

Method Slope evaluations per step Order Error at h=0.1h = 0.1 above
Euler 1 1 about 0.12
RK4 4 4 about 2⋅10−62 \cdot 10^{-6}

Systems and second-order equations

Both methods work unchanged on vectors. A second-order equation becomes a first-order system by naming the velocity: x′′=−4xx'' = -4x turns into (x,v)′=(v,−4x)(x, v)' = (v, -4x). Here is the undamped spring from second-order equations with x(0)=1x(0) = 1, v(0)=0v(0) = 0, exact solution x=cos⁡2tx = \cos 2t, compared against solve_ivp (its default method RK45 adapts hh to a tolerance):

python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp

f = lambda t, s: np.array([s[1], -4 * s[0]])
h, T = 0.05, 10.0
n = int(round(T / h))

sE = np.array([1.0, 0.0]); sR = sE.copy()
for i in range(n):
    t = i * h
    sE = sE + h * f(t, sE)
    k1 = f(t, sR); k2 = f(t + h/2, sR + h/2 * k1)
    k3 = f(t + h/2, sR + h/2 * k2); k4 = f(t + h, sR + h * k3)
    sR = sR + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

ivp = solve_ivp(f, (0, T), [1.0, 0.0], rtol=1e-8, atol=1e-10)
exact = np.cos(2 * T)
print(f"exact      x(10) = {exact: .6f}")
print(f"Euler      x(10) = {sE[0]: .6f}   ({n} f-calls)")
print(f"RK4        x(10) = {sR[0]: .6f}   ({4 * n} f-calls)")
print(f"solve_ivp  x(10) = {ivp.y[0, -1]: .6f}   ({ivp.nfev} f-calls)")
print(f"Euler energy grew by a factor {(sE[0]**2 + sE[1]**2 / 4):.2f}")
exact      x(10) =  0.408082
Euler      x(10) =  1.264886   (200 f-calls)
RK4        x(10) =  0.408097   (800 f-calls)
solve_ivp  x(10) =  0.408082   (1604 f-calls)
Euler energy grew by a factor 7.32

Euler's answer is badly wrong: on an oscillator it adds a little energy every step, so the amplitude spirals outward. RK4 is off by only 1.5⋅10−51.5 \cdot 10^{-5}, and solve_ivp matches all six digits shown; it spent more slope evaluations because we asked for a very tight tolerance (rtol=1e-8). In practice, call solve_ivp (see SciPy ODEs) and write your own stepper only when you need a fixed step, as in a game loop.

Stability: when the step is too big

For decay y′=−kyy' = -ky, Euler's update is yn+1=(1−hk) yny_{n+1} = (1 - hk)\,y_n. If hk>2hk > 2 the factor is below −1-1 and the "decay" explodes with flipping signs.

python · try it yourself
k = 50.0
for h in [0.01, 0.03, 0.05]:
    y, out = 1.0, []
    for _ in range(6):
        y = y + h * (-k * y)
        out.append(f"{y:9.4f}")
    print(f"h = {h}  (h·k = {h * k:.1f}):", " ".join(out))
h = 0.01  (h·k = 0.5):    0.5000    0.2500    0.1250    0.0625    0.0312    0.0156
h = 0.03  (h·k = 1.5):   -0.5000    0.2500   -0.1250    0.0625   -0.0312    0.0156
h = 0.05  (h·k = 2.5):   -1.5000    2.2500   -3.3750    5.0625   -7.5938   11.3906

Equations that mix very fast decay with slow behaviour are called stiff; they force explicit methods to tiny steps. Implicit solvers (solve_ivp(..., method="BDF") or "Radau") are built for them.

In software

  • Games and simulations step physics with fixed-step Euler variants every frame, because they are cheap and predictable (physics integration, integrators in game physics).
  • Scientific code (orbits, chemistry, epidemics) uses adaptive RK methods like RK45 or, for stiff systems, BDF.
  • Machine learning: gradient descent is Euler's method on θ′=−∇L(θ)\theta' = -\nabla L(\theta), and its "learning rate too large" divergence is the same instability as above (gradient descent). Neural ODEs and diffusion-model samplers call ODE solvers inside the network.

Exercises

Exercise 1: Two Euler steps by hand

Use Euler with h=0.5h = 0.5 to estimate y(1)y(1) for y′=t+yy' = t + y, y(0)=1y(0) = 1. The exact solution is y=2et−t−1y = 2e^t - t - 1; how big is the error?

Answer

Euler gives y(1)≈2.5y(1) \approx 2.5; exact 2e−2≈3.43662e - 2 \approx 3.4366, so the error is about 0.94.

Solution
step 1: t=0, y=1slope=0+1=1y=1+0.5⋅1=1.5step 2: t=0.5, y=1.5slope=0.5+1.5=2y=1.5+0.5⋅2=2.5exact: y(1)=2e−1−1≈3.4366error≈0.9366\begin{aligned} &\text{step 1: } t = 0,\ y = 1 && \text{slope} = 0 + 1 = 1 && y = 1 + 0.5 \cdot 1 = 1.5 \\ &\text{step 2: } t = 0.5,\ y = 1.5 && \text{slope} = 0.5 + 1.5 = 2 && y = 1.5 + 0.5 \cdot 2 = 2.5 \\ &\text{exact: } y(1) = 2e - 1 - 1 \approx 3.4366 && && \text{error} \approx 0.9366 \end{aligned}

Exercise 2: Predict the error

Euler with h=0.01h = 0.01 has error 0.004 at some fixed end time. Roughly what error do you expect with h=0.0025h = 0.0025? And for RK4, if h=0.1h = 0.1 gives error 3⋅10−63 \cdot 10^{-6}, what does h=0.05h = 0.05 give?

Answer

Euler: about 0.001. RK4: about 1.9⋅10−71.9 \cdot 10^{-7}.

Solution
Euler is order 1: h shrinks 4×→error shrinks≈4×→0.004/4=0.001RK4 is order 4: h shrinks 2×→error shrinks≈24=16×→3⋅10−6/16≈1.9⋅10−7\begin{aligned} &\text{Euler is order 1: } h \text{ shrinks } 4\times && \to \text{error shrinks} \approx 4\times && \to 0.004 / 4 = 0.001 \\ &\text{RK4 is order 4: } h \text{ shrinks } 2\times && \to \text{error shrinks} \approx 2^4 = 16\times && \to 3 \cdot 10^{-6} / 16 \approx 1.9 \cdot 10^{-7} \end{aligned}

Exercise 3: Largest stable step

For y′=−200yy' = -200y, what is the largest step hh for which Euler does not blow up? Which hh makes the numerical solution jump to exactly 0 after one step?

Answer

h<0.01h < 0.01 (hk<2hk < 2); h=0.005h = 0.005 gives factor 1−hk=01 - hk = 0.

Solution
yn+1=(1−200h) ynstable  ⟺  ∣1−200h∣<1  ⟺  0<h<2/200=0.011−200h=0  ⟺  h=0.005\begin{aligned} &y_{n+1} = (1 - 200h)\,y_n \\ &\text{stable} \iff \lvert 1 - 200h \rvert < 1 \iff 0 < h < 2/200 = 0.01 \\ &1 - 200h = 0 \iff h = 0.005 \end{aligned}

For 0.005<h<0.010.005 < h < 0.01 the solution still decays, but oscillates in sign, which the real solution never does.

Exercise 4: RK4 on cooling

Use RK4 with h=1h = 1 minute on T′=−0.07(T−20)T' = -0.07(T - 20), T(0)=90T(0) = 90, and compare T(10)T(10) with the exact Newton's-cooling formula.

Answer

Both give T(10)≈54.761T(10) \approx 54.761 °C; RK4 is off by only about 5⋅10−65 \cdot 10^{-6} °C.

Solution
python · try it yourself
import math

f = lambda t, T: -0.07 * (T - 20)
T, h = 90.0, 1.0
for i in range(10):
    t = i * h
    k1 = f(t, T); k2 = f(t + h/2, T + h*k1/2)
    k3 = f(t + h/2, T + h*k2/2); k4 = f(t + h, T + h*k3)
    T += h / 6 * (k1 + 2*k2 + 2*k3 + k4)
exact = 20 + 70 * math.exp(-0.7)
print(f"RK4 {T:.6f}   exact {exact:.6f}   diff {abs(T - exact):.1e}")
RK4 54.760976   exact 54.760971   diff 5.2e-06

Test yourself

Halving the step size of RK4 reduces the global error by roughly what factor?

  1. 2
  2. 4
  3. 8
  4. 16

What does one Euler step for y′=f(t,y)y' = f(t, y) do?

  1. Moves along the tangent line: y+h f(t,y)y + h\,f(t, y)
  2. Averages four slopes
  3. Solves an equation for the next yy
  4. Integrates ff exactly

Euler on an undamped spring makes the amplitude…

  1. Stay exactly constant
  2. Shrink to zero
  3. Grow step by step
  4. Jump to infinity in one step