Astronomy and Space Exploration ES

Higher Education / Numerical methods in astrophysics

Runge–Kutta and adaptive step size

From Euler to RK4 and to the embedded pairs RKF45 and Dormand–Prince: order, local and global error, automatic step-size control and its application to a highly eccentric orbit, with measured error tables.

⏱ 180 min ODEsTaylor seriesorder conditionslinear stabilityerror analysisfeedback step control revision

By the end you will be able to:
  • Define the local and global error of a one-step method and prove that a local error O(h^(p+1)) produces a global error O(h^p) under a Lipschitz condition.
  • Derive the order conditions of Runge–Kutta methods up to order 2 and state those of RK4.
  • Explain the principle of embedded pairs (RKF45, Dormand–Prince) and derive the step-control law from the local error estimate.
  • Numerically measure the order of Euler, RK4 and Dormand–Prince on a Keplerian orbit and compare the cost of fixed and adaptive step on an orbit of eccentricity 0.9.
  • Recognize which properties (symplecticity, energy conservation) are lost with the adaptive step and when it pays off.

1. Motivation: a probe on a highly eccentric orbit

Illustration: Motivation: a probe on a highly eccentric orbit

A probe on an orbit of eccentricity e=0.9e = 0.9 spends 90% of the time far from the planet moving slowly and, for a brief fraction, crosses the pericenter at a velocity (1+e)/(1−e)=19≈4.4\sqrt{(1+e)/(1-e)} = \sqrt{19} \approx 4.4 times larger than at the apocenter. If we integrate with a small fixed step to resolve the pericenter, we waste almost all the work at the apocenter; if we choose it large, the pericenter is poorly resolved and the orbit opens or closes. This is the problem solved by adaptive step methods: estimate the error of each step and let the integrator itself decide how long the next one can be.

In this lesson we use the planar Kepler problem with gravitational parameter μ=G(m1+m2)\mu = G(m_1+m_2) as a test bench, because it has an exact solution (lesson on Kepler’s equation) against which to measure errors. We write y=(x,y,vx,vy)y = (x, y, v_x, v_y) and

y˙=f(t,y)=(vx, vy, −μxr3, −μyr3),r=x2+y2.\dot y = f(t, y) = \left(v_x,\ v_y,\ -\frac{\mu x}{r^3},\ -\frac{\mu y}{r^3}\right),\qquad r = \sqrt{x^2+y^2}.

Units: in the code (src/lib/math/rungekutta.ts\mathtt{src/lib/math/rungekutta.ts}) everything is dimensionless with μ=1\mu = 1, a=1a = 1; the period is T=2πT = 2\pi. To go to SI it suffices to fix μ\mu and aa and use [t]=a3/μ[t] = \sqrt{a^3/\mu}.

2. One-step methods: local and global error

Illustration: One-step methods: local and global error

Let y˙=f(t,y)\dot y = f(t,y) with ff Lipschitz in yy with constant LL, that is, ∥f(t,u)−f(t,v)∥≤L∥u−v∥\lVert f(t,u) - f(t,v)\rVert \le L\lVert u - v\rVert. A one-step method advances with an increment function Φ\Phi:

yn+1=yn+h Φ(tn,yn,h).y_{n+1} = y_n + h\,\Phi(t_n, y_n, h).

Definition. The local error at step nn is the difference between what the method gives starting from the exact value and the exact value one step later: ℓn+1=y(tn)+hΦ(tn,y(tn),h)−y(tn+1)\ell_{n+1} = y(t_n) + h\Phi(t_n, y(t_n), h) - y(t_{n+1}). The method is of order pp if ∥ℓn+1∥≤Chp+1\lVert\ell_{n+1}\rVert \le C h^{p+1}. The global error is en=yn−y(tn)e_n = y_n - y(t_n).

Theorem (convergence). If the method has order pp and Φ\Phi is Lipschitz in yy with constant Λ\Lambda, then on a fixed interval [t0,t0+Tf][t_0, t_0 + T_f]

∥en∥≤ChpΛ(eΛTf−1)=O(hp).\lVert e_n\rVert \le \frac{C h^{p}}{\Lambda}\left(e^{\Lambda T_f} - 1\right) = O(h^p).

Proof. Subtracting the definition of the local error from that of the method, en+1=en+h[Φ(tn,yn,h)−Φ(tn,y(tn),h)]+ℓn+1e_{n+1} = e_n + h\left[\Phi(t_n, y_n, h) - \Phi(t_n, y(t_n), h)\right] + \ell_{n+1}, hence ∥en+1∥≤(1+hΛ)∥en∥+Chp+1\lVert e_{n+1}\rVert \le (1 + h\Lambda)\lVert e_n\rVert + C h^{p+1}. Iterating this linear recurrence with e0=0e_0 = 0,

