Numerical ODE Solvers: Accuracy, Stiffness, and Optimization Euler & Runge–Kutta · local vs. global error · stability function R(z) · stiffness & A-stability · gradient descent
Why Gradient Descent Blows Up on a Simple Bowl
Motivation
When a training run diverges at a large learning rate \eta, it is tempting to blame a pathological loss surface. Yet divergence happens on the simplest convex parabola \mathcal{L}(x) = 25x^2:
Gradient Descent as Euler’s Method: The update x_{k+1} = x_k - \eta \cdot 50x_k = (1 - 50\eta)x_k is one forward-Euler step of size h = \eta on the gradient flow ODE \dot{x} = -50x.
Exact Flow vs. Discrete Steps: The true continuous trajectory x(t) = e^{-50t}x_0 decays monotonically to zero from every starting point.
Step-Size Instability: At h = 0.01, Euler multiplies by 1 - 50(0.01) = 0.5 and converges; at h = 0.05, the exact flow shrinks by e^{-2.5} \approx 0.082, but Euler multiplies by 1 - 50(0.05) = -1.5, flipping sign and exploding.
The differential equation \dot{x} = -50x is completely stable—the numerical steps are unstable whenever h > 2/50 = 0.04.
Forward Euler as Compound Interest on a Vector Field
First-Order Solver
With step size h = T/n and grid times t_n = nh, forward Euler freezes the velocity arrow at the start of each step:
Compound interest on \dot{x} = x(x_0 = 1, T = 1):n steps compute x_n = (1 + 1/n)^n \to e \approx 2.7183.
First-order accuracy (p = 1): Doubling n cuts the endpoint error |x_n - e| \approx \frac{e}{2n} \approx 1.36\,h in half.
Local Truncation Error vs. Global Error Accumulation
Error Analysis I
Local truncation error (\|\mathbf{r}_n\| \le \frac12 M h^2): A single Euler step started on the true trajectory errs by O(h^2).
One-step error recursion: For an L-Lipschitz field, global error \varepsilon_n = \|\mathbf{x}_n - \mathbf{x}(t_n)\| obeys \varepsilon_{n+1} \le (1 + hL)\varepsilon_n + \frac12 M h^2.
Why one power of h is lost: Summing n = T/h steps divides by h, yielding global order p = 1: \varepsilon_n \le \frac{Mh}{2L}(e^{LT} - 1) = O(h).
Proof of Order-1 Global Convergence for Forward Euler
Error Analysis II
Unrolling the recursion \varepsilon_{n+1} \le (1 + hL)\varepsilon_n + \frac{1}{2}Mh^2 from \varepsilon_0 = 0 over n \le T/h steps sums a geometric series:
Where One Power of h Is Lost: Accumulating T/h local errors of size O(h^{p+1}) divides by h, yielding a global error of order p(O(h^p)).
When e^{LT} Is Tight vs. Pessimistic: On expanding \dot{x} = x(L=1, M=e), the bound gives 2.3h vs. true error 1.36h. On contracting \dot{x} = -50x, L = 50 ignores the sign of the slope and predicts e^{50} \approx 5 \times 10^{21}, whereas stable steps actually contract old errors by |1 - 50h| < 1.
Probing Slopes Inside the Step: Runge–Kutta Geometry
Higher-Order Solvers
Forward Euler commits to the initial slope while the trajectory curves away. Runge–Kutta methods probe the vector field at intermediate points inside the step to cancel higher-order Taylor terms:
On \dot{x} = x from x_0 = 1 with a single giant step h = 1 (exact e \approx 2.718): Euler lands at 2.0, Midpoint lands at 2.5, and 4-stage RK4 lands at 2.708 (within 0.4\%).
Second-Order Solvers: Midpoint and Heun’s Method
Order-2 Methods
Evaluating the vector field twice per step matches the O(h^2) second derivative \ddot{x} = f'(x)f(x) of the true Taylor expansion, leaving an O(h^3) local error and order p = 2 global error:
Explicit Midpoint Method: Takes a half-length trial Euler step to sample the slope at the midpoint t_n + h/2: \mathbf{x}_{n+1} = \mathbf{x}_n + h\,\mathbf{f}\!\left(\mathbf{x}_n + \frac{h}{2}\mathbf{f}(\mathbf{x}_n)\right)
Taylor Verification (1D):x + h f\!\left(x + \tfrac{h}{2}f\right) = x + hf + \tfrac{h^2}{2}f'f + O(h^3)
Heun’s Method (Explicit Trapezoid Rule): Takes a full trial Euler step and averages the initial and endpoint slopes: \mathbf{x}_{n+1} = \mathbf{x}_n + \frac{h}{2}\Big[\mathbf{f}(\mathbf{x}_n) + \mathbf{f}\big(\mathbf{x}_n + h\mathbf{f}(\mathbf{x}_n)\big)\Big]
Role in Diffusion Models: Modern diffusion and flow-matching samplers (such as EDM) use Heun’s method to cut step counts drastically.
Classical Fourth-Order Runge–Kutta (RK4)
The Workhorse Solver
Classical RK4 probes four slopes per step (start \mathbf{k}_1, two midpoints \mathbf{k}_2, \mathbf{k}_3, and endpoint \mathbf{k}_4) combined with Simpson’s weights:
Fourth-order accuracy (O(h^4)): Halving h shrinks global error by 2^4 = 16\times (vs. 2\times for Euler and 4\times for Heun) at a cost of 4 field evaluations per step.
The Stability Function R(z) on the Test Equation
Unifying Polynomial
On a scalar eigenmode \dot{y} = \lambda y(z = h\lambda), one solver step multiplies the state by its stability functiony_{n+1} = R(z)y_n:
Explicit Taylor polynomials: Euler R(z) = 1 + z(p=1); Midpoint/Heun R(z) = 1 + z + \tfrac12 z^2(p=2); RK4 truncates e^z through \frac{1}{24}z^4(p=4).
Two roles of R(z): Matching e^z near z = 0 sets the order of accuracyp; the region \{|R(z)| < 1\} sets numerical stability.
Implementing Forward Euler and RK4 in Code
Clean Implementation
Both explicit solvers require only a loop over n steps of size h = T/n and vector-field evaluations f(x):
def euler(f, x0, T, n):"""Forward Euler: n steps of size h = T/n.""" x, h = np.asarray(x0, dtype=float), T / nfor _ inrange(n): x = x + h * f(x)return xdef rk4(f, x0, T, n):"""Classical Runge-Kutta: four slope measurements per step.""" x, h = np.asarray(x0, dtype=float), T / nfor _ inrange(n): k1 = f(x) k2 = f(x +0.5* h * k1) k3 = f(x +0.5* h * k2) k4 = f(x + h * k3) x = x + (h /6) * (k1 +2* k2 +2* k3 + k4)return x
Order of Accuracy at Equal Computational Work
Benchmarking on the Spiral
On the planar spiral \mathbf{A} = -\frac{1}{2}\mathbf{I} + \mathbf{K}(\lambda = -0.5 \pm \mathrm{i},|\lambda T|^2 = 5 at T = 2), R(z) predicts global errors of 1.84/n for Euler and 0.343/n^4 for RK4:
Measured Log–Log Slopes: Linear regression confirms order 1.04 for Euler and 4.02 for RK4.
Equal Budget (512 Evaluations):512 Euler steps give error 3.6 \times 10^{-3}, whereas 128 RK4 steps (4 \times 128 = 512 evaluations) reach 1.3 \times 10^{-9}—six orders of magnitude more accurate.
Euler Cost to Match RK4: Achieving 1.3 \times 10^{-9} with Euler requires n \approx 1.4 \times 10^9 evaluations.
measured slope, Euler: 1.040
measured slope, RK4 : 4.022
error at 512 steps: Euler 3.6e-03, RK4 5.0e-12
RK4 with 128 steps (the same 512 evaluations): 1.3e-09
Adaptive Step Sizes and Symplectic Integrators
Specialized Solvers
Adaptive step control (Dormand–Prince RK45): Compares embedded orders p and p+1 on the same stages (\Delta = \|\hat{\mathbf{x}} - \mathbf{x}\|) and scales h \leftarrow 0.9\,h(\text{tol}/\Delta)^{1/(p+1)}.
Symplectic Euler & Leapfrog (HMC): Updating q_{n+1} = q_n + h p_n then p_{n+1} = p_n - h q_{n+1} on Hamiltonian oscillators preserves phase-space area exactly (\det\mathbf{S}_h = 1) for all time when h < 2.
Stiffness: Vanished Fast Modes Still Cap the Step
The Stiffness Bottleneck
A system is stiff when a fast decaying mode forces tiny explicit steps long after that mode has vanished:
The stability trap: By t = 0.1, x_1(t) = e^{-50t} is gone, and h = 0.1 tracks e^{-t} to 5\%. Yet forward Euler multiplies x_1 by 1 - 50(0.1) = -4 per step, exploding unless h < 2/50 = 0.04.
Backward Euler and Unconditional A-Stability
Implicit Solvers
Backward Euler evaluates the velocity arrow at the endpoint of the step:
Unconditional A-stability:|(1 - z)^{-1}| < 1 across the entire left half-plane \operatorname{Re}z < 0 (at h = 0.1, \lambda = -50, it damps by 1/6 per step instead of exploding).
Compute trade-off: Requires a linear or Newton solve per step.
Measuring Stiffness: Explicit vs. Implicit Steps
Numerical Experiment
Comparing forward and backward Euler on \dot{\mathbf{x}} = \mathrm{diag}(-50, -1)\mathbf{x} at T = 1 across step sizes h \in [0.01, 0.10]:
exact at T = 1: fast 1.9e-22, slow 0.3679
h fwd fast fwd slow bwd fast bwd slow
0.10 1.0e+06 0.3487 1.7e-08 0.3855
0.05 3.3e+03 0.3585 1.3e-11 0.3769
0.04 -1.0e+00 0.3604 1.2e-12 0.3751
0.02 0.0e+00 0.3642 8.9e-16 0.3715
0.01 7.9e-31 0.3660 2.5e-18 0.3697
At h = 0.10, both solvers track the slow mode e^{-1} \approx 0.3679 to within 5\%(0.3487 and 0.3855), but forward Euler blows up the fast mode to 1.0 \times 10^6 while backward Euler damps it to 1.0 \times 10^{-8}.
Stability Regions in the Complex z = hλ Plane
A-Stability
A solver’s stability region\{z \in \mathbb{C} : |R(z)| < 1\} shows which combinations of step size h and eigenvalue \lambda decay:
Forward Euler Disc (|1 + z| < 1): Unit disc centered at -1, reaching z = -2 on the real axis. Undamped rotations (z = \mathrm{i}hb) sit outside the disc and spiral outward at every h > 0.
RK4 Lobed Region: Reaches z \approx -2.79 on the negative real axis and covers an interval of the imaginary axis.
No Explicit RK Method Is A-Stable: Every s-stage explicit Runge–Kutta method has a polynomial R(z) of degree \le s, which must diverge as |z| \to \infty. Only implicit solvers like backward Euler cover the entire left half-plane \operatorname{Re}z < 0 (A-stability).
Gradient Descent Is Forward Euler on the Gradient Flow
Optimization as Dynamics
Continuous steepest descent on a loss \mathcal{L}(\mathbf{x}) defines the gradient flow\dot{\mathbf{x}} = -\nabla\mathcal{L}(\mathbf{x}), along which \frac{d}{dt}\mathcal{L}(\mathbf{x}(t)) = -\|\nabla\mathcal{L}\|^2 \le 0. Gradient descent with learning rate \eta is forward Euler with h = \eta:
\dot{\mathbf{x}} = -\nabla\mathcal{L}(\mathbf{x}) \;\xrightarrow{\text{linearize near } \mathbf{x}^\star}\; \dot{\boldsymbol{\delta}} = -\mathbf{H}\boldsymbol{\delta} \;\xrightarrow{\text{Euler, } h = \eta}\; \boldsymbol{\delta}_{k+1} = (\mathbf{I} - \eta\mathbf{H})\boldsymbol{\delta}_k
The Learning-Rate Ceiling: Each eigenvalue \lambda_i > 0 of the Hessian \mathbf{H} evolves with z_i = -\eta\lambda_i. Stability |1 - \eta\lambda_i| < 1 for all modes requires: \eta < \frac{2}{\lambda_{\max}(\mathbf{H})}
Ill-Conditioning Is Stiffness: With \eta capped by the sharpest curvature \lambda_{\max}, the flattest direction \lambda_{\min} contracts by at most 2\lambda_{\min}/\lambda_{\max} = 2/\kappa per step.
Three Solvers on an Ill-Conditioned Quadratic Valley
Numerical Experiment
Integrating the gradient flow \dot{\mathbf{x}} = -\mathbf{H}\mathbf{x} on \mathcal{L}(\mathbf{x}) = \frac{1}{2}\mathbf{x}^\top\mathrm{diag}(10, 1)\mathbf{x} for 100 steps of size \eta:
The Ceiling Is a Quotient: The loss Hessian supplies the denominator \lambda_{\max} = 10, while the solver’s real stability boundary supplies the numerator (2 / 10 = 0.20 for Euler, 2.79 / 10 = 0.279 for RK4, and \infty for Backward Euler).
Why Deep Learning Optimizers Use Euler (and Momentum)
Systems Trade-Offs
Max flow time per gradient: On \lambda_{\max} = 10, Euler advances 0.200 units of flow time per gradient evaluation, whereas 4-stage RK4 advances only 0.279/4 = 0.070 units per gradient.
Endpoints vs. paths: Optimization only cares about reaching \mathbf{x}^\star, and Euler’s backward error implicitly regularizes \mathcal{L}(\mathbf{x}) + \frac{\eta}{4}\|\nabla\mathcal{L}(\mathbf{x})\|^2.
Momentum changes the ODE: Heavy-ball momentum discretizes a second-order damped oscillator m\ddot{\mathbf{x}} + c\dot{\mathbf{x}} = -\nabla\mathcal{L} to achieve \sqrt{\kappa} scaling at 1 gradient/step.
Concept Check: Order, Stiffness, and Stability Regions
Concept Check
Work through these three solver questions:
Error Scaling vs. Work: You halve the step size h \to h/2 on a smooth ODE. By what factor does the global error drop for Heun’s method and for RK4?
Spiral Step Ceiling: For the planar spiral with eigenvalues \lambda = -0.5 \pm \mathrm{i}, forward Euler has |1 + h\lambda|^2 = (1 - 0.5h)^2 + h^2. What is the largest step size h for which the Euler iterates decay?
Mode of Divergence: When \eta slightly exceeds the stability ceiling on \dot{x} = -10x, how does Euler’s divergence at \eta = 0.21 differ visually from RK4’s divergence at \eta = 0.29?
Answers:
Heun (order 2) drops by 2^2 = 4\times; RK4 (order 4) drops by 2^4 = 16\times.
(1 - 0.5h)^2 + h^2 = 1 - h + 1.25h^2 < 1 \iff 1.25h^2 < h \iff h < 0.8.
Euler’s multiplier R(-2.1) = 1 - 2.1 = -1.1 < -1 is negative, so iterates zigzag across the valley floor with growing amplitude. RK4’s polynomial R(-2.9) = +1.187 > 1 is positive, so iterates walk monotonically uphill on one side without changing sign.