Module contents
Lesson 2 of 27Review 75 min

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 pp has global error O(hp)\bigO(h^p) under the usual assumptions for fixed step and finite horizon. Absolute stability answers a different question: when applied to y′=λyy'=\lambda y, 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 yn+1=(1+hλ)yny_{n+1}=(1+h\lambda)y_n. For λ=−1000\lambda=-1000, the non-amplification condition is ∣1−1000h∣≤1|1-1000h|\le1, that is 0≤h≤0.0020\le h\le0.002. Once the exact solution has decayed, a larger step can still be unstable. Implicit Euler gives yn+1=yn/(1−hλ)y_{n+1}=y_n/(1-h\lambda) 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.

InteractiveFive integrators, several tolerances
  • RK45
  • DOP853
  • Radau
  • BDF
  • LSODA

Four tolerances per method. SciPy 1.18.1; nfev excludes the full cost of factorizations and some evaluations used to approximate Jacobians.

Failed runs0
Difference between references7.59e-14
Choose Van der Pol with different μ values, Robertson or Kepler. Each point comes from a SciPy 1.18.1 run; the horizontal axis counts evaluations and the vertical axis measures final error against the reference. For Robertson, RK45 fails at the loosest tolerance and that point is omitted. Which method reaches a target error with fewer evaluations in this experiment?

The figure’s data were obtained with solve_ivp in local Python: relative tolerances 10−3,10−5,10−7,10−910^{-3},10^{-5},10^{-7},10^{-9} and absolute tolerances one hundredth as large. Van der Pol starts at (2,0)(2,0) and ends at t=10t=10; Robertson starts at (1,0,0)(1,0,0) and ends at t=10t=10; Kepler starts at (0.4,0,0,2)(0.4,0,0,2) and ends at 2π2\pi. 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 y1′=y2y_1'=y_2, y2′=μ(1−y12)y2−y1y_2'=\mu(1-y_1^2)y_2-y_1: changing μ\mu changes scale separation, although comparing only up to t=10t=10 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 10610^6, with rtol=1e-3 and atol=1e-12, the relative term is of order 10310^3: it dominates the absolute term. That does not guarantee global error below 10310^3 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 10610^6 meters and a typical concentration of 10−610^{-6} in its units. With rtol=1e-3, their relative contributions are 10310^3 and 10−910^{-9}. 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 g(t,y(t))g(t,\vb y(t)) in an interval with an observed sign change. For a ball, g=yg=y 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.

InteractiveA ball and contact time
  • Exact flight and event
  • Euler, bounce at step end
  • Bisection interval
0.5
0.7
0
Exact impacts shown4
First root interval1.0000 to 1.5000
The blue curve uses exact parabolic flight and locates each impact; orange advances with Euler and changes velocity at the end of a step that has already penetrated the ground. Change the step and restitution. The purple interval brackets the first impact: advance bisection and observe it narrowing. Blue points mark roots.

With unit gravity, y(t0+τ)=y0+v0τ−τ2/2y(t_0+\tau)=y_0+v_0\tau-\tau^2/2. The positive root is τ=v0+v02+2y0\tau=v_0+\sqrt{v_0^2+2y_0}; at impact outgoing velocity is v+=−ev−v^+=-e v^-, 0≤e≤10\le e\le1. 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 gg at the beginning and end of an accepted step. Then solve scalar equation g(t,y~(t))=0g(t,\tilde{\vb y}(t))=0 on interpolant y~\tilde{\vb y}, 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: g(t)=(t−1)2g(t)=(t-1)^2 touches zero at t=1t=1 but is positive on both sides. Detecting it requires additional information, for example searching for minima of gg 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 q=(x,y)\vb q=(x,y), velocity v\vb v and gravity g=(0,−1)\vb g=(0,-1),

q˙=v,v˙=g−λq,q⊤q=1.\dot{\vb q}=\vb v,\qquad \dot{\vb v}=\vb g-\lambda\vb q,\qquad \vb q\T\vb q=1.

The last equation imposes the rod; λ\lambda is constraint force per unit mass in this convention. Differentiating once gives q⊤v=0\vb q\T\vb v=0; a second time gives v⊤v+q⊤g−λq⊤q=0\vb v\T\vb v+\vb q\T\vb g-\lambda\vb q\T\vb q=0, which determines λ\lambda if q≠0\vb q\ne0. A third differentiation of the original constraint yields a differential equation for λ\lambda: 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 q⊤q=1\vb q\T\vb q=1; the acceleration equation does not automatically correct accumulated position or velocity error. Baumgarte replaces c′′=0c''=0 by c′′+2ac′+a2c=0c''+2a c'+a^2c=0, with c=q⊤q−1c=\vb q\T\vb q-1. This damps constraint errors in the continuous model; a large aa can introduce numerical stiffness.