∥en∥≤Chp+1∑k=0n−1(1+hΛ)k=Chp+1 (1+hΛ)n−1hΛ≤ChpΛ(enhΛ−1),\lVert e_n\rVert \le C h^{p+1}\sum_{k=0}^{n-1}(1+h\Lambda)^k = C h^{p+1}\,\frac{(1+h\Lambda)^n - 1}{h\Lambda} \le \frac{C h^p}{\Lambda}\left(e^{n h\Lambda} - 1\right),

using (1+hΛ)n≤enhΛ(1 + h\Lambda)^n \le e^{nh\Lambda}. With nh≤Tfnh \le T_f the bound follows. ■\blacksquare

A local error O(hp+1)O(h^{p+1}) becomes a global O(hp)O(h^p) because n=Tf/hn = T_f/h errors are committed. The constant eΛTfe^{\Lambda T_f} is pessimistic but real: in orbits, phase errors grow linearly with time, and in chaotic systems exponentially (previous lesson).

2.1 Euler

Φ=f(tn,yn)\Phi = f(t_n, y_n). Comparing with the Taylor series y(tn+h)=y+hy˙+h22y¨+…y(t_n + h) = y + h\dot y + \tfrac{h^2}{2}\ddot y + \dots, the local error is h22y¨+O(h3)\tfrac{h^2}{2}\ddot y + O(h^3): order 1. For a circular orbit, y¨\ddot y points toward the center and Euler always leaves “along the tangent”: the orbit grows in a spiral (exercise 1). In our table (§5) one needs h≈10−3h \approx 10^{-3} for a 20% error after a single revolution.

2.2 Order conditions: the two-stage case

An explicit Runge–Kutta method with ss stages is defined by its Butcher tableau (c,A,b)(c, A, b):

ki=f ⁣(tn+cih, yn+h∑j<iaijkj),yn+1=yn+h∑i=1sbiki.k_i = f\!\left(t_n + c_i h,\ y_n + h\sum_{j<i} a_{ij} k_j\right),\qquad y_{n+1} = y_n + h\sum_{i=1}^{s} b_i k_i .

For two stages with c1=0c_1 = 0, c2=a21=cc_2 = a_{21} = c (condition ∑jaij=ci\sum_j a_{ij} = c_i, which we always assume), and writing ff, ftf_t, fyf_y evaluated at (tn,yn)(t_n, y_n),

k2=f+ch (ft+fyf)+O(h2),yn+1=yn+h(b1+b2)f+h2b2c (ft+fyf)+O(h3).k_2 = f + c h\,(f_t + f_y f) + O(h^2),\qquad y_{n+1} = y_n + h(b_1 + b_2) f + h^2 b_2 c\,(f_t + f_y f) + O(h^3).

The exact solution is y+hf+h22(ft+fyf)+O(h3)y + h f + \tfrac{h^2}{2}(f_t + f_y f) + O(h^3), so the method is of order 2 if and only if

b1+b2=1,b2c=12.b_1 + b_2 = 1,\qquad b_2 c = \tfrac12 .

It is a one-parameter family: c=12c = \tfrac12 gives the midpoint method (b=(0,1)b = (0, 1)) and c=1c = 1 Heun’s method (b=(12,12)b = (\tfrac12, \tfrac12)). For order 3 there are 4 conditions, for order 4 there are 8 and for order 5 there are 17; the number of conditions grows like the rooted trees with pp vertices (Butcher’s theory; Hairer–Nørsett–Wanner §II.2). This is why the classical RK4 with 4 stages and order 4 is a sweet spot: from order 5 on, more stages than the order are needed (66 stages for order 5, 77 for order 6).

2.3 RK4

With c=(0,12,12,1)c = (0, \tfrac12, \tfrac12, 1), a21=a32=12a_{21} = a_{32} = \tfrac12, a43=1a_{43} = 1 and b=16(1,2,2,1)b = \tfrac16(1, 2, 2, 1) the 8 conditions of order 4 are satisfied: local error O(h5)O(h^5), global O(h4)O(h^4). Applied to y˙=λy\dot y = \lambda y it gives yn+1=R(hλ)yny_{n+1} = R(h\lambda) y_n with R(z)=1+z+z2/2+z3/6+z4/24R(z) = 1 + z + z^2/2 + z^3/6 + z^4/24, the Taylor polynomial of eze^z: the region of absolute stability ∣R(z)∣≤1\lvert R(z)\rvert \le 1 cuts the negative real axis at z=−2.785z = -2.785 and the imaginary axis at ±2.83 i\pm 2.83\,i. For an oscillator of frequency ω\omega this requires hω<2.83h\omega \lt 2.83; at the pericenter of an orbit the “local frequency” is μ/rp3\sqrt{\mu/r_p^3}, and it is what sets the step.

