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:
Accuracy. How fast does the error go to zero as the step size shrinks?
Stability. For which step sizes does the method give bounded answers at all?
Cost. How many evaluations of the right-hand side does it take to reach a given accuracy?
The answers explain the list of method= options in solve_ivp, and when to pick each.
import time
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
from scipy.optimize import fsolveOrder of accuracy¶
Recall he logistic equation from the last section,
has the exact solution .
Forward Euler takes the step . The exact solution satisfies
so each step makes a local error of size . Reaching a fixed time takes steps, and the local errors add up to a global error of size . A method whose global error is is said to have order , so forward Euler has order 1.
Runge-Kutta methods¶
A Runge-Kutta method samples the slope 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:
Why does this help? Expanding in a Taylor series about gives , where and its partial derivatives and are evaluated at . So
The exact solution has and, by the chain rule, , so this agrees with the Taylor series through the term. The local error is , 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 term. It uses four slopes:
Every explicit Runge-Kutta method has the same structure. Stage evaluates at time and state , and the step combines the stages with weights . The coefficients are collected in a Butcher tableau
so a single function can implement all of them.
def rk_step(f, t, y, h, tableau):
"""
one step of the explicit Runge-Kutta method with Butcher tableau (A, b, c)
"""
A, b, c = tableau
k = []
for i in range(len(b)):
yi = y + h * sum(A[i][j] * k[j] for j in range(i))
k.append(f(t + c[i] * h, yi))
return y + h * sum(bi * ki for bi, ki in zip(b, k))
def rk_solve(f, t_span, y0, h, tableau):
"""
integrate y' = f(t, y) over t_span with fixed step h
returns arrays t (n+1,) and y (n+1, ...), a stripped-down solve_ivp
"""
t0, t1 = t_span
n = int(round((t1 - t0) / h))
t = t0 + h * np.arange(n + 1)
y = [np.asarray(y0, dtype=float)]
for k in range(n):
y.append(rk_step(f, t[k], y[-1], h, tableau))
return t, np.array(y)
# A b c
EULER = ([[0]], [1], [0])
MIDPOINT = ([[0, 0], [1/2, 0]], [0, 1], [0, 1/2])
RK4 = ([[0, 0, 0, 0], [1/2, 0, 0, 0], [0, 1/2, 0, 0], [0, 0, 1, 0]],
[1/6, 1/3, 1/3, 1/6], [0, 1/2, 1/2, 1])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 , not just at the final time.
f = lambda t, y: y * (1 - y)
exact = lambda t: 1 / (1 + 9 * np.exp(-t))
T = 10.0
hs = 2.0 ** -np.arange(1, 12)
methods = {"forward Euler": EULER, "midpoint": MIDPOINT, "RK4": RK4}
errors = {}
for name, tableau in methods.items():
errs = []
for h in hs:
t, y = rk_solve(f, (0, T), 0.1, h, tableau)
errs.append(np.max(np.abs(y - exact(t))))
errors[name] = np.array(errs)
plt.figure(figsize=(6, 4))
for name, err in errors.items():
keep = err > 1e-12 # leave out the points sitting on the round-off floor
p = np.polyfit(np.log(hs[keep]), np.log(err[keep]), 1)[0]
plt.loglog(hs, err, 'o-', label=f'{name} (slope {p:.2f})')
plt.xlabel('step size $h$')
plt.ylabel('max error on $[0, 10]$')
plt.legend()
plt.title('global error of fixed-step methods')
plt.show()The slopes are 1, 2 and 4, as promised. RK4 runs into round-off around 10-15, where shrinking stops helping (compare the error plot in Differentiation).
Accuracy per unit of work¶
Higher order costs more per step: RK4 evaluates four times per step, forward Euler once. The fair comparison is error against the total number of function evaluations, a work-precision diagram.
stages = {"forward Euler": 1, "midpoint": 2, "RK4": 4}
plt.figure(figsize=(6, 4))
for name, err in errors.items():
nfev = stages[name] * T / hs
plt.loglog(nfev, err, 'o-', label=name)
plt.xlabel('function evaluations')
plt.ylabel('max error on $[0, 10]$')
plt.legend()
plt.title('work-precision diagram')
plt.show()
for name, err in errors.items():
nfev = stages[name] * T / hs
first = np.nonzero(err < 1e-4)[0][0] # coarsest step with error below 1e-4
print(f"{name:14}: {nfev[first]:6.0f} evaluations for an error below 1e-4")Unless 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 ):
We can write the second-derivatives as a first-order system for position and velocity :
The planet moves fast near the star and slowly far away. We start it at closest approach on an orbit of eccentricity and period .
def kepler(t, y):
"""
right-hand side of the Kepler problem, y = (q1, q2, p1, p2)
"""
q, p = y[:2], y[2:]
return np.concatenate([p, -q / np.linalg.norm(q)**3])
def kepler_initial(e):
"""
closest approach on an orbit with eccentricity e and period 2*pi (energy -1/2)
"""
return np.array([1 - e, 0.0, 0.0, np.sqrt((1 + e) / (1 - e))])
period = 2 * np.pi
y0 = kepler_initial(0.9)
sol = solve_ivp(kepler, (0, 3 * period), y0, rtol=1e-8, atol=1e-10)
steps = np.diff(sol.t) # time step size is stored in sol.t
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
ax[0].plot(sol.y[0], sol.y[1], '.-', ms=3, lw=0.5)
ax[0].plot(0, 0, 'k*', ms=12)
ax[0].set_aspect('equal')
ax[0].set_title('orbit with $e = 0.9$ (each dot is a step)')
ax[1].semilogy(sol.t[:-1], steps, label='step size')
ax[1].semilogy(sol.t, np.linalg.norm(sol.y[:2], axis=0), label='distance to the star')
ax[1].set_xlabel('$t$')
ax[1].legend()
plt.show()
print(f"{len(steps)} steps; largest / smallest step = {steps.max() / steps.min():.0f}")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 .
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
with our initial condtion the energy is , here is the energy error after 100 orbits.
def kepler_energy(y):
"""
kinetic plus potential energy; y can be one state or a (4, n) array of states
"""
q, p = y[:2], y[2:]
return 0.5 * np.sum(p**2, axis=0) - 1 / np.linalg.norm(q, axis=0)
for rtol in [1e-3, 1e-6, 1e-9]:
s = solve_ivp(kepler, (0, 100 * period), y0, rtol=rtol, atol=1e-3 * rtol)
drift = kepler_energy(s.y[:, -1]) - kepler_energy(y0)
r_end = np.linalg.norm(s.y[:2, -1])
print(f"rtol = {rtol:.0e}: {s.nfev:7d} f evals, energy error {drift:+.1e}, "
f"final distance {r_end:.2e}")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
whose solution decays when . Forward Euler gives , so , which decays only if . For real that means .
lam = -50.0
fig, ax = plt.subplots(1, 3, figsize=(14, 3.5))
for a, h in zip(ax, [0.01, 0.03, 0.045]):
t, y = rk_solve(lambda t, y: lam * y, (0, 1), 1.0, h, EULER)
a.plot(t, y, 'o-', ms=3, label='forward Euler')
a.plot(t, np.exp(lam * t), 'k--', label='exact')
a.set_title(f'$h\\lambda = {h * lam:.2f}$')
a.set_xlabel('$t$')
ax[0].legend()
plt.show()Forward Euler blows up once , and shrinking the step here gives us stability.
Applied to the test equation, one step of any Runge-Kutta method multiplies by a stability function evaluated at . For explicit methods is a polynomial: for forward Euler, for the midpoint method, and for RK4, which are truncated Taylor series of . The stability region is the set of complex with . We allow complex because oscillating solutions (rotations, waves) have complex eigenvalues.
For a linear system with a diagonalizable matrix , the new unknowns satisfy the decoupled equations . So the method is stable when lies in the stability region for every eigenvalue of . For a nonlinear system, the eigenvalues of the Jacobian play the role of near a given solution.
xr, xi = np.meshgrid(np.linspace(-5, 3, 400), np.linspace(-4, 4, 400))
z = xr + 1j * xi
R = {
"forward Euler": 1 + z,
"midpoint": 1 + z + z**2 / 2,
"RK4": 1 + z + z**2 / 2 + z**3 / 6 + z**4 / 24,
"backward Euler": 1 / (1 - z),
}
fig, ax = plt.subplots(figsize=(6, 6))
for (name, Rz), color in zip(R.items(), ['C0', 'C1', 'C2', 'C3']):
ax.contour(xr, xi, np.abs(Rz), levels=[1], colors=color)
ax.plot([], [], color=color, label=name) # legend entry for the contour
ax.axhline(0, color='gray', lw=0.5)
ax.axvline(0, color='gray', lw=0.5)
ax.set_aspect('equal')
ax.set_xlabel(r'Re$(h\lambda)$')
ax.set_ylabel(r'Im$(h\lambda)$')
ax.legend(loc='upper left')
ax.set_title('boundaries $|R(z)| = 1$ of the stability regions')
plt.show()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,
so for the test equation and .
For backward Euler the stable region is the outside of the circle around . 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 appears on both sides of the update, so every step requires solving a (generally nonlinear) system of equations
for . We hand it to fsolve from Root Finding,
starting from the previous value , which is close to the root when 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 ourselves.
def backward_euler(f, t_span, y0, h, tol=1e-10):
"""
backward Euler with fixed step h
each step solves G(Y) = Y - y_n - h f(t_{n+1}, Y) = 0 with fsolve,
starting from the previous value y_n, and raises an error if the
residual |G(Y)| is larger than tol * (1 + |Y|)
"""
t0, t1 = t_span
n = int(round((t1 - t0) / h))
t = t0 + h * np.arange(n + 1)
y = [np.atleast_1d(np.asarray(y0, dtype=float))]
for k in range(n):
G = lambda Y: Y - y[-1] - h * f(t[k + 1], Y)
Y, info, ier, msg = fsolve(G, y[-1], full_output=True)
if np.linalg.norm(info['fvec']) > tol * (1 + np.linalg.norm(Y)):
raise RuntimeError(f"fsolve failed at step {k + 1}: {msg}")
y.append(Y)
return t, np.array(y)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 inside its stability region for them, at every step, forever.
A clean example:
The exact solution is for every , a smooth and slowly varying function. But any deviation from decays like , and with an explicit method needs no matter how smooth the solution is.
lam = -1e4
f_pr = lambda t, y: lam * (y - np.cos(t)) - np.sin(t)
print(f"{'method':8} {'steps':>7} {'f evals':>8} {'max error':>10} {'time':>8}")
for method in ["RK45", "DOP853", "Radau", "BDF", "LSODA"]:
start = time.perf_counter()
s = solve_ivp(f_pr, (0, 10), [1.0], method=method, rtol=1e-6, atol=1e-9)
elapsed = time.perf_counter() - start
err = np.max(np.abs(s.y[0] - np.cos(s.t)))
print(f"{method:8} {len(s.t) - 1:7d} {s.nfev:8d} {err:10.1e} {elapsed:7.3f}s")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:
for h in [0.1, 0.01]:
t, y = backward_euler(f_pr, (0, 10), 1.0, h)
print(f"backward Euler, h = {h}: {len(t) - 1:5d} steps, "
f"max error {np.max(np.abs(y[:, 0] - np.cos(t))):.1e}")h=1e-4
t, y = rk_solve(f_pr, (0, 0.5), 1.0, h, EULER)
print(f"forward Euler, h = {h}: {len(t) - 1:5d} steps, "
f"max error {np.max(np.abs(y - np.cos(t))):.1e}")Backward Euler is only first order, so it needs a hundred steps for an error of , 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 and momenta , and the dynamics are generated by a single scalar function , the Hamiltonian, through Hamilton’s equations
In mechanics is the total energy. For a particle of unit mass,
(kinetic plus potential energy), and Hamilton’s
equations become , , which is
Newton’s second law. The Kepler problem has , and is
kepler_energy above.
def kepler(t, y):
"""
right-hand side of the Kepler problem, y = (q1, q2, p1, p2)
"""
q, p = y[:2], y[2:]
return np.concatenate([p, -q / np.linalg.norm(q)**3])
def kepler_energy(y):
"""
kinetic plus potential energy; y can be one state or a (4, n) array of states
"""
q, p = y[:2], y[2:]
return 0.5 * np.sum(p**2, axis=0) - 1 / np.linalg.norm(q, axis=0)
def kepler_initial(e):
"""
closest approach on an orbit with eccentricity e and period 2*pi (energy -1/2)
"""
return np.array([1 - e, 0.0, 0.0, np.sqrt((1 + e) / (1 - e))])The Hamiltonian is constant along every solution (as long as it does not depend on explicitly), by the chain rule:
The exact flow has a second, less obvious property: it is symplectic. With one degree of freedom (a single and ) this means it preserves area in the 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 is the velocity Verlet method:
where is the acceleration, for the Kepler problem. Verlet is a second order method.
def velocity_verlet(accel, q0, p0, h, n):
"""
n steps of velocity Verlet for q'' = accel(q); returns positions and velocities
"""
q, p = np.array(q0, dtype=float), np.array(p0, dtype=float)
Q, P = [q], [p]
a = accel(q)
for _ in range(n):
p_half = p + 0.5 * h * a
q = q + h * p_half
a = accel(q)
p = p_half + 0.5 * h * a
Q.append(q)
P.append(p)
return np.array(Q), np.array(P)
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 for three periods, all with the same step , i.e. 2000 steps per orbit. The exact orbit (dashed) is an ellipse with the star at one focus.
e = 0.5
y0 = kepler_initial(e)
steps_per_orbit = 2000
h = period / steps_per_orbit
n = 3 * steps_per_orbit # three orbits
accel = lambda q: -q / np.linalg.norm(q)**3
_, Y_fe = rk_solve(kepler, (0, n * h), y0, h, EULER)
_, Y_be = backward_euler(kepler, (0, n * h), y0, h)
Q, P = velocity_verlet(accel, y0[:2], y0[2:], h, n)
orbits = {"forward Euler": Y_fe, "backward Euler": Y_be, "velocity Verlet": np.hstack([Q, P])}
s = np.linspace(0, 2 * np.pi, 400)
fig, ax = plt.subplots(1, 3, figsize=(14, 4.5), sharex=True, sharey=True)
for a, (name, Y) in zip(ax, orbits.items()):
a.plot(np.cos(s) - e, np.sqrt(1 - e**2) * np.sin(s), 'k--', lw=1)
a.plot(Y[:, 0], Y[:, 1], lw=1)
a.plot(0, 0, 'k*', ms=10)
a.set_aspect('equal')
a.set_title(name)
plt.show()
for name, Y in orbits.items():
print(f"{name:15}: largest energy error {np.max(np.abs(kepler_energy(Y.T) + 0.5)):.1e}")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 change , and the drift changes . Their Jacobian matrices
have determinant 1, so every substep preserves area. Forward Euler instead updates both variables at once, , and its Jacobian determinant is . With , every step expands area a little, and the computed solution spirals outwards. For backward Euler the determinant is , 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.
y0 = kepler_initial(0.5)
h = period / 60
n = 500 * 60 # 500 orbits, 60 steps per orbit
t = h * np.arange(n + 1)
Q, P = velocity_verlet(lambda q: -q / np.linalg.norm(q)**3, y0[:2], y0[2:], h, n)
E_verlet = kepler_energy(np.vstack([Q.T, P.T]))
_, Y = rk_solve(kepler, (0, n * h), y0, h, RK4)
E_rk4 = kepler_energy(Y.T)
plt.figure(figsize=(8, 4))
plt.plot(t / period, E_rk4 + 0.5, label='RK4 (4 force evaluations per step)')
plt.plot(t / period, E_verlet + 0.5, label='velocity Verlet (1 per step)', alpha=0.7)
plt.xlabel('number of orbits')
plt.ylabel('energy error')
plt.legend()
plt.title('energy error with the same step size')
plt.show()Verlet’s energy error oscillates within each orbit, but it does not grow. Being symplectic does not make Verlet conserve exactly.
Choosing a method in solve_ivp¶
method | type | order | use it for |
|---|---|---|---|
RK45 (default) | explicit Runge-Kutta, adaptive | 5(4) | non-stiff problems, moderate accuracy |
DOP853 | explicit Runge-Kutta, adaptive | 8 | non-stiff problems, high accuracy |
Radau | implicit Runge-Kutta | 5 | stiff problems, high accuracy |
BDF | implicit multistep | 1 to 5 | stiff problems, large systems |
LSODA | switches between Adams (explicit) and BDF (implicit) | variable | when you do not know whether the problem is stiff |
Some rules of thumb:
Set
rtolandatolexplicitly, and giveatolper component when the components have very different sizes.Check an answer by tightening the tolerances and confirming that nothing you care about changes.
If
RK45takes a huge number of steps on a solution that looks smooth, the problem is probably stiff. Switch toBDForRadauand pass the Jacobian.For long runs of conservative systems, monitor the conserved quantities, and consider a symplectic method such as Verlet (
solve_ivpdoes not have one).
Exercises¶
Exercise 1¶
The “3/8 rule” is another fourth-order Runge-Kutta method, with tableau
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?
# Your code hereExercise 2¶
For , find the largest stable fixed step size for forward Euler, the midpoint method and RK4 experimentally (for example by bisection on , declaring a run unstable if grows over 1000 steps). Compare with the points where the stability regions above cross the negative real axis.
# Your code hereExercise 3¶
The trapezoidal rule (Crank-Nicolson) is
Find its stability function and show that it is A-stable. What is its order?
Implement it (modify
backward_euler) and solve the Prothero-Robinson problem with starting from instead of 1, which puts the fast component in at full strength. Compare with backward Euler over the first few steps.Explain what you see using the limit of as for each method. (A method with there is called L-stable.)
# Your code hereExercise 4¶
The Van der Pol oscillator
becomes stiff as grows. Write it as a first-order system and solve it on
for with RK45, BDF, and LSODA, using
rtol=1e-6. Tabulate the number of function evaluations and the run time. Around which
does the stiff solver start to win? Plot for and describe the
two time scales you see.
# Your code hereExercise 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?
# Your code here