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 with and step size , the derivative is the slope of the tangent line, so walk along the tangent:
This is the linear approximation used over and over. Each step makes an error of order (the Taylor term that is dropped), and reaching a fixed end time takes steps, so the total error is of order . Euler is a first-order method: halve 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:
The weights 1, 2, 2, 1 are those of Simpson's rule. RK4 is fourth order: halve and the error shrinks about times.
The accuracy table
Test both on , , whose exact value at is .
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 divides Euler's error by about 2 and RK4's by about 16. With (10 steps, 40 slope evaluations) RK4 is already about as accurate as Euler would be with a million steps (Euler's error is roughly here).
| Method | Slope evaluations per step | Order | Error at above |
|---|---|---|---|
| Euler | 1 | 1 | about 0.12 |
| RK4 | 4 | 4 | about |
Systems and second-order equations
Both methods work unchanged on vectors. A second-order equation becomes a first-order system by naming the velocity: turns into . Here is the undamped spring from second-order equations with , , exact solution , compared against solve_ivp (its default method RK45 adapts to a tolerance):
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 , 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 , Euler's update is . If the factor is below and the "decay" explodes with flipping signs.
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 , 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 to estimate for , . The exact solution is ; how big is the error?
Answer
Euler gives ; exact , so the error is about 0.94.
Solution
Exercise 2: Predict the error
Euler with has error 0.004 at some fixed end time. Roughly what error do you expect with ? And for RK4, if gives error , what does give?
Answer
Euler: about 0.001. RK4: about .
Solution
Exercise 3: Largest stable step
For , what is the largest step for which Euler does not blow up? Which makes the numerical solution jump to exactly 0 after one step?
Answer
(); gives factor .
Solution
For the solution still decays, but oscillates in sign, which the real solution never does.
Exercise 4: RK4 on cooling
Use RK4 with minute on , , and compare with the exact Newton's-cooling formula.
Answer
Both give °C; RK4 is off by only about °C.
Solution
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?
- 2
- 4
- 8
- 16
What does one Euler step for do?
- Moves along the tangent line:
- Averages four slopes
- Solves an equation for the next
- Integrates exactly
Euler on an undamped spring makes the amplitude…
- Stay exactly constant
- Shrink to zero
- Grow step by step
- Jump to infinity in one step