3. Embedded pairs and step control

Illustration: Embedded pairs and step control

3.1 The idea

If we have two approximations yn+1y_{n+1} (order pp) and y^n+1\hat y_{n+1} (order p^=p−1\hat p = p - 1) that share the same stages kik_i (only the weights bib_i versus b^i\hat b_i change), the difference

errn+1=yn+1−y^n+1=h∑i(bi−b^i) ki=O(hp)\mathrm{err}_{n+1} = y_{n+1} - \hat y_{n+1} = h\sum_i (b_i - \hat b_i)\,k_i = O(h^{p})

estimates the local error of the lower-order method without any additional evaluation. The two most used pairs:

PairStagesOrdersAuthorFeature
RKF4564(5)Fehlberg (1969)designed to propagate the order-4 solution; in practice the order-5 one is propagated (“local extrapolation”)
Dormand–Prince 5(4)75(4)Dormand & Prince (1980)coefficients optimized to minimize the error of the order-5 method; FSAL property: the seventh stage coincides with the first of the next step, hence it costs 6 evaluations per accepted step

It is MATLAB’s ode45 and SciPy’s RK45. Both tableaux are in rungekutta.ts; the test checks the identities ∑bi=∑b^i=1\sum b_i = \sum\hat b_i = 1, ∑jaij=ci\sum_j a_{ij} = c_i, and measures the order 5 of the propagated solution and the order 5 of the error estimator (§5). Our implementation does not exploit FSAL (7 evaluations per step), which inflates the Dormand–Prince evaluation counts in the tables by 17%.

3.2 Step-control law

We want the local error per component not to exceed a mixed tolerance sci=atol+rtol⋅max⁡(∣yn,i∣,∣yn+1,i∣)sc_i = \mathrm{atol} + \mathrm{rtol}\cdot\max(\lvert y_{n,i}\rvert, \lvert y_{n+1,i}\rvert). We define the scaled norm

err=1N∑i=1N(errn+1,isci)2.\mathrm{err} = \sqrt{\frac1N\sum_{i=1}^N\left(\frac{\mathrm{err}_{n+1,i}}{sc_i}\right)^2}.

Since err≈Khq\mathrm{err} \approx K h^{q} with q=p^+1q = \hat p + 1 (the order of the local error of the embedded method of order p^\hat p), the “optimal” step that would give err=1\mathrm{err} = 1 is hopt=h err−1/qh_{\text{opt}} = h\,\mathrm{err}^{-1/q}. With a safety factor and limits to avoid oscillations:

hnew=h⋅min⁡ ⁣(5, max⁡ ⁣(0.2, 0.9 err−1/q)).h_{\text{new}} = h\cdot\min\!\left(5,\ \max\!\left(0.2,\ 0.9\,\mathrm{err}^{-1/q}\right)\right).

If err≤1\mathrm{err} \le 1 the step is accepted and we advance; if not, it is rejected and repeated with hnewh_{\text{new}}. It is a proportional controller (Hairer–Nørsett–Wanner §II.4, eq. 4.13). In integrarAdaptativo we use q=5q = 5 for both pairs.

One should be honest about what is controlled: the local error per step, not the global one. The accumulated global error can be orders of magnitude larger than the tolerance (table in §5: with tol=10−6\mathrm{tol} = 10^{-6} the position error after one revolution is ∼10−3\sim 10^{-3}) because the phase errors add up and because the eccentric orbit amplifies perturbations near the pericenter. The practical rule is that the global error scales linearly with the tolerance for a method of order pp propagated with local extrapolation (tolp/(p+1)\mathrm{tol}^{p/(p+1)} in theory, but in practice the exponent is usually between 0.8 and 1): the table gives tol 10−6→10−12\mathrm{tol}\, 10^{-6}\to10^{-12} and error 1.6×10−3→4×10−101.6\times10^{-3}\to 4\times10^{-10}, that is, a factor 4×1064\times 10^{6} in error for 10610^{6} in tolerance.

4. Simulator

three equal masses, T ≈ 6.3259 · t = 0.00

What to observe. The simulator integrates with a fixed step (RK4 or leapfrog). With “2 bodies, e = 0.8”, measure how many steps per period RK4 needs for the orbit to close visibly: that number is what an adaptive integrator distributes unevenly, concentrating the short steps at the pericenter (in our run with e=0.9e = 0.9 and tol=10−10\mathrm{tol} = 10^{-10}, the step varies between 4.3×10−54.3\times10^{-5} and 9.5×10−29.5\times10^{-2}: a factor of 2200).

5. Numerical results

Illustration: Numerical results

