Solving ODEs on a computer

Most differential equations cannot be solved with a formula. So we march forward in small steps — carefully.

⏱ 22 minNeeds: Chapters 2 and 53 simulations
In plain words

You are walking in fog and can only see the slope under your feet. Take a small step in that direction, look again, take another step. That is Euler's method. Smarter walkers peek at the slope a little ahead before committing — that is Runge–Kutta. And if your steps are too long on a steep hill, you overshoot wildly — that is instability.

You will learn
Level 1 · basicEuler's method step by step Level 2 · standardRunge–Kutta methods; order and convergence Level 3 · advancedStability and stiff problems
Simplest example first · when Euler's method is exact

For $y' = 2$, $y(0) = 1$ the slope never changes, so walking along the slope is perfect: with step $h = 1$, Euler gives $y_1 = 1 + 1\cdot2 = 3$, $y_2 = 3 + 2 = 5$, $y_3 = 7$ — exactly $1 + 2t$. Errors appear only when the slope changes during a step. For $y' = y$, $y(0) = 1$ (exact $e^t$) with $h = 1$: $y_1 = 1 + 1 = 2$ but $e \approx 2.718$; Euler used the old, smaller slope for the whole step. Smaller steps reduce the error — that is the whole story of this chapter.

1. Euler's method

We want $y(t)$ with $y' = f(t, y)$, $y(t_0) = y_0$. Choose a step size $h$ and grid times $t_n = t_0 + nh$. Taylor's theorem gives $y(t_{n+1}) = y(t_n) + h\,y'(t_n) + O(h^2)$. Drop the $O(h^2)$ and use the ODE (Ordinary Differential Equation) for $y'$:

Definition · Explicit (forward) Euler method

$$y_{n+1} = y_n + h\, f(t_n, y_n), \qquad n = 0, 1, 2, \dots$$ where $y_n$ is the computed approximation of $y(t_n)$.

Iserles, A First Course in the Numerical Analysis of Differential Equations, 2nd ed., CUP (2009), chapter 1 "Euler's method and beyond".
Example by hand

$y' = y$, $y(0) = 1$, $h = 0.5$. Then $y_1 = 1 + 0.5\cdot 1 = 1.5$ and $y_2 = 1.5 + 0.5\cdot1.5 = 2.25$. The exact value is $y(1) = e \approx 2.718$. Error $0.47$. With $h = 0.1$ (10 steps) we get $1.1^{10} \approx 2.594$, error $0.12$ — about 4 times smaller for 5 times the work. Euler is simple but slow to converge.

2. Runge–Kutta methods: look before you leap

Animation: Euler steps spiral outward and gain energy; RK4 steps stay on the exact circle.
Watch: Same step size, two methods. Euler (red) gains energy every cycle; RK4 (green) stays on the exact orbit.

Runge–Kutta methods evaluate the slope at several trial points inside each step and combine them. Heun's method (RK2 (second-order Runge–Kutta method)) averages the slope at the start and at an Euler-predicted end point. The classical fourth-order method (RK4 (classical fourth-order Runge–Kutta method)) uses four slopes:

Definition · Classical Runge–Kutta method (RK4)

$$\begin{aligned} k_1 &= f(t_n, y_n), & k_2 &= f\big(t_n + \tfrac h2,\ y_n + \tfrac h2 k_1\big),\\ k_3 &= f\big(t_n + \tfrac h2,\ y_n + \tfrac h2 k_2\big), & k_4 &= f(t_n + h,\ y_n + h k_3), \end{aligned}$$ $$y_{n+1} = y_n + \frac h6\,(k_1 + 2k_2 + 2k_3 + k_4).$$

Butcher, Numerical Methods for Ordinary Differential Equations, 3rd ed., Wiley (2016); Hairer, Nørsett & Wanner, Solving Ordinary Differential Equations I, 2nd ed., Springer (1993), chapter II.
Euler vs Heun vs RK4y′ = y·cos t, y(0) = 1, exact y = e^(sin t)
exactEuler (order 1)Heun RK2 (order 2)RK4 (order 4)
RK4 costs four slope evaluations per step, Euler one. Even so, RK4 is far more accurate for the same total work — it can take much bigger steps.

3. Error, order and convergence

The local truncation error is the error made in one step assuming we started on the exact solution. The global error $e_n = y(t_n) - y_n$ is what accumulates by the final time. A method has order $p$ if its global error is $O(h^p)$.

Theorem · Convergence of Euler's method

Let $f$ be continuous and satisfy a Lipschitz condition $|f(t,y) - f(t,z)| \le L|y - z|$, and let the exact solution have a bounded second derivative, $|y''| \le M$, on $[t_0, T]$. Then the Euler approximations satisfy $$|y(t_n) - y_n| \le \frac{hM}{2L}\left(e^{L(t_n - t_0)} - 1\right).$$ So the global error is $O(h)$: Euler is first order. Heun is second order and RK4 fourth order.

