Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

ODE Solvers: Accuracy, Stability, and Stiffness

Open in Colab

In Initial Value Problems we handed ODEs to solve_ivp and wrote forward Euler by hand. Three questions decide whether a method is any good for a given problem:

  1. Accuracy. How fast does the error go to zero as the step size hh shrinks?

  2. Stability. For which step sizes does the method give bounded answers at all?

  3. Cost. How many evaluations of the right-hand side ff does it take to reach a given accuracy?

The answers explain the list of method= options in solve_ivp, and when to pick each.

Order of accuracy

Recall he logistic equation from the last section,

y′=f(t,y)=y(1−y),y(0)=0.1,y' = f(t,y) = y(1 - y), \qquad y(0) = 0.1,

has the exact solution y(t)=1/(1+9e−t)y(t) = 1/(1 + 9e^{-t}).

Forward Euler takes the step yn+1=yn+hf(tn,yn)y_{n+1} = y_n + h f(t_n, y_n). The exact solution satisfies

y(t+h)=y(t)+hy′(t)+h22y′′(t)+⋯ ,y(t + h) = y(t) + h y'(t) + \frac{h^2}{2} y''(t) + \cdots,

so each step makes a local error of size O(h2)O(h^2). Reaching a fixed time TT takes T/hT/h steps, and the local errors add up to a global error of size O(h)O(h). A method whose global error is O(hp)O(h^p) is said to have order pp, so forward Euler has order 1.

Runge-Kutta methods

A Runge-Kutta method samples the slope ff at a few points inside each step and combines the samples so that more terms of the Taylor series cancel. The midpoint method takes half an Euler step, evaluates the slope there, and uses that slope for the whole step:

k1=f(tn,yn),k2=f ⁣(tn+h2, yn+h2k1),yn+1=yn+hk2.k_1 = f(t_n, y_n), \qquad k_2 = f\!\left(t_n + \tfrac{h}{2},\ y_n + \tfrac{h}{2} k_1\right), \qquad y_{n+1} = y_n + h k_2 .

Why does this help? Expanding k2k_2 in a Taylor series about (tn,yn)(t_n, y_n) gives k2=f+h2(ft+fyf)+O(h2)k_2 = f + \tfrac h2 (f_t + f_y f) + O(h^2), where ff and its partial derivatives ftf_t and fyf_y are evaluated at (tn,yn)(t_n, y_n). So

yn+1=yn+hf+h22(ft+fyf)+O(h3).y_{n+1} = y_n + h f + \tfrac{h^2}{2} (f_t + f_y f) + O(h^3).

The exact solution has y′=fy' = f and, by the chain rule, y′′=ddtf(t,y(t))=ft+fyfy'' = \frac{d}{dt} f(t, y(t)) = f_t + f_y f, so this agrees with the Taylor series y(tn+h)=y+hy′+h22y′′+O(h3)y(t_n + h) = y + h y' + \tfrac{h^2}{2} y'' + O(h^3) through the h2h^2 term. The local error is O(h3)O(h^3), and the midpoint method has order 2.

The classical fourth-order method, RK4, is designed in the same way, to match the Taylor series through the h4h^4 term. It uses four slopes:

k1=f(tn,yn),k2=f ⁣(tn+h2, yn+h2k1),k3=f ⁣(tn+h2, yn+h2k2),k4=f(tn+h, yn+hk3),yn+1=yn+h6(k1+2k2+2k3+k4).\begin{aligned} k_1 &= f(t_n, y_n), & k_2 &= f\!\left(t_n + \tfrac{h}{2},\ y_n + \tfrac{h}{2}k_1\right),\\ k_3 &= f\!\left(t_n + \tfrac{h}{2},\ y_n + \tfrac{h}{2}k_2\right), & k_4 &= f(t_n + h,\ y_n + h k_3), \end{aligned} \qquad y_{n+1} = y_n + \tfrac{h}{6}\left(k_1 + 2k_2 + 2k_3 + k_4\right).