All the numbers in this section come from rungekutta.ts (the test rungekutta.test.ts verifies the orders; the tables were generated with the same code). Orbit a=1a = 1, μ=1\mu = 1, T=2πT = 2\pi; position error ∥rN−r(T)∥\lVert \mathbf r_N - \mathbf r(T)\rVert after one revolution against the Kepler solution, and relative energy error ∣ΔE/E∣\lvert\Delta E/E\rvert.

5.1 Measured order, e=0.5e = 0.5, fixed step

Steps per revolutionhhEulerRK4Dormand–Prince (order 5, fixed step)
1006.28×10−26.28\times10^{-2}4.64.65.5×10−45.5\times10^{-4}7.8×10−67.8\times10^{-6}
2003.14×10−23.14\times10^{-2}3.23.22.6×10−52.6\times10^{-5}2.7×10−72.7\times10^{-7}
4001.57×10−21.57\times10^{-2}2.22.21.4×10−61.4\times10^{-6}7.3×10−97.3\times10^{-9}
8007.85×10−37.85\times10^{-3}1.41.47.9×10−87.9\times10^{-8}2.0×10−102.0\times10^{-10}
16003.93×10−33.93\times10^{-3}0.830.834.7×10−94.7\times10^{-9}5.6×10−125.6\times10^{-12}
32001.96×10−31.96\times10^{-3}0.450.452.9×10−102.9\times10^{-10}1.5×10−131.5\times10^{-13}
64009.8×10−49.8\times10^{-4}0.230.231.8×10−111.8\times10^{-11}1.3×10−131.3\times10^{-13}

When hh is divided by 2, Euler divides the error by ≈1.5\approx 1.5–22 (order 1, still outside the asymptotic regime while the error is O(1)O(1)), RK4 by ≈17\approx 17–2121 (order 4, 24=162^4 = 16) and Dormand–Prince by ≈29\approx 29–3737 (order 5, 25=322^5 = 32). In the last row Dormand–Prince has already hit the round-off floor in double precision (∼10−13\sim 10^{-13} after 6400×76400\times 7 evaluations): reducing the step further improves nothing, because the round-off error grows as ϵmach/h\epsilon_{\text{mach}}/h.

The energy of RK4 drifts: with h=T/200h = T/200 the error ∣ΔE/E∣\lvert\Delta E/E\rvert is 9.3×10−79.3\times10^{-7} after 1 revolution, 9.3×10−69.3\times10^{-6} after 10 and 9.3×10−59.3\times10^{-5} after 100: exactly linear in tt, as was proved for the oscillator in the previous lesson.

5.2 Adaptive step, e=0.9e = 0.9, one revolution

TolerancePairAccepted stepsRejectedEvaluations of ffPosition error∣ΔE/E∣\lvert\Delta E/E\rvert
10−610^{-6}RKF4553214441.1×10−31.1\times10^{-3}5.0×10−55.0\times10^{-5}
10−610^{-6}DP5(4)50204901.6×10−31.6\times10^{-3}1.1×10−51.1\times10^{-5}
10−810^{-8}RKF45123188461.3×10−51.3\times10^{-5}6.9×10−76.9\times10^{-7}
10−810^{-8}DP5(4)114249661.1×10−51.1\times10^{-5}7.0×10−87.0\times10^{-8}
10−1010^{-10}RKF45302118181.3×10−71.3\times10^{-7}5.9×10−95.9\times10^{-9}
10−1010^{-10}DP5(4)278119536.5×10−86.5\times10^{-8}8.2×10−108.2\times10^{-10}
10−1210^{-12}RKF45760145661.3×10−91.3\times10^{-9}6.0×10−116.0\times10^{-11}
10−1210^{-12}DP5(4)698148934.1×10−104.1\times10^{-10}1.1×10−111.1\times10^{-11}

Comparison with fixed-step RK4 on the same orbit: to bring the position error down to 1.6×10−71.6\times10^{-7} one needs 16 00016\,000 steps (64 00064\,000 evaluations); Dormand–Prince achieves it with tolerance 10−1010^{-10} and 19531953 evaluations, 33 times fewer. The gain is larger the more eccentric the orbit: on a circular one the adaptive step contributes little.

Two observations on the table. (1) At loose tolerance there are many rejections (≈ 30%): the proportional controller overestimates the step after the pericenter; PI controllers (Gustafsson 1991) reduce them. (2) Dormand–Prince conserves energy better than RKF45 at the same cost because its coefficients minimize the error of the order-5 formula, which is the one propagated; RKF45 was optimized for the order-4 one.

6. Error analysis: what the adaptive step does not give