Initial conditions must satisfy both q0⊤q0=1\vb q_0\T\vb q_0=1 and q0⊤v0=0\vb q_0\T\vb v_0=0. 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 λ\lambda into acceleration gives an ODE for (q,v)(\vb q,\vb v) near q≠0\vb q\ne0, 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, λ=v⊤v+q⊤g\lambda=\vb v\T\vb v+\vb q\T\vb g because q⊤q=1\vb q\T\vb q=1. If g\vb g is constant, differentiating and substituting v˙=g−λq\dot{\vb v}=\vb g-\lambda\vb q gives λ˙=3v⊤g−2λv⊤q=3v⊤g\dot\lambda=3\vb v\T\vb g-2\lambda\vb v\T\vb q=3\vb v\T\vb g. 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, c′′=2(v⊤v+q⊤g−λq⊤q)c''=2(\vb v\T\vb v+\vb q\T\vb g-\lambda\vb q\T\vb q) and c′=2q⊤vc'=2\vb q\T\vb v. Substitute these expressions into the stabilized equation and solve:

λ=v⊤v+q⊤g+2aq⊤v+12a2(q⊤q−1)q⊤q.\lambda=\frac{\vb v\T\vb v+\vb q\T\vb g+2a\vb q\T\vb v+\tfrac12a^2(\vb q\T\vb q-1)}{\vb q\T\vb q}.

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 aa and step: as aa increases, also check the product of stabilization scale and step.

InteractiveDrifting length
  • Acceleration reduction
  • Baumgarte
  • Constraint projection

Explicit Euler, step 0.02, unit length and gravity. The projected curve imposes both constraints after each step; the 10⁻¹⁵ floor allows display on a logarithmic scale.

1.0
Last Baumgarte error0.0214
Compare Euler on the acceleration reduction, Baumgarte stabilization and projection of position and velocity onto the index-3 problem's constraints. Change aa: projection is not a general DAE integrator, but an explicit geometric correction in this example.

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 0.020.02, 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 10−1510^{-15} 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.

[ ]Integrator benchmarkBrowser
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)
[ ]Plot work and precisionBrowser
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.

[ ]Van der Pol with μ = 10: referenceBrowser
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')
[ ]Van der Pol with μ = 10: RK45Browser
rows_vdp10 = bench(vdp10, [2,0], 10, 'Radau', ['RK45'], ref10)
print('puntos RK45:', len(rows_vdp10))
[ ]Van der Pol with μ = 10: DOP853Browser
rows_vdp10 += bench(vdp10, [2,0], 10, 'Radau', ['DOP853'], ref10)
print('puntos explícitos:', len(rows_vdp10))
[ ]Van der Pol with μ = 10: RadauBrowser
rows_vdp10 += bench(vdp10, [2,0], 10, 'Radau', ['Radau'], ref10)
print('puntos acumulados:', len(rows_vdp10))
[ ]Van der Pol with μ = 10: BDF and LSODABrowser
rows_vdp10 += bench(vdp10, [2,0], 10, 'Radau', ['BDF','LSODA'], ref10)
print('puntos totales:', len(rows_vdp10))
[ ]Van der Pol with μ = 100Browser
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))
[ ]A Kepler orbitBrowser
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))
[ ]Robertson over a short horizonBrowser
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.

[ ]Terminal event and root findingBrowser
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

QuizTwo targets, two points
For Robertson at t=10 these (nfev, error) pairs were measured: BDF (162, 4.38e-7), BDF (617, 1.33e-9), Radau (232, 3.65e-8), Radau (1553, 5.72e-12). Among these four points, which minimizes nfev with error below 1e-6 and which with error below 1e-10?
NumericPendulum index
In the position–velocity–multiplier pendulum formulation described above, how many differentiations of the position constraint are required to obtain a differential equation for the multiplier and hence what is its differentiation index?
CodeLocate a crossing
Implement 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):
  pass
Shift+Enter to run
QuizWhich tolerance dominates?
A component is 10⁶; rtol=10⁻³ and atol=10⁻¹². Which term dominates the local scale?

Closing

Key idea
Choose a method using an error–cost curve for the quantity that matters; events and constraints require additional checks that a tolerance alone does not provide.

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.