Every explicit Runge-Kutta method has the same structure. Stage ii evaluates ff at time tn+ciht_n + c_i h and state yn+h∑j<iaijkjy_n + h\sum_{j<i} a_{ij} k_j, and the step combines the stages with weights bib_i. The coefficients are collected in a Butcher tableau

cAb⊤\begin{array}{c|c} c & A \\ \hline & b^\top \end{array}

so a single function can implement all of them.

Now measure the error on a sequence of step sizes and read the order off the slope of a log-log plot, as in Convergence of Algorithms. We measure the largest error anywhere on [0,10][0, 10], not just at the final time.

The slopes are 1, 2 and 4, as promised. RK4 runs into round-off around 10-15, where shrinking hh stops helping (compare the error plot in Differentiation).

Accuracy per unit of work

Higher order costs more per step: RK4 evaluates ff four times per step, forward Euler once. The fair comparison is error against the total number of function evaluations, a work-precision diagram.

Unless ff is very cheap or the accuracy requirement very loose, the higher-order method wins by orders of magnitude. This is why the default in solve_ivp is a fifth-order method.

Adaptive step size

A fixed step is wasteful when the solution changes at different rates at different times. Take a planet on an elongated orbit around a star (units with GM=1GM = 1):

q′′=−q∥q∥3.\mathbf q'' = -\frac{\mathbf q}{\|\mathbf q\|^3}.

We can write the second-derivatives as a first-order system for position q\mathbf q and velocity p\mathbf p:

q′=p,p′=−q/∥q∥3.\mathbf q' = \mathbf p, \quad \mathbf p' = -\mathbf q / \|\mathbf q\|^3.

The planet moves fast near the star and slowly far away. We start it at closest approach on an orbit of eccentricity ee and period 2π2\pi.

The step size tracks the distance to the star and varies by three orders of magnitude. A fixed step small enough for the closest approach would be wasted on the rest of the orbit.

How does solve_ivp choose the step? The default method RK45 is an embedded Runge-Kutta method. From the same function evaluations it builds both a fifth-order and a fourth-order approximation, and their difference estimates the local error. If the estimate is below atol + rtol * |y| the step is accepted and the next one enlarged. Otherwise the step is rejected and retried with a smaller hh.

The default tolerances are loose. Unless told otherwise, solve_ivp uses rtol=1e-3 and atol=1e-6. These control the error made in each step, and those errors accumulate. The exact energy of the orbit is

12∥p∥2−1∥q∥\frac{1}{2} \| \mathbf p \|^2 - \frac{1}{\| \mathbf q \|}

with our initial condtion the energy is E0=−1/2E_0 = -1/2, here is the energy error after 100 orbits.

After a whole number of orbits the planet should be back at closest approach, at distance 0.1. The first line uses the default tolerances: the computed planet has crashed into the star (final distance essentially zero, energy off by many orders of magnitude), and nothing warned us. At rtol=1e-6 the energy is fine to four digits but the planet is in the wrong place on its orbit.

Stability

The model problem is the linear test equation

y′=λy,y(0)=1,y' = \lambda y, \qquad y(0) = 1,

whose solution eλte^{\lambda t} decays when Re⁡λ<0\operatorname{Re}\lambda < 0. Forward Euler gives yn+1=(1+hλ) yny_{n+1} = (1 + h\lambda)\, y_n, so yn=(1+hλ)ny_n = (1 + h\lambda)^n, which decays only if ∣1+hλ∣≤1|1 + h\lambda| \le 1. For real λ<0\lambda < 0 that means h≤2/∣λ∣h \le 2/|\lambda|.

Forward Euler blows up once ∣hλ∣>2|h\lambda| > 2, and shrinking the step here gives us stability.

Applied to the test equation, one step of any Runge-Kutta method multiplies yy by a stability function R(z)R(z) evaluated at z=hλz = h\lambda. For explicit methods RR is a polynomial: 1+z1 + z for forward Euler, 1+z+z2/21 + z + z^2/2 for the midpoint method, and 1+z+z2/2+z3/6+z4/241 + z + z^2/2 + z^3/6 + z^4/24 for RK4, which are truncated Taylor series of eze^z. The stability region is the set of complex zz with ∣R(z)∣≤1|R(z)| \le 1. We allow complex λ\lambda because oscillating solutions (rotations, waves) have complex eigenvalues.

