Adaptive Step Size
A fixed step size is a poor compromise: small enough for the hardest part of the solution, it wastes effort everywhere else. Adaptive solvers estimate the local error at each step and adjust to keep it near a tolerance, taking big steps where the solution is smooth and small ones where it changes quickly. This is what solve_ivp does by default.
Estimating the error: embedded pairs
An embedded pair computes two solutions of different orders, and , from the same stages. Their difference estimates the local error of the lower-order one at almost no extra cost. The simplest pair combines Euler (order 1) and Heun (order 2):
Production pairs are Bogacki-Shampine 3(2) (RK23), Dormand-Prince 5(4) (RK45) and an 8th-order pair (DOP853).
Choosing the next step
If is below the tolerance , the step is accepted; either way, the next step is chosen so the predicted error equals . Since the local error of the order- method scales like :
with a safety factor to 0.9 and limits on how much may grow or shrink at once. Rejected steps are retried with the smaller .
import numpy as np
def rk12_adaptive(f, a, b, u0, tol):
t, u, h = a, np.array(u0, float), 0.01
ts, us, rejected = [t], [u.copy()], 0
while t < b:
h = min(h, b - t)
k1 = f(t, u); k2 = f(t + h, u + h * k1)
E = h / 2 * np.linalg.norm(k2 - k1)
if E <= tol: # accept, keep the 2nd-order value
t, u = t + h, u + h / 2 * (k1 + k2)
ts.append(t); us.append(u.copy())
else:
rejected += 1
h *= min(4.0, max(0.2, 0.8 * (tol / max(E, 1e-300)) ** 0.5))
return np.array(ts), np.array(us), rejected
# a decaying system hit by a short, strong pulse of forcing around t = 5
f = lambda t, u: np.array([-u[0] + 10 * np.exp(-((t - 5) / 0.1) ** 2)])
ts, us, rej = rk12_adaptive(f, 0, 10, [1.0], 1e-7)
steps = np.diff(ts)
print(f"{len(ts) - 1} accepted steps, {rej} rejected")
print(f"step size near t = 2: {steps[np.searchsorted(ts, 2.0)]:.2e}, near t = 5: {steps[np.searchsorted(ts, 5.0)]:.2e}")
from scipy.integrate import solve_ivp
ref = solve_ivp(f, (0, 10), [1.0], rtol=1e-12, atol=1e-14, max_step=0.01).y[0, -1]
print(f"u(10) = {us[-1, 0]:.6f}, reference {ref:.6f}")
18924 accepted steps, 6 rejected
step size near t = 2: 9.73e-04, near t = 5: 1.18e-04
u(10) = 0.012018, reference 0.012018
The step size shrinks where the pulse acts and grows again where the solution varies slowly.
Tolerances in solve_ivp
The solver keeps each component's estimated local error below . Two cautions:
- The defaults (, ) give only about 3 digits. Set them explicitly.
- Tolerances control the local error per step; the global error can be larger (for unstable problems, much larger). Check by tightening the tolerances and comparing.
import numpy as np
from scipy.integrate import solve_ivp
f = lambda t, u: [u[1], -u[0]]
exact = np.cos(30.0)
for rtol in (1e-3, 1e-6, 1e-9, 1e-12):
for method in ("RK45", "DOP853"):
sol = solve_ivp(f, (0, 30), [1.0, 0.0], method=method, rtol=rtol, atol=rtol * 1e-3)
print(f"rtol {rtol:.0e} {method:6s}: error {abs(sol.y[0, -1] - exact):.1e}, evaluations {sol.nfev}")rtol 1e-03 RK45 : error 8.7e-03, evaluations 212
rtol 1e-03 DOP853: error 1.7e-03, evaluations 206
rtol 1e-06 RK45 : error 8.8e-07, evaluations 1082
rtol 1e-06 DOP853: error 2.2e-06, evaluations 398
rtol 1e-09 RK45 : error 2.2e-10, evaluations 3794
rtol 1e-09 DOP853: error 2.2e-09, evaluations 878
rtol 1e-12 RK45 : error 4.5e-13, evaluations 14792
rtol 1e-12 DOP853: error 2.1e-12, evaluations 2042
For tight tolerances the 8th-order DOP853 needs far fewer evaluations than RK45.
In software
solve_ivp(..., rtol=..., atol=...)andsol.nfev,sol.t(the accepted step points);first_stepandmax_stepconstrain the step size.max_stepmatters when the right-hand side has short features the solver might step over (a brief forcing pulse): with large steps it may never "see" them.
Exercises
Exercise 1: Step-size update
A 4th-order method's estimated local error is with , and the tolerance is . Suggest the new (safety factor 0.9).
Answer
About .
Solution
(local error of an order-4 method scales like ).
Exercise 2: Local versus global
Why can the global error exceed the tolerance even when every step is accepted?
Answer
Local errors accumulate and can be amplified by the dynamics.
Solution
The tolerance bounds each step's new error; the global error is the sum of these, propagated by the ODE, which can grow them (by up to ).
Exercise 3: Missing a pulse (code)
Integrate , , to with default solve_ivp settings and again with max_step=0.01. The exact final value is .
Answer
With defaults the solver steps over the pulse and returns about ; with max_step it gets .
Solution
import numpy as np
from scipy.integrate import solve_ivp
f = lambda t, u: [100 * np.exp(-((t - 7) / 0.01) ** 2)]
for kw in ({}, {"max_step": 0.01}):
print(kw, round(float(solve_ivp(f, (0, 10), [0.0], **kw).y[0, -1]), 4)){} 0.0
{'max_step': 0.01} 1.7725
Test yourself
An embedded Runge-Kutta pair is used to…
- double the order for free
- estimate the local error cheaply from shared stages
- solve stiff problems
- avoid function evaluations
If the estimated error is 32 times the tolerance for a method whose local error scales like , the step should be reduced by about…
- 32
- 2
- 5
- 16
The default rtol of solve_ivp is…