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 to a simulation you can trust
Almost everything simulated in science and engineering is fundamentally an initial value problem: you know system state at time and a law 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 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 steps to follow it to completion near ; 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 is a neural network. Each 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
with and continuous and Lipschitz in with constant : . The Picard–Lindelöf theorem guarantees a unique solution throughout . Every higher-order equation reduces to this form by adding derivatives as variables: pendulum is system , .
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 and , Grönwall’s inequality gives
The bound can be pessimistic. Finer information lies in the variational equation: matrix satisfies with and (ODE sensitivity). Small perturbation becomes , so is the absolute condition number of map .
Two extremes frame the lesson:
- Contractive problems. In , whose solution with is , Lipschitz constant is , but any two solutions approach as : the problem is superbly conditioned. Grönwall’s bound with is useless. Contraction is measured by the logarithmic norm : if along the path, then , and here . This contrast (well-conditioned problem, huge ) is exactly stiffness, studied below.
- Chaotic problems. In the Lorenz system (1963), , , , perturbations grow on average as , with largest Lyapunov exponent (Sprott’s 2003 value; see Lyapunov exponents). Condition number grows exponentially with horizon. With initial relative error , that of floating-point representation itself, the computed trajectory stops resembling the exact one near , and no integrator can prevent it.
The figure teaches two things to separate. After an initial segment, distance grows as a straight line on logarithmic scale, with slope near , until saturating at attractor size: each factor 10 of initial accuracy buys only time units of prediction. The first segment, where distance hardly grows for about 14 time units, also has an explanation: from the trajectory spirals around one of two fixed points , whose linearization has unstable eigenvalues with real part only , and does not change lobe until . Thus the reference line starting at at leads the measured curve: 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 into steps of size , with , and let approximate . The simplest idea is to follow the tangent.
To quantify loss distinguish two errors.
For explicit Euler, Taylor expansion with remainder gives, if and ,
It is order 1: local error per step. Reaching takes steps, so global error 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, , summing the geometric series. Since , .
∎The proof directly applies the lemma and you will reconstruct it in the final guided exercise. Three readings:
- Global order is local order minus one. Generally, a one-step order- method whose increment is Lipschitz has global error by the same argument. Hence a method “is order ” referring to global error.
- The 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.
- It says nothing about rounding. steps also accumulate about rounding errors of size ; total error behaves like , and reducing 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 , with opposite sign), and costs much more per step: solve with Newton’s method for systems,
starting from or an explicit prediction. Each iteration solves a linear system with LU with partial pivoting. For small , is near identity: well conditioned with rapid convergence. In practice simplified Newton freezes , 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 and (all evaluated at ),
In the method, , because ‘s argument shifts in and in . Thus
Equating coefficients: order 1 if , and order 2 if additionally . With two stages there is a family of solutions, : midpoint (, ) and Heun’s method (, ).
Continuing the expansion multiplies terms: in appear and , independent and each giving a condition. Butcher (1963) discovered the conditions correspond bijectively to rooted trees: each tree with nodes gives a condition . For order 4 there are eight:
Condition count grows quickly: 1, 2, 4, 8, 17, 37, 85 and 200 for orders 1 to 8. Butcher barriers appear: an explicit -stage method has order , with equality only through ; 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:
with . For independent of it reduces to Simpson’s rule, suggesting its order.
Order is verified empirically as in nonlinear-equation order verification: if global error behaves as , log-log scale gives a line of slope , and local error slope . The first lab does this for Euler, implicit Euler, midpoint, Kutta’s 3/8 method and RK4. The same idea estimates error: integrating at and , Richardson extrapolation estimates fine-solution error as . It works but triples cost. Next section obtains an almost-free estimator.
Adaptive step size: Dormand–Prince
With fixed steps one must choose 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 . This is adaptive step-size control, with three pieces.
1. A local error estimator: embedded pairs. Design two Runge–Kutta methods sharing stages but with different weights: of order and of order . Their difference,
costs only additions and approximates the lower-order method’s local error, . 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 and is the next step’s first (FSAL, first same as last), so each accepted step costs 6 evaluations of , 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:
Accept the step if . 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 and atol = 1e-6, you tell the integrator none of its digits matter.
3. A controller. Since , the step giving exactly would be . Add a safety margin and limit change:
with and in scipy. If rejected, repeat at reduced ; if accepted, next step uses new . For DP5(4), exponent is .
Two more pieces complete a real integrator. Initial step is chosen by a Hairer, Nørsett and Wanner heuristic estimating derivatives with an extra evaluation. And dense output: each DP5(4) step has an order-4 interpolation polynomial evaluated at any intermediate without new 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.
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, versus distance to the Sun on log-log axes, with slope- line. Raise eccentricity to 0.98 and change tolerance: does slope change or only cloud height?Slope is not accidental. Near the Sun at distance , the comet moves at speed (units with ) and traverses distance of order in time : the orbit’s local timescale. Solution derivatives scale as powers of , so constant local error requires . 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 the longest step is about 900 times the shortest.
Absolute stability
Integrate with explicit Euler and . Exact solution decays brutally fast; numerical solution instead multiplies by 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 with . It is less particular than it seems. Near a solution, error follows linearization , and if is diagonalizable with , substitution decouples the system into scalar equations , with complex 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 and set . Stages satisfy , with the ones vector, hence , and
is the stability function. Numerical solution is and exact solution ; an order- method satisfies . For an explicit method, is nilpotent, , and is a polynomial of degree . If , order fixes the polynomial: , truncated Taylor expansion of . For implicit methods is rational:
What the figure shows, in formulas:
- Explicit Euler: is disk , center and radius 1. For real it requires . On the imaginary axis, : explicit Euler amplifies any undamped oscillation at any step.
- RK4: region is larger. It intersects the real axis at and contains imaginary segment ; within it, , so RK4 slightly damps oscillations. Dormand–Prince 5 reaches on the real axis.
- Implicit Euler: , exterior of the disk centered at with radius 1, containing : A-stable and, since , L-stable.
- Trapezoid: . Its region is exactly the half-plane: A-stable, preserving modulus on the imaginary axis. But as : not L-stable. With , : the stiff mode, which should immediately disappear, survives oscillating in sign for dozens of steps. Implicit Euler reduces it to in one.
Proof
is a polynomial, and consistency () makes its coefficient 1, so degree at least 1. A nonconstant polynomial satisfies as , hence outside a disk. In particular on the negative real axis there is such that for .
∎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 -stable (their region contains a sector of half-angle around the negative real axis), with , , and ; from order 7 they are unstable even with (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 , solution is smooth and well approximated with , but mode forces explicit Euler to use throughout integration, even after that mode has long disappeared. Each step error excites the stiff mode, and if , amplifies it. This is stiffness and implicit methods: the remedy is a method whose stability region contains those .
Symptoms in an adaptive explicit integrator are unmistakable:
- it takes many nearly constant steps of order even though solution barely changes;
- it regularly rejects steps: controller tries lengthening , 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 to , whereas BDF reaches with 1782.
With the problem is not stiff and explicit order 5 clearly beats implicit order 2: 392 evaluations versus 839. At they tie, and at explicit needs about 38 times more. From solution alternates slow segments, with crawling between and , and rapid jumps. On slow segments the Jacobian has an eigenvalue near , very negative, and DP5 step hugs the dashed curve: not tolerance but sets it. Implicit, by contrast, lengthens steps on slow segments and shortens only on jumps, where solution truly changes quickly. Explicit cost grows as (interval grows as and stable step shrinks as ): in the interactive, from to evaluations grow from about to , factor 9. Implicit across to only grows from about 3300 to 4400.
Implicit methods in practice
An implicit method solves a nonlinear system each step whose Jacobian is for a method-specific . For dimension and dense Jacobian, each factorization costs and each solve ; codes therefore reuse factorization while Newton converges and only recalculate when necessary. If 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 -step version fits a polynomial to and requires its derivative at to be . BDF1 is implicit Euler; fixed-step BDF2 is . They need one evaluation and one system per step; preferred for large systems. scipy
BDFhas 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 Padé approximant of . Solves a dimension- system per step (decomposed into one real and one complex dimension- system). Accurate choice for stiff problems: scipy
Radaufollows 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 and momenta is
or, with and , . Energy is conserved: . Its flow is also symplectic: its Jacobian satisfies (Poincaré). With one degree of freedom this equals : the flow preserves area in phase space. The commonest case is separable, with : masses in a potential.
Look at explicit Euler on harmonic oscillator , , energy . One step gives , , and direct calculation shows
Energy grows by a fixed factor each step: Euler’s outward spiral is exponential. The step Jacobian has determinant : explicit Euler expands phase-space area.
Why symplectic? Each composes two “shear” maps: , with Jacobian and symmetric , and , analogous with the block above. Block calculation gives
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 for all . With this requires ; for an explicit method , so every would vanish, contradicting . No explicit Runge–Kutta is symplectic, including RK4. Implicit midpoint (, , ) 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 . What it does is better than it looks: backward error analysis shows that for analytic , iterates of an order- symplectic method coincide, up to exponentially small error, with the exact solution of a modified Hamiltonian
and as is exactly conserved along its own flow, for exponentially long times, (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
as substitution of one step verifies. While , is positive definite, its level curves are closed ellipses and oscillates bounded, with relative amplitude , forever.
RK4 is not symplectic. On the oscillator, , slightly below 1: it loses a fixed energy fraction each step, tiny but systematic drift proportional to after steps. With local error order and secular drift, RK4 energy moves linearly away over time; leapfrog’s, with order- 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 and a nonsymplectic one like (Hairer, Lubich and Wanner, ch. X).
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 , , solution ; measure both global error at and local error of one step starting from exact solution at .
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 and global as ; RK4 as and . Now the earlier stiff problem, with , on :
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 explicit Euler succeeds; with , outside , numerical solution explodes (each step multiplies perturbation by , and over 952 steps that is factor ). Implicit Euler with a 50-times-larger step gives four correct digits (error ), and since the problem is linear in , 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 . Exact rational arithmetic also verifies eight order-4 conditions and computes coefficients of .
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, , 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.
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 : 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 versus , 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.
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 predicted by local dynamical time; the furthest, 1.51 with rtol = 1e-4 and , comes from a fit with only 17 steps. Longest-to-shortest ratio increases with eccentricity: 7 or 8 with , 115 to 129 with and 887 to 986 with . Law applied to 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:
with . Constants range from to and lives at scale , so needs its own atol. Explicit methods are run only to : beyond that they would be too slow for the browser.
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 , 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 at , not accuracy. With DP5 boundary at , stable step is about , roughly 660 steps per unit time: just the 678 observed. Implicit methods reach in hundreds of steps and BDF reaches in 624, because as reaction calms they lengthen step without stability limit. Explicit cannot: fast eigenvalue remains and approaches , so explicit Euler would need steps and about steps to reach . Notice Jacobian column: BDF evaluates between 2 and 22 times and reuses factorizations across many steps.
The figure’s Van der Pol oscillator, now with scipy methods:
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 , RK45 is cheapest (392 evaluations); with , LSODA and BDF already beat it. With , a quarter period alone needs 20 882 evaluations, more than any implicit method for two full periods, and with we do not try: the interactive, using the same Dormand–Prince pair and controller (and identical steps to RK45 for and ), estimates about 2.5 million steps. LSODA adapts to both regimes automatically.
Lab 2: energy, chaos and symplecticity
Kepler for steps
The duel orbit, eccentricity 0.5 and 100 steps per revolution, for 1000 revolutions: 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.
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 at revolution 1 to about at 10, at 100 and at 1000, proportional to revolution count. Leapfrog has greater error at revolution 1 than RK4 (), but stays in a fixed band: 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 per revolution reaches that band. At equal cost, with 400 steps per revolution, leapfrog maximum falls 16-fold to , as expected for order 2 (), 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
Kinetic energy depends on positions: is not separable and explicit leapfrog does not apply. Use implicit midpoint, , symplectic and solved by fixed-point iteration, comparing it with RK4 over steps of (time 2000) from a highly energetic chaotic position.
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))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 per steps, reaching at the end. Implicit midpoint, order 2, makes larger error at each instant (maximum around ), but that maximum is the same in five blocks: , , , and . There is no drift even though motion is chaotic: backward error analysis does not require integrability, only a symplectic method and analytic . At this step and horizon RK4 remains more accurate; its linear drift would reach midpoint’s band near steps and worsen thereafter. Symplecticity costs twice here: order 2 and iteration each step, 6.6 evaluations of 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 , their initial conditions give period . This is demanding: distances change greatly along the orbit. Compare leapfrog with steps of (400 periods) and RK4 with the same force-evaluation count, namely steps of .
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 and for 400 periods without trend, while RK4 with a four-times-larger step loses energy increasingly fast: at 80 periods and 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: and the Lyapunov exponent
Finally, the opening chaos in numbers. Integrate with RK4 and two trajectories apart in , another with from the same point, and estimate with Benettin’s method: follow a neighboring trajectory at distance , measure its separation each time unit and renormalize.
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 and reaching 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: does not change sign between and while trajectory circles (with ), and Jacobian at fixed points (same spectrum at and by symmetry ) has eigenvalues and . With , trajectories fully separate near . Simulations with and , starting at the same point, differ by at and at , and fully separate near : neither is the exact trajectory beyond then. Even so mean on 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 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 (eulerdampoption, enabled by default).implicitis implicit in velocity: linearizes all velocity-dependent forces (damping, actuators, Coriolis and centrifugal), except constraint forces, and solves a system with LU.implicitfastdoes the same without Coriolis and centrifugal derivatives, leaving a symmetric matrix factored by Cholesky. Documentation recommends it for stability-cost balance.RK4is 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).
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))npm run lab and open the connection link.Read output using lesson theory:
- Without friction,
Euler,implicitandimplicitfastgive 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 (about , and J at , and s on a J scale) and does not grow: maximum in the final 10% of simulation equals the first.RK4is vastly more accurate at equal step ( J with ), but error does grow with time, as in Kepler: at from to J. Per step it costs about four timesEuler(3.4 to 5 in our runs on a shared machine), evaluating dynamics four times;implicitandimplicitfastcost the same order asEuler(0.9 to 1.6 times) in this one-degree-of-freedom model. Time with the loop inside MuJoCo (nstep): timing a Python loop callingmj_stepstep by step mainly measures interpreter overhead. - With strong damping, velocity mode has . Absolute stability predicts Euler with explicit damping (
eulerdampdisabled) diverges for s, and RK4 for s. Exactly so: Euler withouteulerdampis stable at and diverges at , and RK4 is stable at and diverges at . Witheulerdamp(default) orimplicitfast, damping is implicit and simulation stable at any step. - 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.
Eulerandimplicitfasteven give the same penetration;RK4differs somewhat because it solves contact at every stage. Maximum penetration, measured only at step times, is about 10 mm with 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 , raising it automatically unlessrefsafeis disabled. With 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:
| Option | What it does | Beware |
|---|---|---|
method | RK45, RK23, DOP853 (explicit), Radau, BDF (implicit), LSODA (switches automatically) | default RK45 struggles on stiff problems |
rtol, atol | local-error tolerances; atol accepts a vector, one per component | defaults rtol = 1e-3 and atol = 1e-6, only about three digits |
jac, jac_sparsity | analytic Jacobian or sparsity pattern (implicit) | without jac, finite differences approximate it, more expensive and less accurate |
t_eval, dense_output | where solution is wanted; obtained from interpolant | do not change accuracy or steps |
events | functions whose zeros interpolant locates; may stop integration | an event crossing and recrossing within one step is missed |
max_step | limits step | needed if has details shorter than the integrator’s chosen step |
first_step | initial step | automatic 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: evaluations, network passes.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What recurrence does satisfy?
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, statsSummary
- Explicit Euler has local error and global : discrete Grönwall controls propagation of local errors with factor reflecting problem conditioning. Order- Runge–Kutta satisfies Butcher conditions through ; RK4 is explicit methods’ sweet spot.
- An embedded pair like Dormand–Prince 5(4) estimates local error almost free; a controller with exponent adjusts step to local timescale, like in an orbit. Tolerances control local error;
t_evalcontrols nothing. - Test equation gives . 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.