For a linear system y′=Ayy' = Ay with a diagonalizable matrix A=VΛV−1A = V \Lambda V^{-1}, the new unknowns u=V−1yu = V^{-1} y satisfy the decoupled equations ui′=λiuiu_i' = \lambda_i u_i. So the method is stable when hλih\lambda_i lies in the stability region for every eigenvalue λi\lambda_i of AA. For a nonlinear system, the eigenvalues of the Jacobian ∂f/∂y\partial f/\partial y play the role of λ\lambda near a given solution.

Every explicit method has a bounded stability region, since a polynomial blows up at infinity.

Backward Euler evaluates the slope at the end of the step,

yn+1=yn+hf(tn+1,yn+1),y_{n+1} = y_n + h f(t_{n+1}, y_{n+1}),

so for the test equation yn+1=yn/(1−hλ)y_{n+1} = y_n / (1 - h\lambda) and R(z)=1/(1−z)R(z) = 1/(1 - z).

For backward Euler the stable region is the outside of the circle around z=1z = 1. It contains the entire left half-plane, so the decaying test equation is handled stably with any step size. Methods with this property are called A-stable.

The price is that yn+1y_{n+1} appears on both sides of the update, so every step requires solving a (generally nonlinear) system of equations

G(Y)=Y−yn−hf(tn+1,Y)=0G(Y) = Y - y_n - h f(t_{n+1}, Y) = 0

for Y=yn+1Y = y_{n+1}. We hand it to fsolve from Root Finding, starting from the previous value yny_n, which is close to the root when hh is small. fsolve does not raise an error when it fails, and its success flag ier sometimes reports a failure when it has found the root to round-off, so we check the residual ∥G(Y)∥\|G(Y)\| ourselves.

Stiffness

A problem is stiff when the step size of an explicit method is limited by stability rather than by accuracy. The usual cause is a system that contains some very fast, strongly damped components alongside the slow behavior you actually want to follow. The fast components die out almost immediately, but an explicit method must still keep hλh\lambda inside its stability region for them, at every step, forever.

A clean example:

y′(t)=λ (y−cos⁡t)−sin⁡t,λ≪−1,y(0)=1,y'(t) = \lambda\,\bigl(y - \cos t\bigr) - \sin t, \qquad \lambda \ll -1, \qquad y(0) = 1,

The exact solution is y(t)=cos⁡ty(t) = \cos t for every λ\lambda, a smooth and slowly varying function. But any deviation from cos⁡t\cos t decays like eλte^{\lambda t}, and with λ=−104\lambda = -10^4 an explicit method needs h≲3×10−4h \lesssim 3 \times 10^{-4} no matter how smooth the solution is.

All five methods reach the same accuracy. The explicit methods RK45 and DOP853 need tens of thousands of steps, almost all of them spent keeping a component that no longer exists stable. The implicit methods Radau and BDF need between twenty and a hundred or so. LSODA monitors the problem and switches to an implicit method when it detects stiffness.

Our backward Euler, with steps of 0.1 and 0.01:

Backward Euler is only first order, so it needs a hundred steps for an error of 5×10−65 \times 10^{-6}, but it is stable.

Long-time integration and conservation

Hamiltonian systems

The Kepler problem belongs to an important class of conservative systems. In a Hamiltonian system the state consists of positions q\mathbf q and momenta p\mathbf p, and the dynamics are generated by a single scalar function H(q,p)H(\mathbf q, \mathbf p), the Hamiltonian, through Hamilton’s equations

q′=∂H∂p,p′=−∂H∂q.\mathbf q' = \frac{\partial H}{\partial \mathbf p}, \qquad \mathbf p' = -\frac{\partial H}{\partial \mathbf q}.

In mechanics HH is the total energy. For a particle of unit mass,

