article
Notes on Numerical Integration of ODEs
Explicit Euler versus fourth-order Runge-Kutta on a test equation, and why accuracy and stability are separate questions.
Most simulations of physical systems reduce to the same task: advance an ordinary differential equation in small time steps of size . The choice of method decides how much accuracy a given step size buys, and whether the result stays bounded at all. These notes compare two standard methods on the simplest useful test problem.
The test equation
Consider with , whose exact solution is . Setting gives a decaying signal that is easy to check against.
Explicit Euler takes one slope evaluation per step:
On the test equation this becomes . The error made in one step is of order , and accumulated over a fixed time interval the global error is of order .
Classical Runge-Kutta (RK4) evaluates the slope four times per step:
and combines them into the next value:
Its global error is of order .
Measuring the order
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
exact = math.exp(-1.0)
for h in (0.1, 0.05, 0.025):
n = round(1.0 / h)
print(h, abs(euler(f, 0.0, 1.0, h, n) - exact), abs(rk4(f, 0.0, 1.0, h, n) - exact))
Absolute error at , from running this script:
| Step size | Euler | RK4 |
|---|---|---|
| 0.1 | ||
| 0.05 | ||
| 0.025 |
Halving roughly halves the Euler error and divides the RK4 error by about sixteen, consistent with first-order and fourth-order convergence.
Accuracy is not stability
For Euler on the test equation with real , the numerical solution decays only if , which means . With and the factor is , so the computed solution grows in magnitude and flips sign at every step, even though the true solution decays quickly.
Choosing a step size by asking how accurate the answer should be is only half the job. For fast decaying dynamics the step size may be limited by stability instead.
RK4 has a larger stability region than Euler, but it is also bounded. On the negative real axis it reaches about , so the step that makes Euler blow up is stable for RK4.
Stiff problems, where fast and slow dynamics coexist, usually call for implicit methods, which are outside the scope of these notes.