Burden, Faires & Burden, Numerical Analysis, 10th ed., Cengage (2016), chapter 5 "Initial-Value Problems for Ordinary Differential Equations", error bound for Euler's method; Iserles (2009), chapter 1.
Measuring the orderglobal error at t = 6 against step size
EulerHeunRK4
On a log-log scale the slope of each line is the order $p$. The readout estimates $p$ from the two smallest steps: $p \approx \log_2(e_{2h}/e_h)$. This "halve $h$ and see" test is how researchers check their codes.

4. Stability: when small steps are not small enough

Apply Euler to the test equation $y' = \lambda y$ with $\lambda < 0$ (the exact solution decays): $$y_{n+1} = y_n + h\lambda y_n = (1 + h\lambda)\,y_n \quad\Longrightarrow\quad y_n = (1 + h\lambda)^n y_0.$$ This decays only if $|1 + h\lambda| \le 1$, i.e. $h \le 2/|\lambda|$. With a larger step, the numerical solution oscillates and explodes — even though the true solution quietly decays to zero.

Definition · Absolute stability region

Applying a one-step method to $y' = \lambda y$ gives $y_{n+1} = R(z)\,y_n$ with $z = h\lambda$. The method is absolutely stable for $z$ with $|R(z)| \le 1$. Forward Euler: $R(z) = 1 + z$ (a disc of radius 1 centred at $-1$). Backward Euler $y_{n+1} = y_n + h f(t_{n+1}, y_{n+1})$: $R(z) = 1/(1 - z)$, stable for every $z$ with negative real part (A-stable).

Dahlquist, "A special stability problem for linear multistep methods", BIT 3 (1963) 27–43; LeVeque, Finite Difference Methods for ODEs and PDEs, SIAM (2007), chapter 7 "Absolute Stability for Ordinary Differential Equations".
Explicit vs implicit Euler on a fast decayy′ = λy, y(0) = 1
exact e^(λt)forward (explicit) Eulerbackward (implicit) Euler
Push $h$ past $2/|\lambda|$ and forward Euler blows up; backward Euler stays calm at every step size. Implicit methods must solve an equation each step (more work), but for stiff problems they are the only practical choice.
Real world · stiffness

A problem is stiff when it mixes very fast and very slow processes: chemical kinetics with fast and slow reactions, circuits, combustion, the semi-discretised heat equation (Chapter 8). Explicit methods are forced to tiny steps by the fastest process even after it has died out. Production codes (MATLAB's ode15s, SciPy's solve_ivp(method="BDF")) use implicit methods for such problems. The same stiffness also makes PINN training hard (Krishnapriyan et al., NeurIPS 2021).

Principle · Convergence = consistency + stability

A method is consistent if its local error vanishes as $h\to0$ faster than $h$. Dahlquist's equivalence theorem says that for linear multistep methods, convergence is equivalent to consistency plus (zero-)stability. The same principle for PDEs is the Lax equivalence theorem (Chapter 8).

Dahlquist, "Convergence and stability in the numerical integration of ordinary differential equations", Math. Scand. 4 (1956) 33–53; Iserles (2009), chapter 2.
Connection to SciML

A residual network (ResNet) layer $\mathbf x_{k+1} = \mathbf x_k + h\,\sigma(W_k\mathbf x_k + \mathbf b_k)$ is exactly one Euler step of an ODE — the observation behind neural ODEs (Chen et al., 2018) and E, "A proposal on machine learning via dynamical systems", Commun. Math. Stat. 5 (2017) 1–11. Numerical solvers also produce the training data for surrogate models and neural operators (Chapter 18).

5. Try it in Python

import numpy as np
import matplotlib.pyplot as plt

f = lambda t, y: y * np.cos(t)
exact = lambda t: np.exp(np.sin(t))
T = 6.0

def euler(h):
    t, y = 0.0, 1.0
    for _ in range(round(T / h)): y += h * f(t, y); t += h
    return y

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

hs = T / 2**np.arange(3, 11)
eE = [abs(euler(h) - exact(T)) for h in hs]
eR = [abs(rk4(h) - exact(T)) for h in hs]
plt.loglog(hs, eE, "o-", label="Euler"); plt.loglog(hs, eR, "s-", label="RK4")
plt.xlabel("h"); plt.ylabel("error at t = 6"); plt.legend(); plt.grid(alpha=.3); plt.show()
print("observed order Euler: %.2f   RK4: %.2f" % (np.log2(eE[-2]/eE[-1]), np.log2(eR[-3]/eR[-2])))

Forward Euler for $y' = -50y$. Which step size is stable?

Right: stability needs $h \le 2/50 = 0.04$. Only $0.03$ qualifies.

A fourth-order method gives error $10^{-4}$ with step $h$. Roughly what error with step $h/10$?

Right: $(1/10)^4 = 10^{-4}$, so $10^{-4}\times10^{-4} = 10^{-8}$ (until round-off interferes).

Limitations, and where this leads

Each new initial condition or parameter means a new run; stiff problems force implicit solves; and fitting unknown parameters to data needs many runs inside an optimisation loop. Chapter 9 looks at these limits honestly, and at how SciML methods address them by building on what you learned here. Go to Chapter 9 →

Key takeaways

Further reading