H=12∥p∥2+V(q)H = \frac12 \|\mathbf p\|^2 + V(\mathbf q)

(kinetic plus potential energy), and Hamilton’s equations become q′=p\mathbf q' = \mathbf p, p′=−∇V(q)\mathbf p' = -\nabla V(\mathbf q), which is Newton’s second law. The Kepler problem has V(q)=−1/∥q∥V(\mathbf q) = -1/\|\mathbf q\|, and HH is kepler_energy above.

The Hamiltonian is constant along every solution (as long as it does not depend on tt explicitly), by the chain rule:

ddtH(q,p)=∂H∂q⋅q′+∂H∂p⋅p′=∂H∂q⋅∂H∂p−∂H∂p⋅∂H∂q=0.\frac{d}{dt} H(\mathbf q, \mathbf p) = \frac{\partial H}{\partial \mathbf q} \cdot \mathbf q' + \frac{\partial H}{\partial \mathbf p} \cdot \mathbf p' = \frac{\partial H}{\partial \mathbf q} \cdot \frac{\partial H}{\partial \mathbf p} - \frac{\partial H}{\partial \mathbf p} \cdot \frac{\partial H}{\partial \mathbf q} = 0 .

The exact flow has a second, less obvious property: it is symplectic. With one degree of freedom (a single qq and pp) this means it preserves area in the (q,p)(q, p) phase plane: a patch of initial conditions gets stretched and sheared as it moves, but its area never changes. With more degrees of freedom it preserves a sum of such areas. A numerical method whose step is a symplectic map is called a symplectic integrator.

Velocity Verlet

A standard symplectic integrator for H=12∥p∥2+V(q)H = \frac 12 \|\mathbf p\|^2 + V(\mathbf q) is the velocity Verlet method:

pn+1/2=pn+h2 a(qn),qn+1=qn+h pn+1/2,pn+1=pn+1/2+h2 a(qn+1),\mathbf p_{n+1/2} = \mathbf p_n + \frac{h}{2}\, \mathbf a(\mathbf q_n), \qquad \mathbf q_{n+1} = \mathbf q_n + h\, \mathbf p_{n+1/2}, \qquad \mathbf p_{n+1} = \mathbf p_{n+1/2} + \frac{h}{2}\, \mathbf a(\mathbf q_{n+1}),

where a(q)=−∇V(q)\mathbf a(\mathbf q) = -\nabla V(\mathbf q) is the acceleration, −q/∥q∥3-\mathbf q/\|\mathbf q\|^3 for the Kepler problem. Verlet is a second order method.

For a conservative system, small errors in each step can add up in a systematic direction. Here are forward Euler, backward Euler and velocity Verlet on the orbit of eccentricity e=0.5e = 0.5 for three periods, all with the same step h=2π/2000h = 2\pi/2000, i.e. 2000 steps per orbit. The exact orbit (dashed) is an ellipse with the star at one focus.

Even with 2000 steps per orbit, forward Euler gains energy on every orbit and spirals outward, while backward Euler loses energy and spirals in toward the star. Velocity Verlet, at the same cost per step as forward Euler, stays on the orbit.

Why is Verlet symplectic? Take one degree of freedom. Each of the three substeps changes one variable by an amount that depends only on the other: the half kicks (q,p)↦(q, p+h2a(q))(q, p) \mapsto \bigl(q,\ p + \tfrac h2 a(q)\bigr) change pp, and the drift (q,p)↦(q+hp, p)(q, p) \mapsto (q + hp,\ p) changes qq. Their Jacobian matrices

(10h2a′(q)1),(1h01)\begin{pmatrix} 1 & 0 \\ \tfrac h2 a'(q) & 1 \end{pmatrix}, \qquad \begin{pmatrix} 1 & h \\ 0 & 1 \end{pmatrix}