Illustration: Error analysis: what the adaptive step does not give
  1. It is not symplectic. Changing hh according to the state turns the map into y↦Φh(y)(y)y \mapsto \Phi_{h(y)}(y), which in general does not conserve the symplectic form even if Φh\Phi_h does (Hairer–Lubich–Wanner §VIII.2). The energy drifts again: in the table, ∣ΔE/E∣\lvert\Delta E/E\rvert grows with time as in RK4. For integrations of thousands of periods a fixed-step symplectic method is preferred (or one with a reversible variable step, which uses a time transformation dt=g(y) dτdt = g(y)\,d\tau and recovers conservation).
  2. It controls the local error, not the global one. We saw that the global one can be 10310^{3} times the tolerance. To estimate the global error one must integrate twice (with tol\mathrm{tol} and tol/10\mathrm{tol}/10) and compare, or integrate forward and backward.
  3. Round-off. The total error is ≈C1hp+C2 ϵmach/h\approx C_1 h^{p} + C_2\,\epsilon_{\text{mach}}/h; there is an optimal hh and asking for tol<10−13\mathrm{tol} \lt 10^{-13} in double precision is useless (row 6400 of table 5.1).
  4. Close encounters. The adaptive step resolves them (its great advantage over the fixed step), but the cost explodes: h∼rmin⁡3/μh \sim \sqrt{r_{\min}^3/\mu}. For nearly exact collisions one must regularize (Kustaanheimo–Stiefel) or use coordinates that remove the singularity.

Problems

1. (Euler on a circular orbit). For y˙=f(y)\dot y = f(y) with μ=1\mu = 1, r=1r = 1 and circular velocity v=1v = 1, show that one Euler step increases rr by h22+O(h4)\tfrac{h^2}{2} + O(h^4) and the specific energy by h22+O(h4)\tfrac{h^2}{2} + O(h^4), so that the orbit opens in a spiral.

Show solution

We start from r=(1,0)\mathbf r = (1, 0), v=(0,1)\mathbf v = (0, 1), a=(−1,0)\mathbf a = (-1, 0). Euler gives r1=(1,h)\mathbf r_1 = (1, h), v1=(−h,1)\mathbf v_1 = (-h, 1). Then r1=1+h2=1+h22+O(h4)r_1 = \sqrt{1 + h^2} = 1 + \tfrac{h^2}{2} + O(h^4) and v12=1+h2v_1^2 = 1 + h^2. The specific energy goes from E0=12−1=−12E_0 = \tfrac12 - 1 = -\tfrac12 to E1=1+h22−11+h2=12+h22−1+h22+O(h4)=−12+h2+O(h4)E_1 = \tfrac{1 + h^2}{2} - \tfrac{1}{\sqrt{1+h^2}} = \tfrac12 + \tfrac{h^2}{2} - 1 + \tfrac{h^2}{2} + O(h^4) = -\tfrac12 + h^2 + O(h^4). At each step the energy rises by ≈h2\approx h^2 (always with the same sign: that is why it is secular), and after n=2π/hn = 2\pi/h steps it rises by ≈2πh\approx 2\pi h: linear in hh, order 1. In the table, with h=10−3h = 10^{-3} the energy error after one revolution is 2.3×10−2⋅12≈0.012≈2πh⋅22.3\times10^{-2}\cdot\tfrac12 \approx 0.012 \approx 2\pi h \cdot 2; the factor 2 comes from the fact that on the e=0.5e = 0.5 orbit the contribution of the pericenter dominates.

2. (Order-2 conditions). Show that there is no explicit 2-stage Runge–Kutta method of order 3.

Show solution

With the expansion of §2.2 carried to O(h3)O(h^3): the exact solution contains the term h36(ftt+2ftyf+fyyf2+fy(ft+fyf))\tfrac{h^3}{6}\left(f_{tt} + 2f_{ty}f + f_{yy}f^2 + f_y(f_t + f_y f)\right), whereas the method contributes h3b2c22(ftt+2ftyf+fyyf2)h^3 b_2 \tfrac{c^2}{2}\left(f_{tt} + 2 f_{ty} f + f_{yy} f^2\right) and no term proportional to fy(ft+fyf)f_y(f_t + f_y f) (that term only appears when evaluating ff at a point that already contains a “nested” evaluation of ff, which requires a third stage). For general ff both types of terms are independent, so the condition 0=160 = \tfrac16 is impossible. The conditions for order 3 with three stages are ∑bi=1\sum b_i = 1, ∑bici=12\sum b_i c_i = \tfrac12, ∑bici2=13\sum b_i c_i^2 = \tfrac13 and ∑i,jbiaijcj=16\sum_{i,j} b_i a_{ij} c_j = \tfrac16. ■\blacksquare

