Module contents
Lesson 12 of 26Core 115 min

Ordinary differential equations: simulating dynamical systems

How y' = f(t, y) becomes a reliable simulation: Euler and Runge–Kutta methods, adaptive step control, absolute stability, stiffness and implicit methods, and symplectic integrators preserving energy over millions of steps. These underlie physical simulators such as MuJoCo, ODE-based diffusion samplers and Hamiltonian Monte Carlo.

After this lesson you can

  • Implement explicit and implicit Euler, RK4 and a generic Runge–Kutta method from its Butcher tableau.
  • Verify an integrator's order empirically and distinguish local and global error.
  • Implement an embedded pair with adaptive step control and rtol and atol tolerances.
  • Calculate stability regions, detect stiffness and choose between RK45, DOP853, Radau, BDF and LSODA.
  • Explain why symplectic integrators preserve energy long-term and use them for Hamiltonian systems.

Before you start

Motivation: from y′=f(t,y)\vb{y}' = f(t, \vb{y}) to a simulation you can trust

Almost everything simulated in science and engineering is fundamentally an initial value problem: you know system state y0\vb{y}_0 at time t0t_0 and a law y′=f(t,y)\vb{y}' = f(t, \vb{y}) describing its change, and want the state at later times.

  • A robot. State is joint angles and velocities; law is Newton–Euler equations with gravity, motors, friction and contact. A simulator like MuJoCo advances this state in steps of milliseconds (default step 0.0020.002 s) thousands of times per simulated second, and a reinforcement-learning agent learns inside that simulation.
  • An orbit. State is positions and velocities; law is gravitation. Here accurate individual steps are not enough: a probe or planet is integrated for millions of steps, and an error adding a little energy each orbit eventually launches the planet out of the solar system.
  • A chemical reaction. Concentrations obey mass action with reaction constants differing by nine orders of magnitude. In the Robertson reaction, seen in the lab, explicit Euler would need on the order of 101410^{14} steps to follow it to completion near t=1011t = 10^{11}; an implicit method does it in about 600.
  • A diffusion model. Generating an image means integrating the probability-flow ODE backwards in time, whose field ff is a neural network. Each ff evaluation is a full network pass, so evaluation count is sampling cost. DDPM sampled with 1000 steps (Ho, Jain and Abbeel, 2020); DPM-Solver, an integrator designed for that ODE, obtains high-quality samples with only 10 to 20 evaluations (Lu et al., 2022).

The four problems share a skeleton and fail in four ways: lack of accuracy, instability, stiffness or failure to respect system geometry. This lesson builds tools for each: Euler and Runge–Kutta methods, automatic step control, absolute stability theory, implicit methods for stiff problems and symplectic integrators preserving energy over millions of steps. At the end you will read scipy.integrate.solve_ivp and MuJoCo options as what they are: numerical analysis decisions.

The initial value problem and its conditioning

We work with

y′(t)=f(t,y(t)),y(t0)=y0,t∈[t0,T],\vb{y}'(t) = f(t, \vb{y}(t)), \qquad \vb{y}(t_0) = \vb{y}_0, \qquad t \in [t_0, T],

with y(t)∈Rd\vb{y}(t) \in \R^d and ff continuous and Lipschitz in y\vb{y} with constant LL: ∥f(t,y)−f(t,z)∥≤L∥y−z∥\norm{f(t, \vb{y}) - f(t, \vb{z})} \le L\norm{\vb{y} - \vb{z}}. The Picard–Lindelöf theorem guarantees a unique solution throughout [t0,T][t_0, T]. Every higher-order equation reduces to this form by adding derivatives as variables: pendulum θ′′=−sin⁡θ\theta'' = -\sin\theta is system y1′=y2y_1' = y_2, y2′=−sin⁡y1y_2' = -\sin y_1.

Before discretizing, ask what we would of any numerical problem: how sensitive is the answer to data? This is its conditioning. If two solutions start from y0\vb{y}_0 and z0\vb{z}_0, Grönwall’s inequality gives

∥y(t)−z(t)∥≤eL(t−t0)∥y0−z0∥.\norm{\vb{y}(t) - \vb{z}(t)} \le e^{L(t - t_0)}\norm{\vb{y}_0 - \vb{z}_0}.

The bound can be pessimistic. Finer information lies in the variational equation: matrix Φ(t)=∂y(t)/∂y0\mat{\Phi}(t) = \partial\vb{y}(t)/\partial\vb{y}_0 satisfies Φ′=J(t,y(t)) Φ\mat{\Phi}' = \mat{J}(t, \vb{y}(t))\,\mat{\Phi} with Φ(t0)=I\mat{\Phi}(t_0) = \mat{I} and J=∂f/∂y\mat{J} = \partial f/\partial\vb{y} (ODE sensitivity). Small perturbation δy0\delta\vb{y}_0 becomes Φ(t) δy0\mat{\Phi}(t)\,\delta\vb{y}_0, so ∥Φ(t)∥\norm{\mat{\Phi}(t)} is the absolute condition number of map y0↦y(t)\vb{y}_0 \mapsto \vb{y}(t).

Two extremes frame the lesson:

  • Contractive problems. In y′=−1000 (y−cos⁡t)−sin⁡ty' = -1000\,(y - \cos t) - \sin t, whose solution with y(0)=1y(0) = 1 is cos⁡t\cos t, Lipschitz constant is L=1000L = 1000, but any two solutions approach as e−1000te^{-1000t}: the problem is superbly conditioned. Grönwall’s bound with e1000te^{1000t} is useless. Contraction is measured by the logarithmic norm μ2(J)=λmax⁡((J+J⊤)/2)\mu_2(\mat{J}) = \lambda_{\max}\big((\mat{J} + \mat{J}\T)/2\big): if μ2(J)≤μ\mu_2(\mat{J}) \le \mu along the path, then ∥Φ(t)∥2≤eμ(t−t0)\norm{\mat{\Phi}(t)}_2 \le e^{\mu(t - t_0)}, and here μ=−1000\mu = -1000. This contrast (well-conditioned problem, huge LL) is exactly stiffness, studied below.
  • Chaotic problems. In the Lorenz system (1963), x′=10(y−x)x' = 10(y - x), y′=x(28−z)−yy' = x(28 - z) - y, z′=xy−83zz' = xy - \tfrac{8}{3}z, perturbations grow on average as eλ1te^{\lambda_1 t}, with largest Lyapunov exponent λ1≈0.9056\lambda_1 \approx 0.9056 (Sprott’s 2003 value; see Lyapunov exponents). Condition number grows exponentially with horizon. With initial relative error 10−1610^{-16}, that of floating-point representation itself, the computed trajectory stops resembling the exact one near t≈ln⁡(1016)/0.9≈40t \approx \ln(10^{16})/0.9 \approx 40, and no integrator can prevent it.
InteractiveChaos: two correct simulations that do not resemble each other
  • from (1, 1, 1)
  • from (1 + δ₀, 1, 1)
  • distance between the two
  • slope λ₁ = 0.9056
What separates the two simulations
1·10⁻¹²
t = 0.0
Distance at this instant1.0·10⁻¹²
Time when distance reaches 141.1
Prediction ln⁡(1/δ0)/λ1\ln(1/\delta_0)/\lambda_130.5
Mean zz on [5,50][5, 50]: first / second23.89 / 24.07
Both are correct simulations of nearly identical initial conditions. Ending on opposite sides of the attractor is not an integrator failure: the system amplifies any difference as eλ1te^{\lambda_1 t}.
Two Lorenz trajectories integrated with fixed-step RK4. In ‘initial condition’ mode they start δ0\delta_0 apart in xx; in ‘step’ mode they start at the same point, but one uses h=0.002h = 0.002 and the other h=0.001h = 0.001. Below, their distance on a logarithmic scale and the line with slope λ1=0.9056\lambda_1 = 0.9056. Try δ0=10−3\delta_0 = 10^{-3} and 10−1510^{-15}: twelve orders of magnitude of accuracy delay separation only from t≈18t \approx 18 to just beyond t=50t = 50. Then switch to ‘step’ mode and compare both simulations' mean zz.

The figure teaches two things to separate. After an initial segment, distance grows as a straight line on logarithmic scale, with slope near λ1\lambda_1, until saturating at attractor size: each factor 10 of initial accuracy buys only ln⁡10/λ1≈2.5\ln 10/\lambda_1 \approx 2.5 time units of prediction. The first segment, where distance hardly grows for about 14 time units, also has an explanation: from (1,1,1)(1, 1, 1) the trajectory spirals around one of two fixed points C±=(±72,±72,27)C_\pm = (\pm\sqrt{72}, \pm\sqrt{72}, 27), whose linearization has unstable eigenvalues with real part only 0.0940.094, and does not change lobe until t≈13.6t \approx 13.6. Thus the reference line starting at δ0\delta_0 at t=0t = 0 leads the measured curve: λ1\lambda_1 averages over the entire attractor, and local separation rate varies greatly by region. In ‘step’ mode, two simulations from the same initial condition with different steps also separate: integrator error acts as another perturbation. Neither follows the exact solution beyond a certain time and yet both are useful: temporal means, histograms and attractor shape match. For a chaotic system one can trust a simulation’s statistics, not its long-term trajectory. You will measure it numerically in the second lab.

Euler: the first integrator

Divide [t0,T][t_0, T] into NN steps of size h=(T−t0)/Nh = (T - t_0)/N, with tn=t0+nht_n = t_0 + nh, and let yn\vb{y}_n approximate y(tn)\vb{y}(t_n). The simplest idea is to follow the tangent.

To quantify loss distinguish two errors.

For explicit Euler, Taylor expansion with remainder gives, if y∈C2\vb{y} \in C^2 and M2=max⁡∥y′′∥M_2 = \max\norm{\vb{y}''},

τn+1=y(tn+h)−y(tn)−h y′(tn)=∫tntn+1(tn+1−s) y′′(s) ⁣ds,∥τn+1∥≤h22M2.\vb{\tau}_{n+1} = \vb{y}(t_n + h) - \vb{y}(t_n) - h\,\vb{y}'(t_n) = \int_{t_n}^{t_{n+1}} (t_{n+1} - s)\,\vb{y}''(s)\dd s, \qquad \norm{\vb{\tau}_{n+1}} \le \frac{h^2}{2}M_2.

It is order 1: local error O(h2)\bigO(h^2) per step. Reaching TT takes N=(T−t0)/hN = (T - t_0)/h steps, so global error N⋅O(h2)=O(h)N \cdot \bigO(h^2) = \bigO(h) is natural to expect. But errors do not merely add: each propagates through later steps and may be amplified. The tool for controlling propagation is discrete Grönwall.

Proof

By induction, an≤(1+hL)na0+B∑j=0n−1(1+hL)j=(1+hL)na0+B (1+hL)n−1hLa_n \le (1 + hL)^n a_0 + B\sum_{j=0}^{n-1}(1 + hL)^j = (1 + hL)^n a_0 + B\,\frac{(1 + hL)^n - 1}{hL}, summing the geometric series. Since 1+x≤ex1 + x \le e^x, (1+hL)n≤enhL(1 + hL)^n \le e^{nhL}.

∎

The proof directly applies the lemma and you will reconstruct it in the final guided exercise. Three readings:

  1. Global order is local order minus one. Generally, a one-step order-pp method whose increment is Lipschitz has global error O(hp)\bigO(h^p) by the same argument. Hence a method “is order pp” referring to global error.
  2. The eL(T−t0)e^{L(T - t_0)} factor is problem conditioning through the pessimistic Lipschitz lens. In a contractive problem actual error is much smaller; in a chaotic one exponential growth is real.
  3. It says nothing about rounding. NN steps also accumulate about NN rounding errors of size εmach∥y∥\varepsilon_{\text{mach}}\norm{\vb{y}}; total error behaves like C1h+C2 εmach/hC_1 h + C_2\,\varepsilon_{\text{mach}}/h, and reducing hh indefinitely eventually worsens results. An order-1 method reaches that floor early, another reason to use high order.

Implicit Euler has the same order (its local error is also h22y′′\tfrac{h^2}{2}\vb{y}'', with opposite sign), and costs much more per step: solve G(Y)=0\vb{G}(\vb{Y}) = \vb{0} with Newton’s method for systems,

(I−h J(tn+1,Y(k))) Δ(k)=−G(Y(k)),Y(k+1)=Y(k)+Δ(k),\big(\mat{I} - h\,\mat{J}(t_{n+1}, \vb{Y}^{(k)})\big)\,\Delta^{(k)} = -\vb{G}(\vb{Y}^{(k)}), \qquad \vb{Y}^{(k+1)} = \vb{Y}^{(k)} + \Delta^{(k)},

starting from Y(0)=yn\vb{Y}^{(0)} = \vb{y}_n or an explicit prediction. Each iteration solves a d×dd\times d linear system with LU with partial pivoting. For small hh, I−hJ\mat{I} - h\mat{J} is near identity: well conditioned with rapid convergence. In practice simplified Newton freezes I−hJ\mat{I} - h\mat{J}, factors once and reuses across iterations and several steps. Why pay? Stability, below.

Runge–Kutta: more evaluations per step, higher order

Euler uses one slope. The idea of Runge (1895), Heun (1900) and Kutta (1901) is to take several slopes within a step and combine them so Taylor errors cancel.

What does order require? Expand the exact solution over one step. With y′=f\vb{y}' = f and y′′=ft+fyf\vb{y}'' = f_t + f_{\vb{y}}f (all evaluated at (tn,yn)(t_n, \vb{y}_n)),

