Operational review: simulating ODEs with judgment
A practical review of m09 integrators for real models: choose methods and tolerances with work–precision diagrams, detect events with dense output and handle differential-algebraic equations with constraints.
After this lesson you can
- Construct and interpret a work–precision diagram for a particular problem.
- Choose absolute and relative tolerances consistent with nondimensionalized model scales.
- Detect events using dense output and root finding, including terminal and directional events.
- Recognize a DAE, determine its index and reduce it or use an appropriate implicit method.
Before you start
Same equation, different numerical answers
A simulation can finish without errors yet miss an impact, violate a constraint or accumulate an error greater than the tolerance. The previous lesson’s nondimensionalization helps choose scales; now we must choose an algorithm, measure its error and state which cost we compare. We review Runge–Kutta, adaptive steps and stiffness from the model user’s perspective.
A method of order has global error under the usual assumptions for fixed step and finite horizon. Absolute stability answers a different question: when applied to , are errors amplified? A stiff system may force an explicit method to take tiny steps for stability even when the visible solution changes slowly. An implicit method can relieve that constraint, but pays for nonlinear systems and factorizations; it requires Newton for systems or another solver.
For explicit Euler the test equation gives . For , the non-amplification condition is , that is . Once the exact solution has decayed, a larger step can still be unstable. Implicit Euler gives and damps this mode for any positive step. This does not make a huge step accurate: stability and accuracy are distinct criteria.
An embedded pair reuses stages to calculate two approximations of different orders; their difference estimates local error of the lower-order formula. The controller scales that difference, accepts or rejects the step and proposes another size. Local error compares one step with the exact solution starting from that step’s numerical state. Global error compares with the initial-value problem’s solution and also accumulates propagation of previous errors. In sensitive dynamics, a small local estimate can coexist with a large global discrepancy.
Work versus precision
A work–precision diagram plots measured error against cost for each method and several tolerances. Here error is the infinity norm at the final time relative to a stricter reference solution. The displayed cost is nfev, the field evaluations reported by SciPy, not time or total cost: factorizations and some evaluations for numerical Jacobians are not reflected in that count.
The figure’s data were obtained with solve_ivp in local Python: relative tolerances and absolute tolerances one hundredth as large. Van der Pol starts at and ends at ; Robertson starts at and ends at ; Kepler starts at and ends at . References use Radau or DOP853 with stricter tolerances; the difference when relaxing the reference is shown to avoid interpreting figures below its resolution. These are not measured times or a universal ranking.
To build a useful benchmark, first define the error that matters: final state, maximum over common times, energy, phase or another quantity of interest. Use an analytic reference if available; otherwise compare at least two stricter reference solutions and check stability of the result. The most accurate numerical solution available remains an approximation. At the same target error, the leftmost point minimizes nfev among tested points, but may not minimize wall time for a large system.
The figure’s problems contrast different phenomena. Van der Pol satisfies , : changing changes scale separation, although comparing only up to is not the same as comparing a fixed number of periods. Robertson is three-species kinetics with a conserved sum; its small components require attention to absolute tolerance. Kepler uses position and velocity in a central field: for the chosen elliptical orbit, phase error can matter even when energy appears well conserved.
A diagram should not compare methods solving different problems. They must share initial state, interval, equations and error definition; if there are events, they must also share the restart rule. Evaluate the reference at the same times as each method, or use sufficiently accurate dense output. A table at one tolerance does not show how preference changes with the objective. An integrator that stopped before the requested endpoint should not be plotted as successful.
In SciPy documentation, RK45 uses an order-5/4 pair; DOP853 is order 8; Radau is implicit order 5; BDF changes order between 1 and 5; LSODA switches families as it detects stiffness. These are implementation properties, not guarantees that one wins every problem. Symplectic integrators deserve a different comparison when preserving structure over many orbits matters.
The difference between the graph’s references signals resolution, not a proven bound on reference error. If a point approaches that difference, do not interpret the last decimal as a reliable advantage. Curves with different evaluation counts do not by themselves prove the method with fewer evaluations is faster: an evaluation may cost differently from a factorization or linear solve. For a large system also record njev, nlu, memory and time under comparable conditions, and verify both methods attain the same effective accuracy.
Tolerances do not guarantee final digits
The controller compares a local estimator scaled by a combination of atol and rtol * abs(y). If a component is approximately , with rtol=1e-3 and atol=1e-12, the relative term is of order : it dominates the absolute term. That does not guarantee global error below or three correct digits in every component. Near zero atol dominates; when components have very different scales, use per-component absolute tolerances and check convergence of the quantity of interest.
For example, consider two components representing a typical position of meters and a typical concentration of in its units. With rtol=1e-3, their relative contributions are and . The same atol=1e-6 barely affects the first but treats a change comparable to the entire second value as acceptable. Scaling each variable by a relevant magnitude and then choosing tolerances does not change the physics; it makes the required accuracy explicit for each. Changing units without changing atol can alter the numerical problem you ask to solve.
Where did the impact occur?
An integrator can provide values at step endpoints and a continuous interpolant inside. This dense output does not require forcing a step at every requested time. Event detection searches for a root of in an interval with an observed sign change. For a ball, and the descending event marks ground contact.
In solve_ivp, t_eval selects returned times while internal step selection remains controlled by the integrator. With dense_output=True, sol.sol(t) allows evaluation of the interpolant between covered endpoints. Do not extrapolate outside that interval as if the numerical solution were validated there, or confuse interpolant order with advance-method order: for RK45, for example, SciPy documents quartic interpolation for a fifth-order advance method.
With unit gravity, . The positive root is ; at impact outgoing velocity is , . The state must be reset at impact and then integrated again. The ideal interactive stops after an accumulation of bounces: this rule avoids simulating infinitely many impacts in finite time, and does not describe a real contact law.
A root located accurately on the interpolant does not eliminate interpolant error. SciPy also detects sign changes between step endpoints: it can miss multiple crossings within one step or tangential contact without a sign change. Direction and terminal conditions avoid confusing ascending and descending crossings but do not fix those cases. A reasonable max_step may be necessary to resolve frequent events; it does not by itself replace root localization.
The practical algorithm separates three operations. First detect a candidate interval by evaluating at the beginning and end of an accepted step. Then solve scalar equation on interpolant , for example using Brent or bisection. Finally evaluate the state at the root and apply the transition law. For a descending impact, a negative direction condition excludes a later ascending crossing; after restarting, avoid immediately detecting the same zero again if the implementation includes the initial endpoint.
Tangential contact shows the limit of the sign criterion: touches zero at but is positive on both sides. Detecting it requires additional information, for example searching for minima of or a sign change in its derivative when justified by the model. Root-finding tolerance controls the interpolant’s zero; integrator tolerance controls its approximation to the trajectory. These are separate error sources.
Constraints and DAEs
A differential-algebraic equation (DAE) combines evolution and constraints. For a unit-length pendulum, position , velocity and gravity ,
The last equation imposes the rod; is constraint force per unit mass in this convention. Differentiating once gives ; a second time gives , which determines if . A third differentiation of the original constraint yields a differential equation for : under the differentiation-index definition for this formulation, the system has index 3. Replacing the position constraint with the velocity constraint gives the corresponding index-2 formulation; replacing it with acceleration gives index 1. The count depends on the formulation and which variables are algebraic.
Replacing the position constraint with acceleration gives an index-1 formulation. On the consistent set it agrees with the pendulum, but its numerical solutions can leave ; the acceleration equation does not automatically correct accumulated position or velocity error. Baumgarte replaces by , with . This damps constraint errors in the continuous model; a large can introduce numerical stiffness.
Initial conditions must satisfy both and . The first fixes length; the second prevents radial velocity. A consistent position with nonzero radial velocity does not define a state compatible with the ideal rod. Substituting the formula for into acceleration gives an ODE for near , but that ODE also has solutions that do not satisfy the initial constraint.
The third counting step can be seen explicitly. On a consistent solution, because . If is constant, differentiating and substituting gives . This derivative uses the velocity constraint; outside the consistent manifold the same simplification is invalid. The count explains why the position constraint is harder for a solver than an algebraic equation that already directly determines its variable.
With Baumgarte, and . Substitute these expressions into the stabilized equation and solve:
The two additional terms vanish for a consistent state. Their purpose is to return the solution toward the manifold when there is error, not change the force of an exact pendulum. Stability of the continuous error system does not guarantee explicit Euler stability for every and step: as increases, also check the product of stabilization scale and step.
Projection normalizes position and removes the radial velocity component after every step. It preserves constraints up to rounding, but can change energy and phase: checking length is not enough to verify the full trajectory. For a real system, use a suitable DAE method, consistent initial conditions and tolerances, and also measure relevant physical quantities. solve_ivp solves ODEs; it is not a general index-3 DAE solver.
In the figure, the three curves are runs of the same Euler scheme with step , not experimental data. The first integrates the reduced acceleration equation; the second adds the terms above; the third projects after each step. The floor of only allows zero to be shown on a logarithmic scale. The low projection curve does not by itself prove angle, energy or period correct. The index is also a property of the continuous formulation, not a count of how often an algorithm projects.
Lab: errors and events with SciPy
The following benchmark reproduces the figure’s logic on two small problems. Compare each solution at the same final time with a stricter reference and record both nfev and nlu. It runs in the browser: split work by problem so each cell is short.
import numpy as np
from scipy.integrate import solve_ivp
def vdp(t, y):
return [y[1], (1-y[0]**2)*y[1]-y[0]]
def bench(f, y0, end, ref_method, methods=None, reference=None):
ref = reference if reference is not None else solve_ivp(f, (0,end), y0, method=ref_method, rtol=1e-12, atol=1e-14)
assert ref.success
rows=[]
for method in (methods or ['RK45','DOP853','Radau','BDF','LSODA']):
for tol in [1e-3,1e-5,1e-7,1e-9]:
s=solve_ivp(f,(0,end),y0,method=method,rtol=tol,atol=tol/100)
rows.append((method,tol,s.nfev,s.nlu,float(np.max(np.abs(s.y[:,-1]-ref.y[:,-1]))) if s.success else None))
return rows
rows_vdp = bench(vdp,[2,0],10,'DOP853')
for row in rows_vdp:
print(row)import matplotlib.pyplot as plt
fig, ax = plt.subplots()
for method in ['RK45','DOP853','Radau','BDF','LSODA']:
rows = [r for r in rows_vdp if r[0] == method and r[4] is not None and r[4] > 0]
ax.loglog([r[2] for r in rows], [r[4] for r in rows], 'o-', label=method)
ax.set_xlabel('evaluaciones del campo (nfev)')
ax.set_ylabel('error final, norma infinito')
ax.legend()
plt.show()To reproduce the other Van der Pol and Kepler states, run the following cells. The interval is the same as in the figure and each cell runs one benchmark.
def vdp10(t, y): return [y[1], 10*(1-y[0]**2)*y[1]-y[0]]
ref10 = solve_ivp(vdp10, (0,10), [2,0], method='Radau', rtol=1e-12, atol=1e-14)
assert ref10.success
print('referencia calculada')rows_vdp10 = bench(vdp10, [2,0], 10, 'Radau', ['RK45'], ref10)
print('puntos RK45:', len(rows_vdp10))rows_vdp10 += bench(vdp10, [2,0], 10, 'Radau', ['DOP853'], ref10)
print('puntos explícitos:', len(rows_vdp10))rows_vdp10 += bench(vdp10, [2,0], 10, 'Radau', ['Radau'], ref10)
print('puntos acumulados:', len(rows_vdp10))rows_vdp10 += bench(vdp10, [2,0], 10, 'Radau', ['BDF','LSODA'], ref10)
print('puntos totales:', len(rows_vdp10))def vdp100(t, y): return [y[1], 100*(1-y[0]**2)*y[1]-y[0]]
rows_vdp100 = bench(vdp100, [2,0], 10, 'Radau')
print('puntos calculados:', len(rows_vdp100))def kepler(t, y):
x,z,vx,vz=y
r=(x*x+z*z)**1.5
return [vx,vz,-x/r,-z/r]
rows_kepler=bench(kepler,[.4,0,0,2],2*np.pi,'DOP853')
print('puntos calculados:', len(rows_kepler))def robertson(t, y):
a,b,c=y
return [-.04*a+1e4*b*c, .04*a-1e4*b*c-3e7*b*b, 3e7*b*b]
for row in bench(robertson,[1,0,0],1,'Radau'):
print(row)The figure uses horizon 10 for Robertson and additional problems, so its numbers differ from this second cell. The reader can increase the horizon locally. A failed integration is recorded as such; its incomplete final state is not compared with the reference.
To repeat the full Robertson horizon, change the last time argument of bench(robertson, [1,0,0], 1, 'Radau') to 10. That calculation may take longer in the browser, especially with explicit methods; the figure stores a local run and does not present that duration as a browser measurement.
from scipy.optimize import brentq
def flight(t, z): return [z[1], -1.0]
def ground(t, z): return z[0]
ground.direction = -1
ground.terminal = True
sol = solve_ivp(flight, (0,3), [1,0], dense_output=True, rtol=1e-10, atol=1e-12)
bracket = next((a,b) for a,b in zip(sol.t[:-1],sol.t[1:]) if sol.sol(a)[0] > 0 and sol.sol(b)[0] <= 0)
manual = brentq(lambda t: sol.sol(t)[0], *bracket, xtol=1e-12)
event = solve_ivp(flight, (0,3), [1,0], events=ground, rtol=1e-10, atol=1e-12)
print('raíz manual:', manual)
print('evento SciPy:', event.t_events[0][0])
print('error frente a sqrt(2):', abs(manual-np.sqrt(2)))The root is exact for the parabola apart from rounding and numerical interpolation error. For a bounce, take velocity at the event, change it according to restitution and restart; continuing the flight ODE without a restart would pass through the ground.
Exercises
first_crossing(sol, g, a, b). sol(t) evaluates a step's dense output and g(t, sol(t)) is continuous. A unique crossing with opposite endpoint signs is guaranteed. Return the root with error below 1e-10 using bisection.def first_crossing(sol, g, a, b):
passClosing
An interval with multiple crossings can hide events, index reduction can drift off the manifold and a stable simulation can have phase error. Repeat the experiment with different tolerances and steps, check invariants and retain the context of each measurement.