3. (Linear stability of RK4). Show that for y˙=iωy\dot y = i\omega y RK4 gives ∣R(ihω)∣2=1−(hω)672+(hω)8576\lvert R(i h\omega)\rvert^2 = 1 - \tfrac{(h\omega)^6}{72} + \tfrac{(h\omega)^8}{576} and deduce the stability limit hω<22h\omega \lt 2\sqrt2.

Show solution

With θ=hω\theta = h\omega, R(iθ)=(1−θ22+θ424)+i(θ−θ36)R(i\theta) = \left(1 - \tfrac{\theta^2}{2} + \tfrac{\theta^4}{24}\right) + i\left(\theta - \tfrac{\theta^3}{6}\right). Squaring and adding (computation of the previous lesson, exercise 3) gives 1−θ6/72+θ8/5761 - \theta^6/72 + \theta^8/576. The condition ∣R∣≤1\lvert R\rvert \le 1 is equivalent to θ8/576≤θ6/72\theta^8/576 \le \theta^6/72, that is, θ2≤8\theta^2 \le 8, θ≤22≈2.83\theta \le 2\sqrt2 \approx 2.83. For small θ\theta, ∣R∣≈1−θ6/144\lvert R\rvert \approx 1 - \theta^6/144: weak damping per step, which accumulated over t/ht/h steps gives the decay e−th5ω6/144e^{-t h^5\omega^6/144}. This is the secular energy drift of RK4.

4. (Error estimator). For an embedded pair of orders pp and p^=p−1\hat p = p - 1, show that yn+1−y^n+1y_{n+1} - \hat y_{n+1} is an asymptotically correct estimate of the local error of y^n+1\hat y_{n+1} but not of that of yn+1y_{n+1}, and explain why, even so, yn+1y_{n+1} is propagated.

Show solution

Let y(tn+1)y(t_{n+1}) be the local exact solution. Then yn+1−y(tn+1)=O(hp+1)y_{n+1} - y(t_{n+1}) = O(h^{p+1}) and y^n+1−y(tn+1)=ℓ^+O(hp+1)\hat y_{n+1} - y(t_{n+1}) = \hat\ell + O(h^{p+1}) with ℓ^=O(hp)\hat\ell = O(h^{p}) the leading term of the local error of the method of order p^\hat p. Subtracting, yn+1−y^n+1=−ℓ^+O(hp+1)y_{n+1} - \hat y_{n+1} = -\hat\ell + O(h^{p+1}): it coincides with the error of y^\hat y to leading order, whereas that of yy is of a higher order and is masked. One propagates yn+1y_{n+1} (“local extrapolation”) because it is more accurate; the price is that the step is controlled with a conservative estimate: the actual error committed is smaller than the estimated one. This is what makes the global error in table 5.2 look more like tol\mathrm{tol} than like tol4/5\mathrm{tol}^{4/5}.

5. (Control law). Suppose that err(h)=Kh5\mathrm{err}(h) = K h^{5} exactly. Show that, after a rejection, the new step h′=0.9 h err−1/5h' = 0.9\,h\,\mathrm{err}^{-1/5} is always accepted, and compute how much the factor 0.9 wastes in the number of steps.

Show solution