y(tn+h)=yn+hf+h22(ft+fyf)+O(h3).\vb{y}(t_n + h) = \vb{y}_n + h f + \frac{h^2}{2}\big(f_t + f_{\vb{y}}f\big) + \bigO(h^3).

In the method, ki=f+cih (ft+fyf)+O(h2)\vb{k}_i = f + c_i h\,(f_t + f_{\vb{y}}f) + \bigO(h^2), because ff‘s argument shifts cihc_i h in tt and h∑jaijkj=cihf+O(h2)h\sum_j a_{ij}\vb{k}_j = c_i h f + \bigO(h^2) in y\vb{y}. Thus

yn+1=yn+h(∑ibi)f+h2(∑ibici)(ft+fyf)+O(h3).\vb{y}_{n+1} = \vb{y}_n + h\Big(\sum_i b_i\Big)f + h^2\Big(\sum_i b_i c_i\Big)(f_t + f_{\vb{y}}f) + \bigO(h^3).

Equating coefficients: order 1 if ∑ibi=1\sum_i b_i = 1, and order 2 if additionally ∑ibici=12\sum_i b_i c_i = \tfrac12. With two stages there is a family of solutions, b2c2=12b_2 c_2 = \tfrac12: midpoint (c2=12c_2 = \tfrac12, b=(0,1)\vb{b} = (0, 1)) and Heun’s method (c2=1c_2 = 1, b=(12,12)\vb{b} = (\tfrac12, \tfrac12)).