have determinant 1, so every substep preserves area. Forward Euler instead updates both variables at once, (q,p)↦(q+hp, p+ha(q))(q, p) \mapsto \bigl(q + hp,\ p + h a(q)\bigr), and its Jacobian determinant is 1−h2a′(q)1 - h^2 a'(q). With a′(q)<0a'(q) < 0, every step expands area a little, and the computed solution spirals outwards. For backward Euler the determinant is 1/(1+h2a′(q))1/(1 + h^2 a'(q)), and the solution spirals inwards.

Here is RK4, fourth order with four force evaluations per step, against Verlet over 500 orbits with 60 steps per orbit.

Verlet’s energy error oscillates within each orbit, but it does not grow. Being symplectic does not make Verlet conserve HH exactly.

Choosing a method in solve_ivp

methodtypeorderuse it for
RK45 (default)explicit Runge-Kutta, adaptive5(4)non-stiff problems, moderate accuracy
DOP853explicit Runge-Kutta, adaptive8non-stiff problems, high accuracy
Radauimplicit Runge-Kutta5stiff problems, high accuracy
BDFimplicit multistep1 to 5stiff problems, large systems
LSODAswitches between Adams (explicit) and BDF (implicit)variablewhen you do not know whether the problem is stiff

Some rules of thumb:

  • Set rtol and atol explicitly, and give atol per component when the components have very different sizes.

  • Check an answer by tightening the tolerances and confirming that nothing you care about changes.

  • If RK45 takes a huge number of steps on a solution that looks smooth, the problem is probably stiff. Switch to BDF or Radau and pass the Jacobian.

  • For long runs of conservative systems, monitor the conserved quantities, and consider a symplectic method such as Verlet (solve_ivp does not have one).

Exercises

Exercise 1

The “3/8 rule” is another fourth-order Runge-Kutta method, with tableau

01/31/32/3−1/3111−111/83/83/81/8\begin{array}{c|cccc} 0 & & & & \\ 1/3 & 1/3 & & & \\ 2/3 & -1/3 & 1 & & \\ 1 & 1 & -1 & 1 & \\ \hline & 1/8 & 3/8 & 3/8 & 1/8 \end{array}

Add it to rk_solve, verify that it has order 4, and compare its error constant with that of classical RK4 on the logistic problem. Does it have the same stability function?

Exercise 2

For y′=−100yy' = -100 y, find the largest stable fixed step size for forward Euler, the midpoint method and RK4 experimentally (for example by bisection on hh, declaring a run unstable if ∣y∣|y| grows over 1000 steps). Compare with the points where the stability regions above cross the negative real axis.

Exercise 3

The trapezoidal rule (Crank-Nicolson) is

yn+1=yn+h2(f(tn,yn)+f(tn+1,yn+1)).y_{n+1} = y_n + \tfrac{h}{2}\bigl(f(t_n, y_n) + f(t_{n+1}, y_{n+1})\bigr).
  1. Find its stability function R(z)R(z) and show that it is A-stable. What is its order?

  2. Implement it (modify backward_euler) and solve the Prothero-Robinson problem with h=0.1h = 0.1 starting from y(0)=2y(0) = 2 instead of 1, which puts the fast component in at full strength. Compare with backward Euler over the first few steps.

  3. Explain what you see using the limit of R(z)R(z) as z→−∞z \to -\infty for each method. (A method with R(z)→0R(z) \to 0 there is called L-stable.)

Exercise 4

The Van der Pol oscillator

x′′−μ(1−x2) x′+x=0x'' - \mu (1 - x^2)\, x' + x = 0

becomes stiff as μ\mu grows. Write it as a first-order system and solve it on t∈[0,3μ]t \in [0, 3\mu] for μ=1,10,100,1000\mu = 1, 10, 100, 1000 with RK45, BDF, and LSODA, using rtol=1e-6. Tabulate the number of function evaluations and the run time. Around which μ\mu does the stiff solver start to win? Plot x(t)x(t) for μ=1000\mu = 1000 and describe the two time scales you see.

Exercise 5

Repeat the long-time orbit experiment at equal cost: give RK4 a step four times larger than Verlet’s so both use the same number of force evaluations. Besides the energy, look at the phase error, the angle between the computed and the exact position after 500 orbits. Which method is better for which quantity?