err(h′)=K(0.9h)5err−1=0.95⋅Kh5/err=0.95=0.59<1\mathrm{err}(h') = K (0.9 h)^5\mathrm{err}^{-1} = 0.9^5\cdot K h^5/\mathrm{err} = 0.9^5 = 0.59 \lt 1: accepted. Without the factor the step would give exactly err=1\mathrm{err} = 1, at the limit. With factor 0.9, the step is 10% smaller and 11% more steps are needed (1/0.91/0.9). In reality KK varies along the orbit (it grows toward the pericenter) and the model err=Kh5\mathrm{err} = K h^5 fails just where it matters: hence the rejections in the table at loose tolerance.

6. (Computational: order table). Implement fixed-step Euler, RK4 and Dormand–Prince and reproduce table 5.1 for e=0.5e = 0.5. Then estimate the empirical order p=log⁡2(err(h)/err(h/2))p = \log_2\left(\mathrm{err}(h)/\mathrm{err}(h/2)\right) row by row and explain the deviations from 1, 4 and 5.

Show solution

Pseudocode (Python):

import numpy as np
mu = 1.0
def f(t, y):
    r3 = np.hypot(y[0], y[1])**3
    return np.array([y[2], y[3], -mu*y[0]/r3, -mu*y[1]/r3])
def rk4(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 orbita(paso, n, e=0.5):
    y = np.array([1-e, 0, 0, np.sqrt((1+e)/(1-e))]); h = 2*np.pi/n
    for k in range(n): y = paso(f, k*h, y, h)
    return np.hypot(y[0]-(1-e), y[1])      # after T the probe returns to the pericenter
for n in [100, 200, 400, 800, 1600]:
    print(n, orbita(rk4, n), orbita(rk4, n)/orbita(rk4, 2*n))

For Dormand–Prince the coefficients are copied from rungekutta.ts (table 2 of Dormand & Prince 1980). Empirical orders from our table: Euler 0.52, 0.56, 0.64, 0.76, 0.88, 0.96 (tends to 1 from below: the error is O(1)O(1) and the asymptotic expansion does not hold); RK4 4.4, 4.2, 4.1, 4.1, 4.0, 4.0; DP5 4.9, 5.2, 5.2, 5.1, 5.2 and then 0.2 (round-off). The values somewhat larger than pp in RK4 and DP5 at coarse step come from the higher-order terms of the error, which decay faster.

7. (Computational: adaptive step). Implement the controller of §3.2 on Dormand–Prince and integrate the e=0.9e = 0.9 orbit for one revolution with tol=10−6,10−8,10−10\mathrm{tol} = 10^{-6}, 10^{-8}, 10^{-10}. Record hh as a function of the true anomaly and check that h∝r3/2h \propto r^{3/2} approximately. Why that exponent?

Show solution

The local error of a method of order 5 scales as h6 ∥y(6)∥h^6\,\lVert y^{(6)}\rVert and the derivatives of the Keplerian solution scale with the local frequency Ω(r)=μ/r3\Omega(r) = \sqrt{\mu/r^3}: ∥y(6)∥∼Ω6∥y∥\lVert y^{(6)}\rVert \sim \Omega^6\lVert y\rVert. Imposing a constant local error gives h Ω≈h\,\Omega \approx const, that is, h∝r3/2h \propto r^{3/2}. Between the apocenter (r=1.9r = 1.9) and the pericenter (r=0.1r = 0.1) the expected step ratio is 193/2≈8319^{3/2} \approx 83; the measured ratio between the maximum and minimum step was 2200 because the minimum occurs right at the pericenter, where in addition the components of yy are small and the relative tolerance bites harder, and the maximum is set by the growth limit of ×5\times 5 per step when moving away. (It is a good exercise to plot h(ν)h(\nu) on a logarithmic scale.)

✦ Self-assessment

  1. 1. A method has local error O(h⁵). Its global error on a fixed interval is, in general, of order…
  2. 2. What does the difference between the two solutions of an embedded pair such as Dormand–Prince 5(4) estimate?
  3. 3. If dividing the step by 2 divides the error by 32, the method is of order…
  4. 4. On an orbit of eccentricity 0.9 the adaptive step becomes smaller…
  5. 5. Which property is lost when using an adaptive step with a symplectic integrator?
  6. 6. Asking for a tolerance of 10⁻¹⁵ in double precision…
Answer all the questions to check.

Further reading

  • Hairer, Nørsett & Wanner (1993), Solving ODEs I: §II.1 (Runge–Kutta and Butcher theory), §II.3 (convergence), §II.4 (error estimation, step control, Gustafsson’s PI controller), §II.5 (Dormand–Prince tableau).
  • Press et al. (2007), Numerical Recipes, 3rd ed.: §17.1–17.2 (StepperDopr5, step control).
  • Dormand & Prince (1980), J. Comput. Appl. Math. 6, 19–26 (table 2: RK5(4)7M coefficients). Fehlberg (1969), NASA TR R-315 (table III).
  • Hairer, Lubich & Wanner (2006), Geometric Numerical Integration: §VIII.2 (why the variable step destroys symplecticity and how to recover it with time transformations).
  • Murray & Dermott (1999), ch. 2: exact solution of the two-body problem used as reference.
🍎 Teacher guide
Time
2 classes of 90 min
Learning outcome
By the end, the student proves the relation between local and global error, derives the order-2 conditions, implements an embedded pair with step control and experimentally evaluates the order and the cost of Euler, RK4 and Dormand–Prince on a Keplerian orbit.
Evidence of learning
Submission of problem 6 (order table with empirical orders) and of problem 7 (plot of h versus the true anomaly), with a half-page discussion of what the adaptive step does not control.

Materials

  • Python 3 with NumPy (or Julia); optionally SciPy to compare with solve_ivp(method="RK45")
  • Reference code: src/lib/math/rungekutta.ts and its test
  • The portal's N-body simulator

Suggested sequence

Class 1 (90 min). Opening (15 min): the problem of the eccentric probe, estimating by hand with hΩ<2.8h\Omega \lt 2.8 how many RK4 steps would be needed at the pericenter and at the apocenter. Development (60 min): proof of the convergence theorem on the board; order-2 conditions derived by the students in pairs (§2.2); presentation of RK4 and its stability region. Closing (15 min): problem 1 (Euler in a spiral) with a quick calculation and check in the simulator.

Class 2 (90 min). Opening (10 min): “how does the integrator know it is wrong?” (idea of the embedded pair). Development (60 min): programming workshop: implement Dormand–Prince with the given coefficients, verify the tableau sums, reproduce the order table (problem 6) and add the step controller (problem 7). Closing (20 min): share the plots of h(ν)h(\nu), discuss the loss of symplecticity and when each family of methods is preferred; mini-quiz.

Common mistakes

  • Believing that the tolerance is the final error. Show table 5.2: with tol = 10⁻⁶ the global error is 10⁻³. Ask them to integrate twice with different tolerances to estimate the global error.
  • Confusing the order of the local and global error. Insist on the theorem of §2: one power is lost when adding up T/h steps.
  • Reducing the step “until it converges” without noticing round-off. Row 6400 of table 5.1 shows it: the error stops decreasing.
  • Assuming that Dormand–Prince, being of order 5, conserves energy better than an order-2 leapfrog at long times. Compare with the previous lesson: high order reduces the error per step, but the secular drift remains.
  • Forgetting the condition Σⱼ aᵢⱼ = cᵢ when copying a Butcher tableau. Make the sum test (as in rungekutta.test.ts) part of the submission.
Key terms in this lesson (12)

Glossary terms that appear in the text. Each one links to its full entry.

  • Runge–Kutta method An improvement on Euler's method that "samples" the slope at several intermediate points of each step and averages them. The fourth-order version (RK4) is thousands of times more accurate for the same step size.
  • Orbit The path one body follows around another because of gravity: the Moon around Earth, Earth around the Sun. Almost all are ellipses, slightly flattened ovals.
  • Euler's method The simplest way to simulate a motion: advance in small time steps assuming the velocity does not change during each step. With small steps it works, but the error builds up.
  • Perihelion The point of the orbit closest to the Sun; there the planet moves fastest. Earth passes through it in early January. For the Moon around Earth it is called perigee.
  • Symplectic integrator A numerical method designed so that, when simulating orbits over millions of years, energy neither leaks away nor builds up little by little. That is why it is used to study the stability of the Solar System.
  • Aphelion The point of the orbit farthest from the Sun; there the planet moves slowest. For the Moon around Earth it is called apogee.
  • Eccentricity A number between 0 and 1 that says how flattened an orbit is: 0 is a perfect circle, and the closer to 1, the more elongated. Earth's is 0.017, almost a circle; Halley's comet's, 0.97.
  • Two-body problem Working out how two bodies move when they attract only each other, like the Sun and a planet. It has an exact solution: Kepler's ellipses. With three bodies there is no longer a closed formula.
  • Kepler's equation The equation that says where on its ellipse a planet is on a given date. It cannot be solved with algebra: it has to be solved by successive approximations, as astronomy programs do.
  • Apparent magnitude A number that says how bright a star looks from Earth. The smaller it is, the brighter the star: Sirius has −1.5, and the faintest stars you can see with the naked eye, 6.
  • Derivative How fast something changes at an instant: the derivative of position is velocity, and the derivative of velocity is acceleration. It is the slope of the graph at each point.
  • Deterministic chaos Motion that follows exact rules but is impossible to predict in the long run, because a tiny change at the start produces completely different results. The orbits of the planets are chaotic on scales of millions of years.

See the whole glossary →

References

  • Hairer, E., Nørsett, S. P. & Wanner, G. (1993). Solving Ordinary Differential Equations I: Nonstiff Problems, 2nd ed. Springer. §II.1 (Runge–Kutta), §II.3 (global error), §II.4 (error estimation and step control), §II.5 (Dormand–Prince).
  • Press, W. H., Teukolsky, S. A., Vetterling, W. T. & Flannery, B. P. (2007). Numerical Recipes, 3rd ed. Cambridge University Press. §17.1 (Runge–Kutta) and §17.2 (adaptive step, Dormand–Prince).
  • Fehlberg, E. (1969). Low-order classical Runge–Kutta formulas with stepsize control and their application to some heat transfer problems. NASA Technical Report R-315.
  • Dormand, J. R. & Prince, P. J. (1980). A family of embedded Runge–Kutta formulae. Journal of Computational and Applied Mathematics 6, 19–26. doi:10.1016/0771-050X(80)90013-3
  • Hairer, E., Lubich, C. & Wanner, G. (2006). Geometric Numerical Integration, 2nd ed. Springer. §VIII.2 (variable step and symplecticity).
  • Murray, C. D. & Dermott, S. F. (1999). Solar System Dynamics. Cambridge University Press. Ch. 2 (two-body problem).

Simulators for this lesson: N bodies: integrators and chaos