Continuing the expansion multiplies terms: in y′′′\vb{y}''' appear fyy(f,f)f_{\vb{y}\vb{y}}(f, f) and fyfyff_{\vb{y}}f_{\vb{y}}f, independent and each giving a condition. Butcher (1963) discovered the conditions correspond bijectively to rooted trees: each tree τ\tau with ∣τ∣\abs{\tau} nodes gives a condition b⊤Φ(τ)=1/γ(τ)\vb{b}\T\Phi(\tau) = 1/\gamma(\tau). For order 4 there are eight:

∑bi=1,∑bici=12,∑bici2=13,∑biaijcj=16,∑bici3=14,∑biciaijcj=18,∑biaijcj2=112,∑biaijajkck=124.\begin{aligned} &\textstyle\sum b_i = 1, \quad \sum b_i c_i = \frac12, \quad \sum b_i c_i^2 = \frac13, \quad \sum b_i a_{ij} c_j = \frac16,\\ &\textstyle\sum b_i c_i^3 = \frac14, \quad \sum b_i c_i a_{ij} c_j = \frac18, \quad \sum b_i a_{ij} c_j^2 = \frac1{12}, \quad \sum b_i a_{ij} a_{jk} c_k = \frac1{24}. \end{aligned}

Condition count grows quickly: 1, 2, 4, 8, 17, 37, 85 and 200 for orders 1 to 8. Butcher barriers appear: an explicit ss-stage method has order p≤sp \le s, with equality only through p=4p = 4; order 5 needs 6 stages, order 6 needs 7, order 7 needs 9 and order 8 needs 11 (Hairer, Nørsett and Wanner, ch. II). Thus classical Kutta, four stages and order 4, is the sweet spot:

0121212012100116131316⟺k1=f(tn,yn),k2=f(tn+h2,yn+h2k1),k3=f(tn+h2,yn+h2k2),k4=f(tn+h,yn+hk3),\begin{array}{c|cccc} 0 & & & & \\ \tfrac12 & \tfrac12 & & & \\ \tfrac12 & 0 & \tfrac12 & & \\ 1 & 0 & 0 & 1 & \\ \hline & \tfrac16 & \tfrac13 & \tfrac13 & \tfrac16 \end{array} \qquad\Longleftrightarrow\qquad \begin{aligned} \vb{k}_1 &= f(t_n, \vb{y}_n), & \vb{k}_2 &= f(t_n + \tfrac h2, \vb{y}_n + \tfrac h2\vb{k}_1),\\ \vb{k}_3 &= f(t_n + \tfrac h2, \vb{y}_n + \tfrac h2\vb{k}_2), & \vb{k}_4 &= f(t_n + h, \vb{y}_n + h\vb{k}_3), \end{aligned}

with yn+1=yn+h6(k1+2k2+2k3+k4)\vb{y}_{n+1} = \vb{y}_n + \tfrac h6(\vb{k}_1 + 2\vb{k}_2 + 2\vb{k}_3 + \vb{k}_4). For ff independent of y\vb{y} it reduces to Simpson’s rule, suggesting its order.

Order is verified empirically as in nonlinear-equation order verification: if global error behaves as ChpCh^p, log-log scale gives a line of slope pp, and local error slope p+1p + 1. The first lab does this for Euler, implicit Euler, midpoint, Kutta’s 3/8 method and RK4. The same idea estimates error: integrating at hh and h/2h/2, Richardson extrapolation estimates fine-solution error as (yh/2−yh)/(2p−1)(\vb{y}_{h/2} - \vb{y}_h)/(2^p - 1). It works but triples cost. Next section obtains an almost-free estimator.

Adaptive step size: Dormand–Prince

With fixed steps one must choose hh for the trajectory’s hardest part, wasting it elsewhere. A highly eccentric comet spends almost all its time far from the Sun, moving slowly, and a few days close by, moving quickly: a step resolving perihelion is absurdly small at aphelion. Let the integrator measure its own error each step and adjust hh. This is adaptive step-size control, with three pieces.

1. A local error estimator: embedded pairs. Design two Runge–Kutta methods sharing stages ki\vb{k}_i but with different weights: b\vb{b} of order pp and b^\hat{\vb{b}} of order p^=p−1\hat p = p - 1. Their difference,

en+1=yn+1−y^n+1=h∑i(bi−b^i) ki,\vb{e}_{n+1} = \vb{y}_{n+1} - \hat{\vb{y}}_{n+1} = h\sum_{i}(b_i - \hat b_i)\,\vb{k}_i,

costs only additions and approximates the lower-order method’s local error, Chp^+1C h^{\hat p + 1}. The most used pair is Dormand and Prince (1980), DP5(4): seven stages, order 5 to advance and order 4 to estimate. Coefficients were chosen to make the order-5 solution error small because it is used to continue (local extrapolation). Its last stage is evaluated at (tn+1,yn+1)(t_{n+1}, \vb{y}_{n+1}) and is the next step’s first (FSAL, first same as last), so each accepted step costs 6 evaluations of ff, not 7. This is solve_ivp’s RK45; RK23 is Bogacki and Shampine’s (1989) order-3 and -2 pair.

2. A scaled norm. Compare error to a mixed tolerance componentwise:

err=1d∑i=1d(en+1,iatoli+rtol⋅max⁡(∣yn,i∣,∣yn+1,i∣))2.\mathrm{err} = \sqrt{\frac1d\sum_{i=1}^{d}\left(\frac{e_{n+1, i}}{\mathrm{atol}_i + \mathrm{rtol}\cdot\max(\abs{y_{n,i}}, \abs{y_{n+1,i}})}\right)^2}.

Accept the step if err≤1\mathrm{err} \le 1. Relative tolerance rtol controls correct digits of large components; absolute atol avoids requiring relative precision of a component passing through zero and defines which values count as noise. If a component lives at scale 10−610^{-6} and atol = 1e-6, you tell the integrator none of its digits matter.

3. A controller. Since err≈Chp^+1\mathrm{err} \approx C h^{\hat p + 1}, the step giving exactly err=1\mathrm{err} = 1 would be h err−1/(p^+1)h\,\mathrm{err}^{-1/(\hat p + 1)}. Add a safety margin and limit change:

hnuevo=h⋅min⁡(fmax⁡,  max⁡(fmin⁡,  0.9 err−1/(p^+1))),h_{\text{nuevo}} = h\cdot\min\Big(f_{\max},\; \max\big(f_{\min},\; 0.9\,\mathrm{err}^{-1/(\hat p + 1)}\big)\Big),

with fmin⁡=0.2f_{\min} = 0.2 and fmax⁡=10f_{\max} = 10 in scipy. If rejected, repeat at reduced hh; if accepted, next step uses new hh. For DP5(4), exponent is 1/51/5.

Two more pieces complete a real integrator. Initial step is chosen by a Hairer, Nørsett and Wanner heuristic estimating derivatives with an extra ff evaluation. And dense output: each DP5(4) step has an order-4 interpolation polynomial evaluated at any intermediate tt without new ff evaluations (in DOP853 interpolation is order 7). This gives solutions at requested times with t_eval or dense_output=True and locates events such as “orbit crosses axis”. Consequence: t_eval points do not influence steps, which depend only on tolerances.

InteractiveAdaptive step for a comet
  • accepted step
  • rejected attempt (proposed point)
  • exact orbit
  • Sun
Step size hh versus distance rr to the Sun (log-log scale)
10⁻²10⁻¹0.10.20.512r- - slope 3/2
0.90
1.0·10⁻⁶
step 0 of 48
Accepted / rejected steps48 / 21
f evaluations416
hmax⁡/hmin⁡h_{\max} / h_{\min}95
Slope of log⁡h\log h versus log⁡r\log r1.51
Position error after one orbit1.5·10⁻³
With e=0.90e = 0.90 the comet moves 19 times faster at perihelion than at aphelion. The step follows this pace: h∝r3/2h \propto r^{3/2}, the orbit’s local timescale.
Dormand–Prince 5(4), with scipy RK45's controller, integrates one revolution of a highly eccentric Kepler orbit. Each blue point is an accepted step and each red circle a rejected attempt, drawn where it would have landed. Play the orbit: steps cluster at perihelion. Below, hh versus distance rr to the Sun on log-log axes, with slope-3/23/2 line. Raise eccentricity to 0.98 and change tolerance: does slope change or only cloud height?

Slope 3/23/2 is not accidental. Near the Sun at distance rr, the comet moves at speed v≈2/rv \approx \sqrt{2/r} (units with μ=1\mu = 1) and traverses distance of order rr in time τ(r)∼r/v∼r3/2\tau(r) \sim r/v \sim r^{3/2}: the orbit’s local timescale. Solution derivatives scale as powers of 1/τ1/\tau, so constant local error requires h∝τ(r)∝r3/2h \propto \tau(r) \propto r^{3/2}. Adaptive control has independently discovered Kepler’s third law locally. In the lab, slope measured with solve_ivp lies between 1.41 and 1.51 for eccentricities 0.5 to 0.97, and with e=0.97e = 0.97 the longest step is about 900 times the shortest.

Absolute stability

Integrate y′=−1000 yy' = -1000\,y with explicit Euler and h=0.0025h = 0.0025. Exact solution decays brutally fast; numerical solution instead multiplies by 1−2.5=−1.51 - 2.5 = -1.5 each step: changes sign and explodes. This is not an accuracy problem (solution is nearly zero, easy to approximate), but stability. Understand it via the simplest possible equation.

The test equation

Take the Dahlquist test equation y′=λyy' = \lambda y with λ∈C\lambda \in \C. It is less particular than it seems. Near a solution, error follows linearization e′=Je\vb{e}' = \mat{J}\vb{e}, and if J\mat{J} is diagonalizable with J=VΛV−1\mat{J} = \mat{V}\mat{\Lambda}\mat{V}\inv, substitution w=V−1e\vb{w} = \mat{V}\inv\vb{e} decouples the system into scalar equations wi′=λiwiw_i' = \lambda_i w_i, with complex λi\lambda_i for oscillations. Runge–Kutta methods commute with linear changes of variables (applying the method then changing basis equals the reverse), so each mode can be understood separately.

Apply Runge–Kutta to y′=λyy' = \lambda y and set z=hλz = h\lambda. Stages satisfy k=λ(yn1+hAk)\vb{k} = \lambda(y_n\mathbb{1} + h\mat{A}\vb{k}), with 1\mathbb{1} the ones vector, hence k=λ(I−zA)−11 yn\vb{k} = \lambda(\mat{I} - z\mat{A})\inv\mathbb{1}\,y_n, and

yn+1=R(z) yn,R(z)=1+z b⊤(I−zA)−11.y_{n+1} = R(z)\,y_n, \qquad R(z) = 1 + z\,\vb{b}\T(\mat{I} - z\mat{A})\inv\mathbb{1}.

RR is the stability function. Numerical solution is yn=R(z)ny0y_n = R(z)^n y_0 and exact solution enzy0e^{nz}y_0; an order-pp method satisfies R(z)=ez+O(zp+1)R(z) = e^z + \bigO(z^{p+1}). For an explicit method, A\mat{A} is nilpotent, (I−zA)−1=∑k<szkAk(\mat{I} - z\mat{A})\inv = \sum_{k<s} z^k\mat{A}^k, and RR is a polynomial of degree ≤s\le s. If p=s≤4p = s \le 4, order fixes the polynomial: R(z)=∑k=0pzk/k!R(z) = \sum_{k=0}^{p} z^k/k!, truncated Taylor expansion of eze^z. For implicit methods RR is rational:

REuler(z)=1+z,RRK4(z)=1+z+z22+z36+z424,Rimpl(z)=11−z,Rtrap(z)=1+z/21−z/2.R_{\text{Euler}}(z) = 1 + z, \qquad R_{\text{RK4}}(z) = 1 + z + \tfrac{z^2}{2} + \tfrac{z^3}{6} + \tfrac{z^4}{24}, \qquad R_{\text{impl}}(z) = \frac{1}{1 - z}, \qquad R_{\text{trap}}(z) = \frac{1 + z/2}{1 - z/2}.
InteractiveStability regions
z = hλ plane
  • Euler
  • RK4
  • DP5
  • Euler impl.
  • Trapezoid
  • Radau
  • exact
1.50·10⁻³
Shaded region
λ\lambda−1000.0
z=hλz = h\lambda−1.500 + 0.000i
method|R(z)|maximum hEuler0.50002.00·10⁻³RK40.27342.79·10⁻³DP50.22913.31·10⁻³Euler impl.0.4000any hTrapezoid0.1429any hRadau0.2234any h
Euler explicit: ∣R(z)∣=0.5000≤1\abs{R(z)} = 0.5000 \le 1, iterates do not grow (and change sign each step because R(z)<0R(z) < 0).
The exact solution decays as e−1000te^{-1000t}: at t=0.01t = 0.01 it is already 4.5⋅10−54.5\cdot 10^{-5}. Raise hh above 0.0020.002.
Complex plane of z=hλz = h\lambda with ∣R(z)∣=1\abs{R(z)} = 1 boundaries for six methods and selected region shaded. Drag zz, or hold λ\lambda fixed and move hh, sliding zz along the dashed ray. Below, ∣yn∣=∣R(z)∣n\abs{y_n} = \abs{R(z)}^n for each method and the exact solution. With y′=−1000yy' = -1000y, raise hh from 0.0015 to 0.003: which explodes first? With the oscillator, which invents neither growth nor damping? In the stiff case compare decay of implicit Euler and trapezoid.

What the figure shows, in formulas:

  • Explicit Euler: S\mathcal{S} is disk ∣1+z∣≤1\abs{1 + z} \le 1, center −1-1 and radius 1. For real λ<0\lambda < 0 it requires h≤2/∣λ∣h \le 2/\abs{\lambda}. On the imaginary axis, ∣1+iy∣=1+y2>1\abs{1 + iy} = \sqrt{1 + y^2} > 1: explicit Euler amplifies any undamped oscillation at any step.
  • RK4: region is larger. It intersects the real axis at −2.785-2.785 and contains imaginary segment ∣y∣≤22≈2.828\abs{y} \le 2\sqrt 2 \approx 2.828; within it, ∣R(iy)∣2=1−y6/72+y8/576<1\abs{R(iy)}^2 = 1 - y^6/72 + y^8/576 < 1, so RK4 slightly damps oscillations. Dormand–Prince 5 reaches −3.307-3.307 on the real axis.
  • Implicit Euler: ∣1/(1−z)∣≤1  ⟺  ∣1−z∣≥1\abs{1/(1 - z)} \le 1 \iff \abs{1 - z} \ge 1, exterior of the disk centered at 11 with radius 1, containing C−\C^-: A-stable and, since R(z)→0R(z) \to 0, L-stable.
  • Trapezoid: ∣1+z/2∣≤∣1−z/2∣  ⟺  Re z≤0\abs{1 + z/2} \le \abs{1 - z/2} \iff \mathrm{Re}\,z \le 0. Its region is exactly the half-plane: A-stable, preserving modulus on the imaginary axis. But R(z)→−1R(z) \to -1 as z→−∞z \to -\infty: not L-stable. With z=−50z = -50, R=−24/26≈−0.92R = -24/26 \approx -0.92: the stiff mode, which should immediately disappear, survives oscillating in sign for dozens of steps. Implicit Euler reduces it to 1/511/51 in one.
Proof

RR is a polynomial, and consistency (∑bi=1\sum b_i = 1) makes its zz coefficient 1, so degree at least 1. A nonconstant polynomial satisfies ∣R(z)∣→∞\abs{R(z)} \to \infty as ∣z∣→∞\abs{z} \to \infty, hence ∣R(z)∣>1\abs{R(z)} > 1 outside a disk. In particular on the negative real axis there is x∗x^* such that ∣R(x)∣>1\abs{R(x)} > 1 for x<x∗x < x^*.

∎

Multistep methods have their own barrier. Dahlquist’s second barrier (1963): an A-stable linear multistep method has order at most 2, and among order-2 methods trapezoid has the smallest error constant. BDF formulas (backward differentiation formulas), seen shortly, are A-stable at orders 1 and 2; orders 3 to 6 are only A(α)A(\alpha)-stable (their region contains a sector of half-angle α\alpha around the negative real axis), with α≈86.03°\alpha \approx 86.03°, 73.35°73.35°, 51.84°51.84° and 17.84°17.84°; from order 7 they are unstable even with λ=0\lambda = 0 (Hairer and Wanner, ch. V).

Stiffness and implicit methods

What stiffness is

The term comes from Curtiss and Hirschfelder (1952), studying chemical kinetics. There is no single satisfactory mathematical definition; Hairer and Wanner’s operational one is: a problem is stiff when explicit methods do not work, in the sense that stability rather than accuracy dictates step size. The typical cause is a Jacobian with some eigenvalues of very negative real part (almost instantly decaying modes) alongside a solution varying slowly after the transient. With y′=−1000 (y−cos⁡t)−sin⁡ty' = -1000\,(y - \cos t) - \sin t, solution cos⁡t\cos t is smooth and well approximated with h=0.1h = 0.1, but mode e−1000te^{-1000t} forces explicit Euler to use h≤0.002h \le 0.002 throughout integration, even after that mode has long disappeared. Each step error excites the stiff mode, and if hλ∉Sh\lambda \notin \mathcal{S}, amplifies it. This is stiffness and implicit methods: the remedy is a method whose stability region contains those hλh\lambda.

Symptoms in an adaptive explicit integrator are unmistakable:

  • it takes many nearly constant steps of order 3/∣λmax⁡∣3/\abs{\lambda_{\max}} even though solution barely changes;
  • it regularly rejects steps: controller tries lengthening hh, exits the stability region, estimated error spikes and it goes back;
  • loosening tolerance barely reduces cost, because tolerance does not limit the step.

The last is the most reliable diagnosis. In the lab RK45 needs 4712 evaluations to advance Robertson reaction from t=0t = 0 to t=1t = 1, whereas BDF reaches t=1011t = 10^{11} with 1782.

InteractiveVan der Pol stiffness
Solution y1(t)y_1(t)
Step size hh (log scale)
10⁻⁵10⁻⁴10⁻³10⁻²10⁻¹110081163244t = 326
  • Dormand–Prince 5(4), explicit
  • Variable-step BDF2, implicit
  • DP5 stability limit

μ = 100: 17,675 explicit steps versus 1,468 implicit steps.

100
Two periods[0, 326]
rtol / atol10⁻⁴ / 10⁻⁶
DP5: steps (rejections)17,675 (2,835)
DP5: f evaluations123,062
BDF2: steps (rejections)1,468 (74)
BDF2: f evaluations3,278
BDF2: Newton systems3,276
Evaluations: explicit / implicit38×
With μ=100\mu = 100 the explicit method needs 38 times more evaluations. On slow branches its step is set by h∣λ∣≤3.31h\abs{\lambda} \le 3.31, not the tolerance.
Van der Pol oscillator, y1′=y2y_1' = y_2, y2′=μ(1−y12)y2−y1y_2' = \mu(1 - y_1^2)y_2 - y_1, integrated over two periods by Dormand–Prince 5(4) (explicit) and variable-step BDF2 with Newton (implicit), at the same tolerances. Above, solution; below, each step size and dashed DP5 stability limit calculated from Jacobian eigenvalues at each point. Start at μ=100\mu = 100: what sets explicit step size on slow branches? Lower to μ=1\mu = 1 for the nonstiff case, then raise to 1000.

With μ=1\mu = 1 the problem is not stiff and explicit order 5 clearly beats implicit order 2: 392 ff evaluations versus 839. At μ=10\mu = 10 they tie, and at μ=100\mu = 100 explicit needs about 38 times more. From μ≈10\mu \approx 10 solution alternates slow segments, with y1y_1 crawling between ±2\pm 2 and ±1\pm 1, and rapid jumps. On slow segments the Jacobian has an eigenvalue near μ(1−y12)\mu(1 - y_1^2), very negative, and DP5 step hugs the dashed curve: not tolerance but h∣λ∣≲3.3h\abs{\lambda} \lesssim 3.3 sets it. Implicit, by contrast, lengthens steps on slow segments and shortens only on jumps, where solution truly changes quickly. Explicit cost grows as μ2\mu^2 (interval grows as μ\mu and stable step shrinks as 1/μ1/\mu): in the interactive, from μ=100\mu = 100 to μ=300\mu = 300 evaluations grow from about 1.2⋅1051.2\cdot 10^5 to 1.1⋅1061.1\cdot 10^6, factor 9. Implicit across μ=100\mu = 100 to μ=1000\mu = 1000 only grows from about 3300 to 4400.

Implicit methods in practice

An implicit method solves a nonlinear system each step whose Jacobian is I−hγJ\mat{I} - h\gamma\mat{J} for a method-specific γ\gamma. For dimension dd and dense Jacobian, each factorization costs O(d3)\bigO(d^3) and each solve O(d2)\bigO(d^2); codes therefore reuse factorization while Newton converges and only recalculate J\mat{J} when necessary. If J\mat{J} is sparse (discretized PDEs), supply its pattern with jac_sparsity and use sparse factorizations from Krylov methods and sparse matrices. Three families in libraries:

  • BDF (backward differentiation formulas). The kk-step version fits a polynomial to yn+1,yn,…,yn+1−k\vb{y}_{n+1}, \vb{y}_n, \dots, \vb{y}_{n+1-k} and requires its derivative at tn+1t_{n+1} to be f(tn+1,yn+1)f(t_{n+1}, \vb{y}_{n+1}). BDF1 is implicit Euler; fixed-step BDF2 is 32yn+1−2yn+12yn−1=hf(tn+1,yn+1)\tfrac32\vb{y}_{n+1} - 2\vb{y}_n + \tfrac12\vb{y}_{n-1} = h f(t_{n+1}, \vb{y}_{n+1}). They need one ff evaluation and one system per step; preferred for large systems. scipy BDF has variable order 1 to 5, with Shampine and Reichelt’s (1997) NDF formulas.
  • Radau IIA. Three-stage order-5 implicit Runge–Kutta, L-stable; its stability function is the (2,3)(2, 3) Padé approximant of eze^z. Solves a dimension-3d3d system per step (decomposed into one real and one complex dimension-dd system). Accurate choice for stiff problems: scipy Radau follows Hairer and Wanner’s RADAU5 code.
  • LSODA (Petzold, 1983). Detects stiffness on the fly and switches between Adams methods (solved by functional iteration, without Jacobian, like an explicit method) and BDF. A good default when stiffness is unknown or regime changes.

scipy documentation summarizes the choice: RK45 or RK23 for nonstiff problems (DOP853 for high accuracy); Radau or BDF for stiff ones; if RK45 takes unusual numbers of steps, diverges or fails, the problem is probably stiff.

Geometric integration: Hamiltonian systems

In an orbit or molecular dynamics simulation the problem is not stiffness but time: millions of steps are integrated and what matters is that conserved quantities do not drift. No integrator preserves everything, but some preserve the structure causing energy conservation.

Hamiltonian systems and symplecticity

A Hamiltonian system with positions q∈Rm\vb{q} \in \R^m and momenta p∈Rm\vb{p} \in \R^m is

q′=∇pH(q,p),p′=−∇qH(q,p),\vb{q}' = \nabla_{\vb{p}}H(\vb{q}, \vb{p}), \qquad \vb{p}' = -\nabla_{\vb{q}}H(\vb{q}, \vb{p}),

or, with y=(q,p)\vb{y} = (\vb{q}, \vb{p}) and Ω=[0I−I0]\mat{\Omega} = \begin{bmatrix} \mat{0} & \mat{I} \\ -\mat{I} & \mat{0}\end{bmatrix}, y′=Ω−1∇H(y)\vb{y}' = \mat{\Omega}\inv\nabla H(\vb{y}). Energy HH is conserved:  ⁣d ⁣dtH=∇qH⋅q′+∇pH⋅p′=0\frac{\dd}{\dd t}H = \nabla_{\vb{q}}H\cdot\vb{q}' + \nabla_{\vb{p}}H\cdot\vb{p}' = 0. Its flow φt\varphi_t is also symplectic: its Jacobian satisfies φt′(y)⊤Ω φt′(y)=Ω\varphi_t'(\vb{y})\T\mat{\Omega}\,\varphi_t'(\vb{y}) = \mat{\Omega} (Poincaré). With one degree of freedom this equals det⁡φt′=1\det\varphi_t' = 1: the flow preserves area in phase space. The commonest case is separable, H=T(p)+V(q)H = T(\vb{p}) + V(\vb{q}) with T=12p⊤M−1pT = \tfrac12\vb{p}\T\mat{M}\inv\vb{p}: masses in a potential.

Look at explicit Euler on harmonic oscillator q′=pq' = p, p′=−ω2qp' = -\omega^2 q, energy H=12p2+12ω2q2H = \tfrac12 p^2 + \tfrac12\omega^2 q^2. One step gives qn+1=qn+hpnq_{n+1} = q_n + hp_n, pn+1=pn−hω2qnp_{n+1} = p_n - h\omega^2 q_n, and direct calculation shows

H(qn+1,pn+1)=(1+h2ω2) H(qn,pn).H(q_{n+1}, p_{n+1}) = (1 + h^2\omega^2)\,H(q_n, p_n).

Energy grows by a fixed factor each step: Euler’s outward spiral is exponential. The step Jacobian has determinant 1+h2ω2>11 + h^2\omega^2 > 1: explicit Euler expands phase-space area.

Why symplectic? Each composes two “shear” maps: (q,p)↦(q,p−h∇V(q))(\vb{q}, \vb{p}) \mapsto (\vb{q}, \vb{p} - h\nabla V(\vb{q})), with Jacobian [I0SI]\begin{bmatrix} \mat{I} & \mat{0} \\ \mat{S} & \mat{I}\end{bmatrix} and symmetric S=−h∇2V\mat{S} = -h\nabla^2 V, and (q,p)↦(q+hM−1p,p)(\vb{q}, \vb{p}) \mapsto (\vb{q} + h\mat{M}\inv\vb{p}, \vb{p}), analogous with the block above. Block calculation gives

[I0SI]⊤Ω[I0SI]=[S−S⊤I−I0]=Ω  ⟺  S=S⊤,\begin{bmatrix} \mat{I} & \mat{0} \\ \mat{S} & \mat{I}\end{bmatrix}\T\mat{\Omega}\begin{bmatrix} \mat{I} & \mat{0} \\ \mat{S} & \mat{I}\end{bmatrix} = \begin{bmatrix} \mat{S} - \mat{S}\T & \mat{I} \\ -\mat{I} & \mat{0}\end{bmatrix} = \mat{\Omega} \iff \mat{S} = \mat{S}\T,

and composition of symplectic maps is symplectic by the chain rule. Leapfrog composes half kick, drift and half kick. The method, popularized in molecular dynamics by Verlet in 1967, was already used by Störmer in 1907 to calculate charged-particle paths in Earth’s magnetic field.

A general Runge–Kutta method has an algebraic criterion (Sanz-Serna, 1988; Lasagni, 1988; Suris, 1988): it is symplectic if and only if biaij+bjaji−bibj=0b_i a_{ij} + b_j a_{ji} - b_i b_j = 0 for all i,ji, j. With i=ji = j this requires 2biaii=bi22b_i a_{ii} = b_i^2; for an explicit method aii=0a_{ii} = 0, so every bib_i would vanish, contradicting ∑bi=1\sum b_i = 1. No explicit Runge–Kutta is symplectic, including RK4. Implicit midpoint (s=1s = 1, a11=12a_{11} = \tfrac12, b1=1b_1 = 1) is, and we will use it for a double pendulum whose Hamiltonian is not separable.

Why energy remains bounded

A symplectic integrator does not exactly preserve HH. What it does is better than it looks: backward error analysis shows that for analytic HH, iterates of an order-pp symplectic method coincide, up to exponentially small error, with the exact solution of a modified Hamiltonian

H~=H+hpHp+1+hp+1Hp+2+⋯ ,\tilde H = H + h^p H_{p+1} + h^{p+1}H_{p+2} + \cdots,

and as H~\tilde H is exactly conserved along its own flow, H(yn)−H(y0)=O(hp)H(\vb{y}_n) - H(\vb{y}_0) = \bigO(h^p) for exponentially long times, nh≤ec/hnh \le e^{c/h} (Benettin and Giorgilli, 1994; Hairer and Lubich, 1997; Hairer, Lubich and Wanner, ch. IX). For the harmonic oscillator one sees it without approximation: leapfrog preserves exactly

H~(q,p)=12p2+12ω2q2(1−h2ω24),\tilde H(q, p) = \tfrac12 p^2 + \tfrac12\omega^2 q^2\left(1 - \tfrac{h^2\omega^2}{4}\right),

as substitution of one step verifies. While hω<2h\omega < 2, H~\tilde H is positive definite, its level curves are closed ellipses and HH oscillates bounded, with relative amplitude O(h2)\bigO(h^2), forever.

RK4 is not symplectic. On the oscillator, ∣R(ihω)∣2=1−(hω)6/72+(hω)8/576\abs{R(ih\omega)}^2 = 1 - (h\omega)^6/72 + (h\omega)^8/576, slightly below 1: it loses a fixed energy fraction each step, tiny but systematic drift proportional to nn after nn steps. With local error order h5h^5 and secular drift, RK4 energy moves linearly away over time; leapfrog’s, with order-h2h^2 error, never moves away. RK4 wins short-term; symplectic always wins long-term. For integrable problems like Kepler there is also a trajectory result: global error of a symplectic method grows like tt and a nonsymplectic one like t2t^2 (Hairer, Lubich and Wanner, ch. X).

InteractiveIntegrator duel on an orbit
  • exact orbit
  • Euler explícito
  • RK4
  • Leapfrog
  • Sun (focus)
  • Euler explícito
  • RK4
  • Leapfrog
0.50
100
1000
Comparison
orbit 0 of 1000
Step: RK4 / others0.06283 / 0.06283
Euler explícito: ∣ΔE/E0∣\abs{\Delta E / E_0}0
RK4: ∣ΔE/E0∣\abs{\Delta E / E_0}0
Leapfrog: ∣ΔE/E0∣\abs{\Delta E / E_0}0
Force evaluations: RK4 / leapfrog400 k / 100 k
Euler gains energy each orbit until the orbit opens (energy ≥0\ge 0) at orbit 7.5. At the end, leapfrog conserves energy better than RK4 (0.0106 versus 0.0299): its error does not grow over time, while RK4’s does.
A Kepler orbit integrated simultaneously with explicit Euler, RK4 and leapfrog. Above, the revolution each method traces at the selected time over the exact orbit; below, relative energy error (maximum per window) versus number of revolutions on a log scale. Play with initial values: 100 steps per revolution for 1000 revolutions. Then shorten to 30 revolutions: who conserves energy better short-term? Finally switch to ‘same cost’, giving Euler and leapfrog steps 4 times smaller than RK4 to equalize force evaluations.

Three things the duel shows and the second lab quantifies. Explicit Euler gains energy every revolution until the orbit opens and the body escapes. RK4 slowly loses energy in a straight line on the plot: its orbit closes toward the Sun. Leapfrog starts with greater energy error than RK4 (order 2 versus 4) but stays in that band; its orbit precesses, rotating slowly, because phase error accumulates: what is preserved is orbit shape, not planet position on it.

This property matters outside celestial mechanics. Hamiltonian Monte Carlo proposes jumps by integrating a fictional Hamiltonian system with leapfrog: it needs a volume-preserving, reversible integrator for exact Metropolis correction, and bounded energy keeps acceptance probability high on long trajectories.

Lab 1: integrators from scratch

Start with the three basic integrators written for systems: f(t, y) functions receiving and returning NumPy arrays. Implicit Euler solves each step with Newton and LU (np.linalg.solve uses LAPACK LU with partial pivoting). Test problem is y′=−2ty2y' = -2ty^2, y(0)=1y(0) = 1, solution y=1/(1+t2)y = 1/(1 + t^2); measure both global error at t=2t = 2 and local error of one step starting from exact solution at t=0.5t = 0.5.

[ ]Euler, implicit Euler and RK4: local and global errorsBrowser
import numpy as np

def euler_paso(f, t, y, h):
    return y + h * f(t, y)

def rk4_paso(f, t, y, h):
    k1 = f(t, y)
    k2 = f(t + h / 2, y + h / 2 * k1)
    k3 = f(t + h / 2, y + h / 2 * k2)
    k4 = f(t + h, y + h * k3)
    return y + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

def euler_implicito_paso(f, jac, t, y, h, tol=1e-12, max_iter=20):
    """Resuelve Y - y - h f(t+h, Y) = 0 con Newton; cada iteración es un sistema lineal (LU con pivoteo)."""
    Y = y + h * f(t, y)                      # predicción explícita
    I = np.eye(len(y))
    for it in range(max_iter):
        G = Y - y - h * f(t + h, Y)
        dY = np.linalg.solve(I - h * jac(t + h, Y), -G)
        Y = Y + dY
        if np.linalg.norm(dY) <= tol * (1 + np.linalg.norm(Y)):
            return Y, it + 1
    raise RuntimeError("Newton no converge: reduce h")

def integra(paso, f, t0, y0, T, n, **kw):
    h = (T - t0) / n
    t, y = t0, np.array(y0, dtype=float)
    for _ in range(n):
        y = paso(f, t, y, h, **kw) if not kw else paso(f, kw["jac"], t, y, h)[0]
        t += h
    return y

f = lambda t, y: -2 * t * y**2
jac = lambda t, y: np.array([[-4 * t * y[0]]])
exacta = lambda t: 1 / (1 + t**2)

ns = np.array([10, 20, 40, 80, 160, 320, 640])
hs = 2.0 / ns
for nombre, paso, kw in [("Euler", euler_paso, {}), ("Euler implícito", euler_implicito_paso, {"jac": jac}), ("RK4", rk4_paso, {})]:
    glob = np.array([abs(integra(paso, f, 0, [1.0], 2.0, n, **kw)[0] - exacta(2.0)) for n in ns])
    loc = []
    for h in hs:
        y1 = paso(f, 0.5, np.array([exacta(0.5)]), h) if not kw else paso(f, jac, 0.5, np.array([exacta(0.5)]), h)[0]
        loc.append(abs(y1[0] - exacta(0.5 + h)))
    pg = np.polyfit(np.log(hs), np.log(glob), 1)[0]
    pl = np.polyfit(np.log(hs), np.log(loc), 1)[0]
    print(f"{nombre:16s} error global con h = {hs[-1]:.4f}: {glob[-1]:.2e}   pendiente global {pg:.2f}   pendiente local {pl:.2f}")

Slopes match theory: local error of Euler and implicit Euler falls as h2h^2 and global as hh; RK4 as h5h^5 and h4h^4. Now the earlier stiff problem, y′=−1000 (y−cos⁡t)−sin⁡ty' = -1000\,(y - \cos t) - \sin t with y(0)=1y(0) = 1, on [0,2][0, 2]:

[ ]A stiff problem: explicit versus implicit EulerBrowser
import numpy as np

lam = 1000.0
f = lambda t, y: -lam * (y - np.cos(t)) - np.sin(t)
jac = lambda t, y: np.array([[-lam]])

def euler_hasta(T, h):
    t, y = 0.0, np.array([1.0])
    for _ in range(int(round(T / h))):
        y = y + h * f(t, y); t += h
    return y[0]

def implicito_hasta(T, h):
    t, y, its = 0.0, np.array([1.0]), 0
    for _ in range(int(round(T / h))):
        y, k = euler_implicito_paso(f, jac, t, y, h); t += h; its += k
    return y[0], its

for h in [0.0019, 0.0021, 0.0025]:
    print(f"Euler explícito, h = {h}: y(2) = {euler_hasta(2.0, h):.4g}   (exacta {np.cos(2.0):.6f})")
for h in [0.1, 0.01]:
    y2, its = implicito_hasta(2.0, h)
    print(f"Euler implícito, h = {h}: y(2) = {y2:.6f}   error {abs(y2 - np.cos(2.0)):.1e}   iteraciones de Newton {its}")

With h=0.0019h = 0.0019 explicit Euler succeeds; with h=0.0021h = 0.0021, outside h≤2/1000h \le 2/1000, numerical solution explodes (each step multiplies perturbation by ∣1−2.1∣=1.1\abs{1 - 2.1} = 1.1, and over 952 steps that is factor 1.1952≈10391.1^{952} \approx 10^{39}). Implicit Euler with a 50-times-larger step gives four correct digits (error 1.9⋅10−51.9\cdot 10^{-5}), and since the problem is linear in yy, Newton converges in one iteration per step (plus a check).

Generic Runge–Kutta from its Butcher tableau

One integrator serves any explicit method if given tableau (A,b,c)(\mat{A}, \vb{b}, \vb{c}). Exact rational arithmetic also verifies eight order-4 conditions and computes coefficients of R(z)=1+∑k≥1zk b⊤Ak−11R(z) = 1 + \sum_{k \ge 1} z^k\,\vb{b}\T\mat{A}^{k-1}\mathbb{1}.

[ ]Explicit Runge–Kutta from its tableauBrowser
import numpy as np
from fractions import Fraction as F

def rk_paso(f, t, y, h, A, b, c):
    s = len(b)
    k = []
    for i in range(s):
        yi = y + h * sum(float(A[i][j]) * k[j] for j in range(i)) if i else y
        k.append(f(t + float(c[i]) * h, yi))
    return y + h * sum(float(b[i]) * k[i] for i in range(s))

def tabla(A, b):
    A = [[F(x) for x in fila] + [F(0)] * (len(b) - len(fila)) for fila in A]
    return A, [F(x) for x in b], [sum(fila, F(0)) for fila in A]

TABLAS = {
    "Euler": tabla([[0]], [1]),
    "punto medio": tabla([[0], [F(1, 2)]], [0, 1]),
    "Kutta 3/8": tabla([[0], [F(1, 3)], [F(-1, 3), 1], [1, -1, 1]], [F(1, 8), F(3, 8), F(3, 8), F(1, 8)]),
    "RK4": tabla([[0], [F(1, 2)], [0, F(1, 2)], [0, 0, 1]], [F(1, 6), F(1, 3), F(1, 3), F(1, 6)]),
    "Dormand-Prince 5": tabla(
        [[0], [F(1, 5)], [F(3, 40), F(9, 40)], [F(44, 45), F(-56, 15), F(32, 9)],
         [F(19372, 6561), F(-25360, 2187), F(64448, 6561), F(-212, 729)],
         [F(9017, 3168), F(-355, 33), F(46732, 5247), F(49, 176), F(-5103, 18656)],
         [F(35, 384), 0, F(500, 1113), F(125, 192), F(-2187, 6784), F(11, 84)]],
        [F(35, 384), 0, F(500, 1113), F(125, 192), F(-2187, 6784), F(11, 84), 0]),
}

def condiciones(A, b, c):
    s = len(b)
    Ac = [sum(A[i][j] * c[j] for j in range(s)) for i in range(s)]
    Ac2 = [sum(A[i][j] * c[j]**2 for j in range(s)) for i in range(s)]
    AAc = [sum(A[i][j] * Ac[j] for j in range(s)) for i in range(s)]
    lados = [sum(b), sum(bi * ci for bi, ci in zip(b, c)), sum(bi * ci**2 for bi, ci in zip(b, c)),
             sum(bi * x for bi, x in zip(b, Ac)), sum(bi * ci**3 for bi, ci in zip(b, c)),
             sum(bi * ci * x for bi, ci, x in zip(b, c, Ac)), sum(bi * x for bi, x in zip(b, Ac2)),
             sum(bi * x for bi, x in zip(b, AAc))]
    objetivo = [F(1), F(1, 2), F(1, 3), F(1, 6), F(1, 4), F(1, 8), F(1, 12), F(1, 24)]
    orden_de = [1, 2, 3, 3, 4, 4, 4, 4]
    ok = [l == o for l, o in zip(lados, objetivo)]
    p = 0
    for q in (1, 2, 3, 4):
        if all(ok[i] for i in range(8) if orden_de[i] <= q):
            p = q
    return p

def coef_R(A, b):
    s = len(b)
    v = [F(1)] * s                       # A^0 · 1
    out = [F(1)]
    for k in range(1, s + 1):
        out.append(sum(bi * vi for bi, vi in zip(b, v)))
        v = [sum(A[i][j] * v[j] for j in range(s)) for i in range(s)]
    while out and out[-1] == 0:
        out.pop()
    return out

f = lambda t, y: -2 * t * y**2
for nombre, (A, b, c) in TABLAS.items():
    errs = []
    for n in (20, 40, 80, 160):
        h, y = 2.0 / n, np.array([1.0])
        for i in range(n):
            y = rk_paso(f, i * h, y, h, A, b, c)
        errs.append(abs(y[0] - 0.2))
    pend = np.polyfit(np.log(2.0 / np.array([20, 40, 80, 160])), np.log(errs), 1)[0]
    print(f"{nombre:16s} etapas {len(b)}  condiciones hasta orden {condiciones(A, b, c)}  pendiente medida {pend:.2f}")
    print(f"{'':16s} R(z) = " + " + ".join(f"({r}) z^{k}" for k, r in enumerate(coef_R(A, b))))

Algebraic conditions and measured slopes agree. Rational check only reaches order 4 (order 5 requires nine more conditions), but Dormand–Prince slope confirms order 5 while error stays above rounding. Its stability function, ∑k≤5zk/k!+z6/600\sum_{k \le 5} z^k/k! + z^6/600, is drawn by the region explorer.

Adaptive step from scratch: Bogacki–Shampine pair

A complete adaptive-integrator skeleton with Bogacki–Shampine 3(2) pair (scipy RK23): four stages, last reusable (FSAL), Hairer, Nørsett and Wanner initial step and scipy’s controller. If correct it should take nearly identical steps to solve_ivp(method="RK23"). Check on a Kepler orbit of eccentricity 0.9.

[ ]Adaptive RK23 from scratch versus solve_ivpBrowser
import numpy as np
from scipy.integrate import solve_ivp

def norma(x, escala):
    return np.sqrt(np.mean((x / escala) ** 2))

def paso_inicial(f, t0, y0, f0, rtol, atol, orden_est):
    escala = atol + rtol * np.abs(y0)
    d0, d1 = norma(y0, escala), norma(f0, escala)
    h0 = 1e-6 if d0 < 1e-5 or d1 < 1e-5 else 0.01 * d0 / d1
    f1 = f(t0 + h0, y0 + h0 * f0)
    d2 = norma(f1 - f0, escala) / h0
    h1 = max(1e-6, h0 * 1e-3) if max(d1, d2) <= 1e-15 else (0.01 / max(d1, d2)) ** (1 / (orden_est + 1))
    return min(100 * h0, h1)

def rk23(f, t_span, y0, rtol=1e-3, atol=1e-6):
    t, T = t_span
    y = np.array(y0, dtype=float)
    k1 = f(t, y); nfev = 2
    h = min(paso_inicial(f, t, y, k1, rtol, atol, 2), T - t)
    ts, ys, rechazos = [t], [y], 0
    while t < T:
        h = min(h, T - t)
        rechazado = False
        while True:
            k2 = f(t + h / 2, y + h / 2 * k1)
            k3 = f(t + 3 * h / 4, y + 3 * h / 4 * k2)
            y_nuevo = y + h * (2 / 9 * k1 + 1 / 3 * k2 + 4 / 9 * k3)      # orden 3
            k4 = f(t + h, y_nuevo); nfev += 3                             # FSAL: k4 es el k1 siguiente
            e = h * (-5 / 72 * k1 + 1 / 12 * k2 + 1 / 9 * k3 - 1 / 8 * k4)  # orden 3 menos orden 2
            err = norma(e, atol + rtol * np.maximum(np.abs(y), np.abs(y_nuevo)))
            if err <= 1:
                factor = 10 if err == 0 else min(10, 0.9 * err ** (-1 / 3))
                if rechazado:
                    factor = min(1, factor)
                t, y, k1 = t + h, y_nuevo, k4
                h *= factor
                break
            h *= max(0.2, 0.9 * err ** (-1 / 3)); rechazado = True; rechazos += 1
        ts.append(t); ys.append(y)
    return np.array(ts), np.array(ys).T, nfev, rechazos

def kepler(t, y):
    r3 = (y[0]**2 + y[1]**2) ** 1.5
    return np.array([y[2], y[3], -y[0] / r3, -y[1] / r3])

e = 0.9
y0 = np.array([1 - e, 0.0, 0.0, np.sqrt((1 + e) / (1 - e))])
for rtol in (1e-3, 1e-5, 1e-7):
    atol = rtol * 1e-2
    ts, ys, nfev, rech = rk23(kepler, (0, 2 * np.pi), y0, rtol, atol)
    ref = solve_ivp(kepler, (0, 2 * np.pi), y0, method="RK23", rtol=rtol, atol=atol)
    err = np.hypot(*(ys[:2, -1] - y0[:2]))
    print(f"rtol = {rtol:.0e}: desde cero {len(ts) - 1:5d} pasos, {nfev:5d} evaluaciones, {rech:3d} rechazos, "
          f"error de posición tras una vuelta {err:.1e}   |   scipy RK23 {len(ref.t) - 1:5d} pasos, {ref.nfev:5d} evaluaciones")

Both integrators take exactly the same steps and evaluations (61, 250 and 1164 steps), so the skeleton reproduces scipy’s algorithm. Error after one orbit falls with tolerance, although not by the same factor: dividing rtol by 100 lowers it about 55 and 86 times. Dormand–Prince is the same skeleton with seven stages and exponent 1/51/5: implement it in the final code exercise, whose tests compare steps to RK45.

Where an adaptive integrator places steps

With scipy RK45 measure what the comet figure showed: slope of log⁡h\log h versus log⁡r\log r, longest-to-shortest step ratio and global-error response to tolerance. The last part checks that requesting solutions at 1000 times with t_eval changes neither steps nor error.

[ ]RK45 on eccentric orbits: h versus r, tolerances and t_evalBrowser
import numpy as np
from scipy.integrate import solve_ivp

for e in (0.5, 0.9, 0.97):
    y0 = [1 - e, 0.0, 0.0, np.sqrt((1 + e) / (1 - e))]
    for rtol in (1e-4, 1e-6, 1e-8):
        s = solve_ivp(kepler, (0, 2 * np.pi), y0, method="RK45", rtol=rtol, atol=rtol * 1e-2)
        h = np.diff(s.t)[2:-1]                       # sin el arranque ni el último paso, recortado para llegar a T
        r = np.hypot(s.y[0], s.y[1])[2:-2]
        pend = np.polyfit(np.log(r), np.log(h), 1)[0]
        err = np.hypot(s.y[0, -1] - y0[0], s.y[1, -1] - y0[1])
        print(f"e = {e}, rtol = {rtol:.0e}: {len(s.t) - 1:4d} pasos, {s.nfev:5d} evaluaciones, "
              f"pendiente {pend:.2f}, h_max/h_min = {h.max() / h.min():6.0f}, error tras una vuelta {err:.1e}")

y0 = [0.1, 0.0, 0.0, np.sqrt(1.9 / 0.1)]
a = solve_ivp(kepler, (0, 2 * np.pi), y0, rtol=1e-6, atol=1e-8)
b = solve_ivp(kepler, (0, 2 * np.pi), y0, rtol=1e-6, atol=1e-8, t_eval=np.linspace(0, 2 * np.pi, 1000))
print(f"\nsin t_eval: {a.nfev} evaluaciones, y(2π) = {a.y[:2, -1]}")
print(f"con t_eval: {b.nfev} evaluaciones, y(2π) = {b.y[:2, -1]}, {b.t.size} salidas")

Slope remains between 1.41 and 1.51 in nine cases, near 3/23/2 predicted by local dynamical time; the furthest, 1.51 with rtol = 1e-4 and e=0.5e = 0.5, comes from a fit with only 17 steps. Longest-to-shortest ratio increases with eccentricity: 7 or 8 with e=0.5e = 0.5, 115 to 129 with e=0.9e = 0.9 and 887 to 986 with e=0.97e = 0.97. Law h∝r3/2h \propto r^{3/2} applied to rmax⁡/rmin⁡=(1+e)/(1−e)r_{\max}/r_{\min} = (1 + e)/(1 - e) predicts 5, 83 and 532: same order of magnitude, with measured ratios somewhat larger because they compare individual fluctuating steps rather than fitted line. And t_eval changes nothing: same evaluations, same result, because 1000 outputs come from the interpolant.

solve_ivp on nonstiff and stiff problems

Robertson’s reaction (1966) is the classical stiffness benchmark:

y1′=−0.04 y1+104y2y3,y2′=0.04 y1−104y2y3−3⋅107y22,y3′=3⋅107y22,y_1' = -0.04\,y_1 + 10^4 y_2 y_3, \qquad y_2' = 0.04\,y_1 - 10^4 y_2 y_3 - 3\cdot 10^7 y_2^2, \qquad y_3' = 3\cdot 10^7 y_2^2,

with y(0)=(1,0,0)\vb{y}(0) = (1, 0, 0). Constants range from 0.040.04 to 3⋅1073\cdot 10^7 and y2y_2 lives at scale 10−510^{-5}, so needs its own atol. Explicit methods are run only to t=1t = 1: beyond that they would be too slow for the browser.

[ ]Robertson: explicit versus implicit methodsBrowser
import numpy as np
from scipy.integrate import solve_ivp

def robertson(t, y):
    y1, y2, y3 = y
    return [-0.04 * y1 + 1e4 * y2 * y3, 0.04 * y1 - 1e4 * y2 * y3 - 3e7 * y2**2, 3e7 * y2**2]

def robertson_jac(t, y):
    y1, y2, y3 = y
    return [[-0.04, 1e4 * y3, 1e4 * y2], [0.04, -1e4 * y3 - 6e7 * y2, -1e4 * y2], [0, 6e7 * y2, 0]]

atol = [1e-8, 1e-14, 1e-8]
finales = {}
print("método  t final   pasos  evaluaciones  jacobianos  LU    y(t final)")
for metodo, T in [("RK45", 1.0), ("DOP853", 1.0), ("Radau", 1.0), ("BDF", 1.0), ("LSODA", 1.0),
                  ("Radau", 1e5), ("BDF", 1e5), ("LSODA", 1e5), ("BDF", 1e11)]:
    kw = {"jac": robertson_jac} if metodo in ("Radau", "BDF", "LSODA") else {}
    s = solve_ivp(robertson, (0, T), [1, 0, 0], method=metodo, rtol=1e-6, atol=atol, **kw)
    finales[T] = s.y[:, -1]
    print(f"{metodo:7s} {T:8.0e} {len(s.t) - 1:6d} {s.nfev:12d} {s.njev:10d} {s.nlu:5d}   {np.array2string(s.y[:, -1], precision=4)}")

# el síntoma: relajar la tolerancia casi no abarata el método explícito
for rtol in (1e-3, 1e-6):
    s = solve_ivp(robertson, (0, 1.0), [1, 0, 0], method="RK45", rtol=rtol, atol=[x * rtol / 1e-6 for x in atol])
    print(f"RK45 con rtol = {rtol:.0e}: {s.nfev} evaluaciones")

for T in (1.0, 1e5, 1e11):
    lam = np.linalg.eigvals(np.array(robertson_jac(T, finales[T])))
    print(f"t = {T:.0e}: autovalor más negativo del jacobiano {lam.real.min():.4g}, paso máximo de Euler explícito {2 / abs(lam.real.min()):.1e}")

Numbers tell the stiffness story. To t=1t = 1, RK45 needs 678 steps and 4712 evaluations and DOP853 4310, whereas BDF and LSODA stay below 250 and Radau around 400. With tolerance a thousand times looser, RK45 does not get cheaper at all (4868 evaluations versus 4712): its step is set by the Jacobian’s most negative eigenvalue, about −2.2⋅103-2.2\cdot 10^3 at t=1t = 1, not accuracy. With DP5 boundary at −3.31-3.31, stable step is about 1.5⋅10−31.5\cdot 10^{-3}, roughly 660 steps per unit time: just the 678 observed. Implicit methods reach t=105t = 10^5 in hundreds of steps and BDF reaches t=1011t = 10^{11} in 624, because as reaction calms they lengthen step without stability limit. Explicit cannot: fast eigenvalue remains and approaches −104-10^4, so explicit Euler would need steps 2⋅10−42\cdot 10^{-4} and about 5⋅10145\cdot 10^{14} steps to reach t=1011t = 10^{11}. Notice Jacobian column: BDF evaluates J\mat{J} between 2 and 22 times and reuses factorizations across many steps.

The figure’s Van der Pol oscillator, now with scipy methods:

[ ]Van der Pol: each method’s cost as μ growsBrowser
import numpy as np
from scipy.integrate import solve_ivp

periodos = {1: 6.663, 10: 19.078, 100: 162.837, 1000: 1614.401}   # calculados con Radau, rtol = 1e-10
print("   μ   método   pasos  evaluaciones  LU")
for mu, P in periodos.items():
    f = lambda t, y, mu=mu: [y[1], mu * (1 - y[0]**2) * y[1] - y[0]]
    jac = lambda t, y, mu=mu: [[0, 1], [-2 * mu * y[0] * y[1] - 1, mu * (1 - y[0]**2)]]
    metodos = ["RK45", "Radau", "BDF", "LSODA"] if mu <= 10 else ["Radau", "BDF", "LSODA"]
    for m in metodos:
        kw = {} if m == "RK45" else {"jac": jac}
        s = solve_ivp(f, (0, 2 * P), [2, 0], method=m, rtol=1e-4, atol=1e-6, **kw)
        print(f"{mu:5d}   {m:6s} {len(s.t) - 1:6d} {s.nfev:12d} {s.nlu:4d}")
    if mu == 100:
        s = solve_ivp(f, (0, P / 4), [2, 0], method="RK45", rtol=1e-4, atol=1e-6)
        print(f"{mu:5d}   RK45 solo hasta t = {P / 4:.0f}: {len(s.t) - 1} pasos, {s.nfev} evaluaciones")

With μ=1\mu = 1, RK45 is cheapest (392 evaluations); with μ=10\mu = 10, LSODA and BDF already beat it. With μ=100\mu = 100, a quarter period alone needs 20 882 evaluations, more than any implicit method for two full periods, and with μ=1000\mu = 1000 we do not try: the interactive, using the same Dormand–Prince pair and controller (and identical steps to RK45 for μ=1\mu = 1 and μ=10\mu = 10), estimates about 2.5 million steps. LSODA adapts to both regimes automatically.

Lab 2: energy, chaos and symplecticity

Kepler for 10510^5 steps

The duel orbit, eccentricity 0.5 and 100 steps per revolution, for 1000 revolutions: 10510^5 steps per method. The loop uses Python scalars rather than NumPy arrays, slower for four numbers of state. Record relative energy error at the end of revolutions 1, 10, 100 and 1000 and its maximum over all integration.

[ ]Kepler: Euler, RK4 and leapfrog for 10⁵ stepsBrowser
import math

def energia(x, y, vx, vy):
    return 0.5 * (vx * vx + vy * vy) - 1 / math.sqrt(x * x + y * y)

def aceleracion(x, y):
    r2 = x * x + y * y
    k = 1 / (r2 * math.sqrt(r2))
    return -x * k, -y * k

def kepler_fijo(metodo, e, pasos_vuelta, vueltas):
    x, y, vx, vy = 1 - e, 0.0, 0.0, math.sqrt((1 + e) / (1 - e))
    E0 = energia(x, y, vx, vy)
    h = 2 * math.pi / pasos_vuelta
    ax, ay = aceleracion(x, y)
    registro, peor = {}, 0.0
    for i in range(1, pasos_vuelta * vueltas + 1):
        if metodo == "Euler":
            x, y, vx, vy = x + h * vx, y + h * vy, vx + h * ax, vy + h * ay
            ax, ay = aceleracion(x, y)
        elif metodo == "leapfrog":
            vx += 0.5 * h * ax; vy += 0.5 * h * ay
            x += h * vx; y += h * vy
            ax, ay = aceleracion(x, y)
            vx += 0.5 * h * ax; vy += 0.5 * h * ay
        else:  # RK4
            a1 = (ax, ay)
            a2 = aceleracion(x + 0.5 * h * vx, y + 0.5 * h * vy)
            u2, w2 = vx + 0.5 * h * a1[0], vy + 0.5 * h * a1[1]
            a3 = aceleracion(x + 0.5 * h * u2, y + 0.5 * h * w2)
            u3, w3 = vx + 0.5 * h * a2[0], vy + 0.5 * h * a2[1]
            a4 = aceleracion(x + h * u3, y + h * w3)
            u4, w4 = vx + h * a3[0], vy + h * a3[1]
            x += h / 6 * (vx + 2 * u2 + 2 * u3 + u4); y += h / 6 * (vy + 2 * w2 + 2 * w3 + w4)
            vx += h / 6 * (a1[0] + 2 * a2[0] + 2 * a3[0] + a4[0]); vy += h / 6 * (a1[1] + 2 * a2[1] + 2 * a3[1] + a4[1])
            ax, ay = aceleracion(x, y)
        rel = (energia(x, y, vx, vy) - E0) / abs(E0)
        if rel >= 1:
            return {"escapa en la vuelta": i / pasos_vuelta}, peor
        peor = max(peor, abs(rel))
        if i % pasos_vuelta == 0 and (i // pasos_vuelta) in (1, 10, 100, 1000):
            registro[i // pasos_vuelta] = rel
    return registro, peor

for metodo in ("Euler", "RK4", "leapfrog"):
    reg, peor = kepler_fijo(metodo, 0.5, 100, 1000)
    print(f"{metodo:9s}", "  ".join(f"vuelta {k}: {v:+.2e}" if isinstance(k, int) else f"{k} {v:.1f}" for k, v in reg.items()),
          f"  máximo |ΔE/E0| = {peor:.2e}")

# a igual coste: leapfrog con 400 pasos por vuelta hace tantas evaluaciones como RK4 con 100
reg, peor = kepler_fijo("leapfrog", 0.5, 400, 1000)
print("leapfrog con 400 pasos por vuelta: máximo |ΔE/E0| en 1000 vueltas =", f"{peor:.2e}")

Theory predicts the result. Euler gains energy until escape in a few revolutions. RK4 loses energy at the same rate per revolution: signed error changes from −3.0⋅10−5-3.0\cdot 10^{-5} at revolution 1 to about −3⋅10−4-3\cdot 10^{-4} at 10, −3⋅10−3-3\cdot 10^{-3} at 100 and −3⋅10−2-3\cdot 10^{-2} at 1000, proportional to revolution count. Leapfrog has greater error at revolution 1 than RK4 (1.5⋅10−31.5\cdot 10^{-3}), but stays in a fixed band: 1.1⋅10−21.1\cdot 10^{-2} at the end of revolutions 10, 100 and 1000, also its integration-wide maximum. Thus RK4 wins initially and loses near revolution 360, when drift of about 3⋅10−53\cdot 10^{-5} per revolution reaches that band. At equal cost, with 400 steps per revolution, leapfrog maximum falls 16-fold to 6.7⋅10−46.7\cdot 10^{-4}, as expected for order 2 (42=164^2 = 16), and RK4 error overtakes it near revolution 22.

Double pendulum: a nonseparable Hamiltonian

With masses, lengths and gravity equal to 1 and angles measured from vertical, the double pendulum has

H(q,p)=p12+2p22−2p1p2cos⁡(q1−q2)2 (1+sin⁡2(q1−q2))−2cos⁡q1−cos⁡q2.H(\vb{q}, \vb{p}) = \frac{p_1^2 + 2p_2^2 - 2p_1p_2\cos(q_1 - q_2)}{2\,\big(1 + \sin^2(q_1 - q_2)\big)} - 2\cos q_1 - \cos q_2.

Kinetic energy depends on positions: HH is not separable and explicit leapfrog does not apply. Use implicit midpoint, yn+1=yn+hf(12(yn+yn+1))\vb{y}_{n+1} = \vb{y}_n + h f\big(\tfrac12(\vb{y}_n + \vb{y}_{n+1})\big), symplectic and solved by fixed-point iteration, comparing it with RK4 over 10510^5 steps of h=0.02h = 0.02 (time 2000) from a highly energetic chaotic position.

[ ]Double pendulum with RK4: 10⁵ stepsBrowser
import math

def H(q1, q2, p1, p2):
    d = q1 - q2
    return (p1 * p1 + 2 * p2 * p2 - 2 * p1 * p2 * math.cos(d)) / (2 * (1 + math.sin(d) ** 2)) - 2 * math.cos(q1) - math.cos(q2)

def campo(q1, q2, p1, p2):
    s, c = math.sin(q1 - q2), math.cos(q1 - q2)
    den = 1 + s * s
    A = p1 * p2 * s / den
    B = (p1 * p1 + 2 * p2 * p2 - 2 * p1 * p2 * c) * s * c / (den * den)
    return (p1 - p2 * c) / den, (2 * p2 - p1 * c) / den, -2 * math.sin(q1) - A + B, -math.sin(q2) + A - B

def pendulo_rk4(y, h, n, cada):
    q1, q2, p1, p2 = y
    E0, out = H(*y), []
    for i in range(1, n + 1):
        k1 = campo(q1, q2, p1, p2)
        k2 = campo(q1 + .5 * h * k1[0], q2 + .5 * h * k1[1], p1 + .5 * h * k1[2], p2 + .5 * h * k1[3])
        k3 = campo(q1 + .5 * h * k2[0], q2 + .5 * h * k2[1], p1 + .5 * h * k2[2], p2 + .5 * h * k2[3])
        k4 = campo(q1 + h * k3[0], q2 + h * k3[1], p1 + h * k3[2], p2 + h * k3[3])
        q1 += h / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0]); q2 += h / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])
        p1 += h / 6 * (k1[2] + 2 * k2[2] + 2 * k3[2] + k4[2]); p2 += h / 6 * (k1[3] + 2 * k2[3] + 2 * k3[3] + k4[3])
        if i % cada == 0:
            out.append((H(q1, q2, p1, p2) - E0) / abs(E0))
    return out

y0 = (2.0, 2.0, 0.0, 0.0)         # los dos brazos a 115° de la vertical, en reposo
print(f"energía inicial H = {H(*y0):.6f}")
rk = pendulo_rk4(y0, 0.02, 100_000, 20_000)
print("RK4, error relativo de energía cada 2·10⁴ pasos:", "  ".join(f"{v:+.2e}" for v in rk))
[ ]Double pendulum with implicit midpoint: 10⁵ stepsBrowser
def pendulo_punto_medio(y, h, n, cada, tol=1e-12):
    q1, q2, p1, p2 = y
    E0, out, picos, iters, peor = H(*y), [], [], 0, 0.0
    k = campo(q1, q2, p1, p2)
    for i in range(1, n + 1):
        for _ in range(50):     # punto fijo para k = f(y_n + h k / 2)
            kn = campo(q1 + .5 * h * k[0], q2 + .5 * h * k[1], p1 + .5 * h * k[2], p2 + .5 * h * k[3])
            dif = abs(kn[0] - k[0]) + abs(kn[1] - k[1]) + abs(kn[2] - k[2]) + abs(kn[3] - k[3])
            k = kn; iters += 1
            if h * dif < tol:
                break
        q1 += h * k[0]; q2 += h * k[1]; p1 += h * k[2]; p2 += h * k[3]
        rel = (H(q1, q2, p1, p2) - E0) / abs(E0)
        peor = max(peor, abs(rel))
        if i % cada == 0:
            out.append(rel); picos.append(peor); peor = 0.0
    return out, picos, iters / n

pm, picos, it_medio = pendulo_punto_medio(y0, 0.02, 100_000, 20_000)
print("punto medio, error relativo de energía cada 2·10⁴ pasos:", "  ".join(f"{v:+.2e}" for v in pm))
print("máximo de |ΔE/E0| en cada bloque de 2·10⁴ pasos:        ", "  ".join(f"{v:.2e}" for v in picos))
print(f"evaluaciones de f por paso (iteraciones de punto fijo): {it_medio:.1f}")

Notice series shapes, not only sizes. RK4 loses energy steadily, about 1.9⋅10−41.9\cdot 10^{-4} per 2⋅1042\cdot 10^4 steps, reaching −9.7⋅10−4-9.7\cdot 10^{-4} at the end. Implicit midpoint, order 2, makes larger error at each instant (maximum around 5.4⋅10−35.4\cdot 10^{-3}), but that maximum is the same in five blocks: 5.375.37, 5.395.39, 5.385.38, 5.445.44 and 5.10⋅10−35.10\cdot 10^{-3}. There is no drift even though motion is chaotic: backward error analysis does not require integrability, only a symplectic method and analytic HH. At this step and horizon RK4 remains more accurate; its linear drift would reach midpoint’s band near 6⋅1056\cdot 10^5 steps and worsen thereafter. Symplecticity costs twice here: order 2 and iteration each step, 6.6 evaluations of ff per step versus RK4’s 4. With a separable Hamiltonian the balance is much better, as the next problem shows.

Three bodies in a figure eight

Moore (1993) numerically found a periodic orbit in which three equal masses chase one another along a figure-eight curve, and Chenciner and Montgomery (2000) proved existence. With G=m=1G = m = 1, their initial conditions give period 6.32596.3259. This is demanding: distances change greatly along the orbit. Compare leapfrog with 10510^5 steps of h=T/250h = T/250 (400 periods) and RK4 with the same force-evaluation count, namely 2.5⋅1042.5\cdot 10^4 steps of 4h4h.

[ ]The figure-eight orbit: leapfrog versus RK4 at equal costBrowser
import math

def aceleraciones(x):
    a = [0.0] * 6
    for i in range(3):
        for j in range(i + 1, 3):
            dx, dy = x[2 * j] - x[2 * i], x[2 * j + 1] - x[2 * i + 1]
            r2 = dx * dx + dy * dy
            k = 1 / (r2 * math.sqrt(r2))
            a[2 * i] += dx * k; a[2 * i + 1] += dy * k
            a[2 * j] -= dx * k; a[2 * j + 1] -= dy * k
    return a

def energia3(x, v):
    U = -sum(1 / math.hypot(x[2 * j] - x[2 * i], x[2 * j + 1] - x[2 * i + 1]) for i in range(3) for j in range(i + 1, 3))
    return 0.5 * sum(vi * vi for vi in v) + U

x0 = [0.97000436, -0.24308753, -0.97000436, 0.24308753, 0.0, 0.0]
v3 = (-0.93240737, -0.86473146)
v0 = [-v3[0] / 2, -v3[1] / 2, -v3[0] / 2, -v3[1] / 2, v3[0], v3[1]]
T = 6.32591398
E0 = energia3(x0, v0)

def leapfrog3(h, n, cada):
    x, v, a, out = x0[:], v0[:], aceleraciones(x0), []
    for k in range(1, n + 1):
        for i in range(6):
            v[i] += 0.5 * h * a[i]; x[i] += h * v[i]
        a = aceleraciones(x)
        for i in range(6):
            v[i] += 0.5 * h * a[i]
        if k % cada == 0:
            out.append((energia3(x, v) - E0) / abs(E0))
    return out

def rk4_3(h, n, cada):
    x, v, out = x0[:], v0[:], []
    for k in range(1, n + 1):
        a1 = aceleraciones(x)
        x2 = [x[i] + .5 * h * v[i] for i in range(6)]; u2 = [v[i] + .5 * h * a1[i] for i in range(6)]; a2 = aceleraciones(x2)
        x3 = [x[i] + .5 * h * u2[i] for i in range(6)]; u3 = [v[i] + .5 * h * a2[i] for i in range(6)]; a3 = aceleraciones(x3)
        x4 = [x[i] + h * u3[i] for i in range(6)]; u4 = [v[i] + h * a3[i] for i in range(6)]; a4 = aceleraciones(x4)
        x = [x[i] + h / 6 * (v[i] + 2 * u2[i] + 2 * u3[i] + u4[i]) for i in range(6)]
        v = [v[i] + h / 6 * (a1[i] + 2 * a2[i] + 2 * a3[i] + a4[i]) for i in range(6)]
        if k % cada == 0:
            out.append((energia3(x, v) - E0) / abs(E0))
    return out

h = T / 250
lf = leapfrog3(h, 100_000, 20_000)
rk = rk4_3(4 * h, 25_000, 5_000)
print(f"energía inicial {E0:.6f}")
print("leapfrog (10⁵ pasos de T/250), error de energía cada 80 periodos:", "  ".join(f"{e:+.1e}" for e in lf))
print("RK4 (2.5·10⁴ pasos de T/62.5), mismo coste:                    ", "  ".join(f"{e:+.1e}" for e in rk))

At equal cost the difference spans orders of magnitude: leapfrog keeps energy error between 4⋅10−54\cdot 10^{-5} and 4⋅10−44\cdot 10^{-4} for 400 periods without trend, while RK4 with a four-times-larger step loses energy increasingly fast: −2.5⋅10−2-2.5\cdot 10^{-2} at 80 periods and −0.50-0.50 at 400: with energy off by 50%, what is simulated is no longer the original figure-eight orbit. Here spending evaluations on smaller steps of an order-2 symplectic method is far better than on stages of an order-4 method.

Lorenz: 10−1210^{-12} and the Lyapunov exponent

Finally, the opening chaos in numbers. Integrate with RK4 and h=0.002h = 0.002 two trajectories 10−1210^{-12} apart in xx, another with h=0.001h = 0.001 from the same point, and estimate λ1\lambda_1 with Benettin’s method: follow a neighboring trajectory at distance 10−810^{-8}, measure its separation each time unit and renormalize.

[ ]Lorenz: trajectory separation and Lyapunov exponentBrowser
import math
import numpy as np

def lorenz(x, y, z):
    return 10 * (y - x), x * (28 - z) - y, x * y - 8 / 3 * z

def paso(u, h):
    x, y, z = u
    a = lorenz(x, y, z)
    b = lorenz(x + .5 * h * a[0], y + .5 * h * a[1], z + .5 * h * a[2])
    c = lorenz(x + .5 * h * b[0], y + .5 * h * b[1], z + .5 * h * b[2])
    d = lorenz(x + h * c[0], y + h * c[1], z + h * c[2])
    return (x + h / 6 * (a[0] + 2 * b[0] + 2 * c[0] + d[0]), y + h / 6 * (a[1] + 2 * b[1] + 2 * c[1] + d[1]),
            z + h / 6 * (a[2] + 2 * b[2] + 2 * c[2] + d[2]))

def trayectoria(u, h, T, cada_t=0.02):
    n, cada = int(round(T / h)), int(round(cada_t / h))
    out = [u]
    for k in range(1, n + 1):
        u = paso(u, h)
        if k % cada == 0:
            out.append(u)
    return np.array(out)

A = trayectoria((1.0, 1.0, 1.0), 0.002, 50)
B = trayectoria((1.0 + 1e-12, 1.0, 1.0), 0.002, 50)
C = trayectoria((1.0, 1.0, 1.0), 0.001, 50)
t = np.arange(len(A)) * 0.02
dAB = np.linalg.norm(A - B, axis=1)
dAC = np.linalg.norm(A - C, axis=1)
m = (t > 2) & (dAB < 1e-2)
print(f"δ0 = 1e-12: la distancia llega a 1 en t = {t[np.argmax(dAB >= 1)]:.1f};  pendiente de log(distancia) en t > 2: {np.polyfit(t[m], np.log(dAB[m]), 1)[0]:.3f}")
print(f"h frente a h/2: distancia en t = 1: {dAC[50]:.1e}, en t = 5: {dAC[250]:.1e}; llega a 1 en t = {t[np.argmax(dAC >= 1)]:.1f}")
print(f"media de z en [5, 50]: {A[t > 5, 2].mean():.2f} (h = 0.002), {C[t > 5, 2].mean():.2f} (h = 0.001), {B[t > 5, 2].mean():.2f} (δ0 = 1e-12)")

# por qué la separación apenas crece al principio: la trayectoria gira alrededor de un punto fijo
cruces = t[1:][np.sign(A[1:, 0]) != np.sign(A[:-1, 0])]
print("primeros instantes en que x cambia de signo:", np.round(cruces[:3], 1))
s = math.sqrt(8 / 3 * 27)                       # puntos fijos C± = (±s, ±s, 27)
J = np.array([[-10, 10, 0], [1, -1, -s], [s, s, -8 / 3]])
print("autovalores del jacobiano en C+:", np.round(np.linalg.eigvals(J), 3))

# Benettin: λ1 como tasa media de separación, renormalizando cada unidad de tiempo
h, u = 0.01, (1.0, 1.0, 1.0)
for _ in range(1000):
    u = paso(u, h)                            # descarta el transitorio
d0, suma = 1e-8, 0.0
v = (u[0] + d0, u[1], u[2])
for k in range(1, 50_001):
    u, v = paso(u, h), paso(v, h)
    if k % 100 == 0:
        d = math.dist(u, v)
        suma += math.log(d / d0)
        v = tuple(u[i] + (v[i] - u[i]) * d0 / d for i in range(3))
print(f"λ1 estimado con t = 500: {suma / 500:.3f}   (Sprott, 2003: 0.9056)")

Estimated exponent 0.905 matches reference. Separation slope between t=2t = 2 and reaching 10−210^{-2} is lower, about 0.71: local separation rate fluctuates greatly across the attractor and one segment of a few dozen time units is not a reliable mean. The last two output lines show the opening extreme: xx does not change sign between t=0.5t = 0.5 and t=13.6t = 13.6 while trajectory circles C−C_- (with x<0x < 0), and Jacobian at fixed points (same spectrum at C+C_+ and C−C_- by symmetry (x,y)↦(−x,−y)(x, y) \mapsto (-x, -y)) has eigenvalues −13.85-13.85 and 0.094±10.19i0.094 \pm 10.19i. With δ0=10−12\delta_0 = 10^{-12}, trajectories fully separate near t=41t = 41. Simulations with hh and h/2h/2, starting at the same point, differ by 7⋅10−87\cdot 10^{-8} at t=1t = 1 and 2⋅10−72\cdot 10^{-7} at t=5t = 5, and fully separate near t=25t = 25: neither is the exact trajectory beyond then. Even so mean zz on [5,50][5, 50] agrees across all three within 1% (23.89, 23.83 and 24.07), and that difference is statistical fluctuation of an average over only 45 time units, not integrator bias. That is what a “correct” chaotic simulation means.

MuJoCo integrators

MuJoCo, the physics simulator used in robotics and reinforcement projects (MuJoCo), integrates articulated-body dynamics M(q) v′=τ(q,v)+fuerzas de restriccioˊn\mat{M}(\vb{q})\,\vb{v}' = \vb{\tau}(\vb{q}, \vb{v}) + \text{fuerzas de restricción} at fixed step and offers several integrators. According to its documentation (Computation, “Numerical integration”):

  • Euler (default, documentation now recommends only for compatibility with old models) is not explicit Euler, which MuJoCo does not offer because strictly worse: it is semi-implicit Euler, updating velocity first then position using the new velocity. For conservative forces it is this lesson’s symplectic Euler. It also treats joint damping implicitly (eulerdamp option, enabled by default).
  • implicit is implicit in velocity: linearizes all velocity-dependent forces (damping, actuators, Coriolis and centrifugal), except constraint forces, and solves a system with LU.
  • implicitfast does the same without Coriolis and centrifugal derivatives, leaving a symmetric matrix factored by Cholesky. Documentation recommends it for stability-cost balance.
  • RK4 is classical four-stage Runge–Kutta, recommended by documentation for systems conserving or nearly conserving energy.

Recent versions add a discrete integrator, which documentation describes as new and in development; here we keep the four classics.

The lab uses a pendulum: a 1 kg ball at the end of a 0.5 m hinged rod and a wall it can hit. It measures energy without friction, stability with strong damping and contact. It runs on your machine (pip install mujoco).

[ ]MuJoCo: Euler, implicit, implicitfast and RK4 on a pendulumLocal GPU
import time
import numpy as np
import mujoco

XML = """
<mujoco model="pendulo">
  <option timestep="{dt}" integrator="{integ}">
    <flag energy="enable" contact="{contacto}" eulerdamp="{eulerdamp}"/>
  </option>
  <worldbody>
    <body name="brazo" pos="0 0 1">
      <joint name="bisagra" type="hinge" axis="0 1 0" damping="{b}"/>
      <geom type="capsule" fromto="0 0 0 0 0 -0.5" size="0.02" mass="0.1"/>
      <geom name="bola" type="sphere" pos="0 0 -0.5" size="0.05" mass="1"/>
    </body>
    <geom name="pared" type="box" pos="0.3 0 0.5" size="0.02 0.2 0.3"/>
  </worldbody>
</mujoco>
"""

def modelo(integ, dt, b=0.0, contacto="disable", eulerdamp="enable"):
    m = mujoco.MjModel.from_xml_string(XML.format(dt=dt, integ=integ, b=b, contacto=contacto, eulerdamp=eulerdamp))
    return m, mujoco.MjData(m)

def simula(integ, dt, T, q0, **kw):
    m, d = modelo(integ, dt, **kw)
    d.qpos[0] = q0
    mujoco.mj_forward(m, d)
    E0, E, pen = d.energy.sum(), [], 0.0
    for i in range(int(round(T / dt))):
        mujoco.mj_step(m, d)
        if not np.isfinite(d.qpos[0]) or abs(d.qvel[0]) > 1e4:
            return None, i * dt, None
        E.append(d.energy.sum() - E0)
        for c in d.contact[: d.ncon]:
            pen = max(pen, -c.dist)
    return np.array(E), d.qpos[0], pen

def coste_por_paso(integ, dt=0.002, n=20_000, repeticiones=7):
    """Tiempo por paso con el bucle dentro de MuJoCo (nstep), el mejor de varias repeticiones."""
    m, d = modelo(integ, dt)
    mejor = float("inf")
    for _ in range(repeticiones):
        mujoco.mj_resetData(m, d)
        d.qpos[0] = 1.5
        t0 = time.perf_counter()
        mujoco.mj_step(m, d, nstep=n)
        mejor = min(mejor, time.perf_counter() - t0)
    return mejor / n

m, _ = modelo("Euler", 0.002)
I = m.dof_M0[0]
print(f"inercia de la bisagra I = {I:.4f} kg·m²;  escala de energía m g l = {9.81 * 0.5:.2f} J\n")

print("1) Sin rozamiento ni contacto, 100 s desde 1.5 rad: error de energía en julios")
for integ in ["Euler", "implicit", "implicitfast", "RK4"]:
    for dt in [0.001, 0.01, 0.05]:
        E, q, _ = simula(integ, dt, 100.0, 1.5)
        n = len(E)
        print(f"   {integ:12s} dt = {dt:5.3f}: máx |ΔE| primer 10 % = {np.abs(E[: n // 10]).max():.2e}   "
              f"último 10 % = {np.abs(E[-n // 10:]).max():.2e}   ΔE final = {E[-1]:+.2e}")
coste = {integ: coste_por_paso(integ) for integ in ["Euler", "implicit", "implicitfast", "RK4"]}
print("   coste por paso relativo a Euler:", "  ".join(f"{k} {v / coste['Euler']:.2f}" for k, v in coste.items()))

b = 50.0
print(f"\n2) Amortiguamiento b = {b} N·m·s/rad: tasa b/I = {b / I:.1f} 1/s")
print(f"   predicción de la teoría lineal: Euler explícito estable si dt < 2 I/b = {2 * I / b:.4f} s;  RK4 si dt < 2.785 I/b = {2.785 * I / b:.4f} s")
for dt in [0.008, 0.010, 0.011, 0.012, 0.014, 0.015, 0.02, 0.05]:
    fila = []
    for integ, ed in [("Euler", "disable"), ("RK4", "enable"), ("Euler", "enable"), ("implicitfast", "enable")]:
        E, q, _ = simula(integ, dt, 5.0, -1.5, b=b, eulerdamp=ed)
        nombre = integ + ("" if ed == "enable" or integ != "Euler" else " sin eulerdamp")
        fila.append(f"{nombre}: {'DIVERGE' if E is None else f'q(5) = {q:.4f}'}")
    print(f"   dt = {dt:5.3f}   " + "   ".join(fila))

print("\n3) Contacto con la pared (b = 0.05), 5 s desde -1.5 rad: ángulo final y penetración máxima")
for dt in [0.001, 0.002, 0.005, 0.01, 0.02, 0.04]:
    fila = []
    for integ in ["Euler", "implicitfast", "RK4"]:
        E, q, pen = simula(integ, dt, 5.0, -1.5, b=0.05, contacto="enable")
        fila.append(f"{integ}: q = {q:.4f}, penetración {1000 * pen:.1f} mm")
    print(f"   dt = {dt:5.3f}   " + "   ".join(fila))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Read output using lesson theory:

  1. Without friction, Euler, implicit and implicitfast give exactly the same numbers. No velocity-dependent forces exist (one hinge has no Coriolis terms), so all reduce to semi-implicit, i.e. symplectic, Euler. Energy error is proportional to Δt\Delta t (about 9.5⋅10−39.5\cdot 10^{-3}, 9.6⋅10−29.6\cdot 10^{-2} and 0.510.51 J at Δt=0.001\Delta t = 0.001, 0.010.01 and 0.050.05 s on a 4.94.9 J scale) and does not grow: maximum in the final 10% of simulation equals the first. RK4 is vastly more accurate at equal step (2⋅10−82\cdot 10^{-8} J with Δt=0.001\Delta t = 0.001), but error does grow with time, as in Kepler: at Δt=0.05\Delta t = 0.05 from 5.4⋅10−35.4\cdot 10^{-3} to 1.4⋅10−21.4\cdot 10^{-2} J. Per step it costs about four times Euler (3.4 to 5 in our runs on a shared machine), evaluating dynamics four times; implicit and implicitfast cost the same order as Euler (0.9 to 1.6 times) in this one-degree-of-freedom model. Time with the loop inside MuJoCo (nstep): timing a Python loop calling mj_step step by step mainly measures interpreter overhead.
  2. With strong damping, velocity mode has λ≈−b/I≈−193 s−1\lambda \approx -b/I \approx -193\ \text{s}^{-1}. Absolute stability predicts Euler with explicit damping (eulerdamp disabled) diverges for Δt>2I/b≈0.0104\Delta t > 2I/b \approx 0.0104 s, and RK4 for Δt>2.785 I/b≈0.0145\Delta t > 2.785\,I/b \approx 0.0145 s. Exactly so: Euler without eulerdamp is stable at Δt=0.010\Delta t = 0.010 and diverges at 0.0110.011, and RK4 is stable at 0.0140.014 and diverges at 0.0150.015. With eulerdamp (default) or implicitfast, damping is implicit and simulation stable at any step.
  3. With contact, final angle agrees across the three tested integrators at each step: constraint forces are computed by the contact solver and no integrator linearizes them. Euler and implicitfast even give the same penetration; RK4 differs somewhat because it solves contact at every stage. Maximum penetration, measured only at step times, is about 10 mm with Δt≤0.002\Delta t \le 0.002 s and varies irregularly at larger steps (3.9 to 23.8 mm), because sampling is coarser and a safeguard intervenes: MuJoCo requires the contact virtual spring time constant (solref[0], default 0.02 s) to be at least 2Δt2\Delta t, raising it automatically unless refsafe is disabled. With Δt=0.02\Delta t = 0.02 s it becomes 0.04 s: a softer contact, stable for that step, penetrating more (23.8 mm). This is absolute stability logic applied to contact: a mode with timescale shorter than the step would destabilize simulation, so it is softened until the step resolves it.

Practical moral: in robotics, MuJoCo step is limited not by trajectory precision but stability of fast modes (damping, high-gain actuators, contacts). Velocity-implicit integrators exist for that, and the table above shows numerically why documentation recommends them. See simulation timestep stability.

With libraries: solve_ivp in depth

scipy.integrate.solve_ivp(fun, t_span, y0, method="RK45", t_eval=None, dense_output=False, events=None, ...) is the modern interface. Options worth knowing:

OptionWhat it doesBeware
methodRK45, RK23, DOP853 (explicit), Radau, BDF (implicit), LSODA (switches automatically)default RK45 struggles on stiff problems
rtol, atollocal-error tolerances; atol accepts a vector, one per componentdefaults rtol = 1e-3 and atol = 1e-6, only about three digits
jac, jac_sparsityanalytic Jacobian or sparsity pattern (implicit)without jac, finite differences approximate it, more expensive and less accurate
t_eval, dense_outputwhere solution is wanted; obtained from interpolantdo not change accuracy or steps
eventsfunctions g(t,y)g(t, \vb{y}) whose zeros interpolant locates; may stop integrationan event crossing and recrossing within one step is missed
max_steplimits stepneeded if ff has details shorter than the integrator’s chosen step
first_stepinitial stepautomatic heuristic is normally better

Result contains t, y, nfev, njev, nlu, status and message: always inspect status and counters, the first stiffness symptom. PyTorch and JAX have differentiable integrators (torchdiffeq, diffrax) following the same embedded-pair and step-control design, used in neural ODEs and diffusion samplers. The same count matters: ff evaluations, network passes.

Common mistakes

Exercises

NumericEuler's maximum step
What is the largest step hh for which explicit Euler is stable on y′=−1000 yy' = -1000\,y?
NumericDoes RK4 pay off on a stiff problem?
On y′=−1000 yy' = -1000\,y, each method uses its largest stable step. How many evaluations of ff per unit time does RK4 need? (Its stability region crosses the real axis at −2.785-2.785.)
NumericFour more digits
A Dormand–Prince 5(4) integrator solves a nonstiff problem in 400 steps at rtol = 1e-6. Assume controller keeps estimated local error equal to tolerance and solution is smooth. Approximately how many steps at rtol = 1e-10?
NumericWhat quadruple precision buys
In the Lorenz system with λ1=0.9056\lambda_1 = 0.9056, a double-precision simulation starts with relative error 10−1610^{-16}. In quadruple precision with initial error 10−3410^{-34} and an integrator as accurate as needed, how many more time units could you predict the trajectory before error reaches the same size?
QuizLeapfrog and RK4 energy
In the orbit duel, leapfrog (order 2) keeps energy bounded over hundreds of orbits while RK4's (order 4) drifts continuously. What is the correct explanation?
QuizEver smaller steps
You integrate a kinetic model with RK45. The solution of interest is smooth and barely changes, but the integrator takes ever smaller steps, rejects many, and changing rtol = 1e-6 to rtol = 1e-3 barely reduces evaluation count. What does this indicate and what do you do?
QuizStability regions
Which statements are true?

More than one answer may be correct.

QuizOne tolerance for everything
You solve Robertson with solve_ivp(..., method='BDF', rtol=1e-6, atol=1e-6). Component y2y_2 is at most about 3.7⋅10−53.7\cdot 10^{-5}. What accuracy can you expect in y2y_2?
ProofEuler's global error is O(h)
Prove: If ff is continuous and Lipschitz in y\vb{y} with constant LL and the solution is C2C^2 with ∥y′′∥≤M2\norm{\vb{y}''} \le M_2, explicit Euler with y0=y(t0)\vb{y}_0 = \vb{y}(t_0) satisfies ∥y(tn)−yn∥≤hM22L(eL(tn−t0)−1)\norm{\vb{y}(t_n) - \vb{y}_n} \le \frac{hM_2}{2L}\big(e^{L(t_n - t_0)} - 1\big).
0
Let en=y(tn)−yn\vb{e}_n = \vb{y}(t_n) - \vb{y}_n be global error and τn+1=y(tn+1)−y(tn)−hf(tn,y(tn))\vb{\tau}_{n+1} = \vb{y}(t_{n+1}) - \vb{y}(t_n) - hf(t_n, \vb{y}(t_n)) local error.

Step 1 of 4. What recurrence does en\vb{e}_n satisfy?

CodeAdaptive Dormand–Prince
Implement dopri5(f, t_span, y0, rtol=1e-6, atol=1e-9), an adaptive integrator with Dormand–Prince 5(4): advance with the order-5 solution, estimate error with E = b − b̂, use the last stage as the next step's first (FSAL), use the RMS norm scaled by atol + rtol·max(|y|, |y_nuevo|) (atol may be scalar or array), and controller h·min(10, max(0.2, 0.9·err^(−1/5))), preventing the factor exceeding 1 immediately after rejection. The last step must end exactly at t_span[1]. Return (t, y, stats): t of shape (n,) with accepted times (including initial), y of shape (d, n) and stats a dictionary with nfev, naccept and nreject. Choose the initial step with the lab heuristic or another reasonable one.
import numpy as np

C = np.array([0, 1/5, 3/10, 4/5, 8/9, 1, 1])
A = [[], [1/5], [3/40, 9/40], [44/45, -56/15, 32/9],
   [19372/6561, -25360/2187, 64448/6561, -212/729],
   [9017/3168, -355/33, 46732/5247, 49/176, -5103/18656],
   [35/384, 0, 500/1113, 125/192, -2187/6784, 11/84]]
B = np.array([35/384, 0, 500/1113, 125/192, -2187/6784, 11/84, 0])            # orden 5
E = np.array([71/57600, 0, -71/16695, 71/1920, -17253/339200, 22/525, -1/40])  # b - b_gorro

def dopri5(f, t_span, y0, rtol=1e-6, atol=1e-9):
  t, T = t_span
  y = np.array(y0, dtype=float)
  # tu código: paso inicial, bucle de pasos con las 7 etapas, error, aceptación o rechazo y nuevo h
  ts, ys = [t], [y]
  stats = {"nfev": 0, "naccept": 0, "nreject": 0}
  return np.array(ts), np.array(ys).T, stats
Shift+Enter to run

Summary

Key idea
Integrating an ODE means choosing which system property cannot be lost: accuracy (order and adaptive step), fast-mode stability (implicit methods on stiff problems), or geometry (symplectic integrators for Hamiltonian systems). No method provides all at once.
  • Explicit Euler has local error O(h2)\bigO(h^2) and global O(h)\bigO(h): discrete Grönwall controls propagation of local errors with factor eL(T−t0)e^{L(T - t_0)} reflecting problem conditioning. Order-pp Runge–Kutta satisfies Butcher conditions through pp; RK4 is explicit methods’ sweet spot.
  • An embedded pair like Dormand–Prince 5(4) estimates local error almost free; a controller with exponent 1/(p^+1)1/(\hat p + 1) adjusts step to local timescale, like h∝r3/2h \propto r^{3/2} in an orbit. Tolerances control local error; t_eval controls nothing.
  • Test equation y′=λyy' = \lambda y gives yn+1=R(hλ) yny_{n+1} = R(h\lambda)\,y_n. Explicit methods have bounded stability regions; A-stable regions contain the left half-plane, and L-stable methods also damp stiff modes.
  • A problem is stiff when stability rather than accuracy dictates an explicit method’s step. Implicit methods (BDF, Radau, LSODA) pay for a linear system per step in exchange for large steps.
  • Symplectic integrators like leapfrog preserve a modified Hamiltonian and keep energy bounded for exponentially long times; higher-order RK4 drifts. In chaotic systems only statistics, not trajectories, are reproducible long-term.

These tools recur throughout the syllabus: the method of lines converts PDEs to large stiff ODE systems; diffusion and flow-matching models sample by integrating ODEs with low-order Runge–Kutta; Hamiltonian Monte Carlo relies on leapfrog; robotics simulators integrate dynamics with the measured MuJoCo schemes; and stochastic differential equations extend Euler to Euler–Maruyama.