Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Runge-Kutta methods

ProblemSolve the initial value problem , , for a system of ordinary differential equations
Devised byLeonhard Euler (1768); Carl Runge (1895), Karl Heun (1900) and Martin Kutta (1901); order theory by John Butcher (1963); embedded pairs by Erwin Fehlberg (1969); the 5(4) pair by John Dormand and Peter Prince (1980)
AccuracyRK4: global error . Dormand-Prince: local error per step kept below the tolerance by adapting
CostRK4: 4 evaluations of per step. Dormand-Prince: 6 per step (7 stages, one reused)
Read firstPreliminaries: floating-point arithmetic
APIrk4_solve, dormand_prince_solve, OdeOptions, OdeSolution

Overview

A differential equation tells us the direction in which the solution moves at every point. Integrating it numerically means following those directions in steps of size . The simplest method, Euler’s, takes one direction per step and follows it in a straight line; its error is proportional to , so it needs very many steps.

Runge-Kutta methods sample the direction field several times within each step, at carefully chosen trial points, and combine the samples so that the step agrees with the true solution’s Taylor series to high order. The classical fourth-order method (RK4) uses four samples and has global error . Embedded pairs such as Dormand-Prince 5(4) compute two solutions of different orders from the same samples; their difference estimates the error, and the step size is adapted so that each step is just accurate enough. Dormand-Prince is the default non-stiff solver in MATLAB (ode45), SciPy (RK45) and Julia, and the method to try first for most initial value problems.

Where it is used

Runge-Kutta methods solve most initial value problems that arise in simulation.

  • Mechanics and robotics. Motion of satellites, pendulums, vehicles and multibody systems.
  • Circuits and control. Simulating a plant and controller together before building them.
  • Epidemiology and ecology. Compartment models (SIR) and predator-prey dynamics.
  • Everywhere else. ode45 in MATLAB and solve_ivp in SciPy default to Dormand-Prince Runge-Kutta pairs with step-size control.

History

Leonhard Euler described the method of following tangent lines in his Institutionum calculi integralis (1768). For more than a century it was the only general numerical method for differential equations, used alongside series expansions.

In 1895 the German mathematician Carl Runge, studying the solution of equations by hand computation, observed that one could gain accuracy by evaluating the slope at intermediate points, in the spirit of the midpoint and Simpson rules for integrals. Karl Heun (1900) extended the idea, and in 1901 Martin Kutta systematically derived methods of order up to five, including the classical fourth-order method still taught today. Kutta also studied the “3/8 rule” variant, the analogue of Simpson’s three-eighths rule.

The theory remained ad hoc until John Butcher (1963) showed that the conditions a method must satisfy to reach a given order correspond to rooted trees, which made it possible to construct methods of high order systematically and gave us the Butcher tableau notation. Error control arrived with Erwin Fehlberg’s embedded pairs (1969), which estimate the error almost for free. John Dormand and Peter Prince (1980) improved on Fehlberg by optimising the error of the higher-order solution, which is the one actually used, and their 5(4) pair became the standard.

The idea

Euler’s method and the order of a method

Euler’s method is . By Taylor’s theorem the exact solution satisfies , so each step makes a local error of . Covering an interval of length takes steps, and the errors accumulate to a global error of . A method with local error has order and global error .

One could reach higher order by including more Taylor terms, and so on, but involves derivatives of that are tedious or impossible to supply. Runge-Kutta methods match the same Taylor terms using only values of .

Stages and the Butcher tableau

An -stage explicit Runge-Kutta method computes

Each stage is a slope evaluated at a trial point built from the earlier stages. The coefficients are written in a Butcher tableau; for the classical RK4 method

that is: a slope at the start, two at the midpoint (the second using the first midpoint slope), and one at the end, averaged with weights . When does not depend on , the two midpoint slopes coincide and the step is exactly Simpson’s rule.

Order conditions

Expanding and the exact in powers of and matching terms gives polynomial equations for the coefficients. For order 1, ; order 2 adds ; order 3 adds and ; order 4 adds four more. Butcher’s insight was that there is one condition for each rooted tree with up to nodes, each tree describing one of the ways derivatives of combine in the Taylor expansion. The number of conditions grows quickly (8 for order 4, 17 for order 5, 37 for order 6), and with it the minimum number of stages: order 4 needs 4 stages, but order 5 needs 6, which is why fourth order was the classical sweet spot.

Error estimation with embedded pairs

The local error of a step is unknown, but it can be estimated by taking the same step with two methods of different orders. An embedded pair shares all its stages and differs only in the weights: of order 5 and of order 4. Their difference is dominated by the error of the lower-order solution and costs nothing extra. Dormand and Prince chose their coefficients to make the fifth-order solution as accurate as possible, and the method continues with it (local extrapolation).

Their pair has seven stages, but the seventh is evaluated at the new solution , so it is also the first stage of the next step. With this first same as last property each step costs six evaluations.

/// The nodes `c`, coefficients `a` and fifth-order weights (last row of `a`) of the
/// Dormand-Prince 5(4) pair. The seventh stage is evaluated at the new solution, so it is the
/// first stage of the next step ("first same as last").
const C: [f64; 7] = [0.0, 0.2, 0.3, 0.8, 8.0 / 9.0, 1.0, 1.0];
const A: [[f64; 6]; 7] = [
    [0.0; 6],
    [0.2, 0.0, 0.0, 0.0, 0.0, 0.0],
    [3.0 / 40.0, 9.0 / 40.0, 0.0, 0.0, 0.0, 0.0],
    [44.0 / 45.0, -56.0 / 15.0, 32.0 / 9.0, 0.0, 0.0, 0.0],
    [19372.0 / 6561.0, -25360.0 / 2187.0, 64448.0 / 6561.0, -212.0 / 729.0, 0.0, 0.0],
    [9017.0 / 3168.0, -355.0 / 33.0, 46732.0 / 5247.0, 49.0 / 176.0, -5103.0 / 18656.0, 0.0],
    [35.0 / 384.0, 0.0, 500.0 / 1113.0, 125.0 / 192.0, -2187.0 / 6784.0, 11.0 / 84.0],
];
/// Fifth-order weights minus the embedded fourth-order weights: `h Σ eⱼ kⱼ` estimates the
/// local error.
const E: [f64; 7] = [
    35.0 / 384.0 - 5179.0 / 57600.0,
    0.0,
    500.0 / 1113.0 - 7571.0 / 16695.0,
    125.0 / 192.0 - 393.0 / 640.0,
    -2187.0 / 6784.0 + 92097.0 / 339200.0,
    11.0 / 84.0 - 187.0 / 2100.0,
    -1.0 / 40.0,
];

Step-size control

Each component’s error is compared with its own tolerance, , and the worst ratio decides the step. If the step is accepted. Either way the next step size follows from the error model of the fourth-order solution:

limited to between a fifth and five times the old step. The safety factor 0.9 makes the next step likely to be accepted. Steps therefore shrink where the solution changes quickly and grow where it is smooth, without any input beyond the tolerances.

The Arenstorf orbit is the classic demonstration. A small satellite moves under the gravity of the Earth and the Moon, in a rotating frame in which both are fixed; Richard Arenstorf found this periodic orbit in 1963 while working on the trajectories of the Apollo programme. Near the Moon the satellite moves fast and its path curves sharply, and the accepted steps crowd together there:

Figure 2.19. The Arenstorf orbit.

A fixed step small enough for the close approach is wasted on the rest of the orbit. Measured by the error after one period, adaptive Dormand-Prince is about a thousand times cheaper than RK4 with a fixed step:

Figure 2.20. Error after one period.

Stability and stiffness

Applied to the test equation , any explicit Runge-Kutta step multiplies the solution by a polynomial ; for RK4, . If is large and negative, the true solution decays, but the numerical one is bounded only when , which for RK4 requires . A system that combines a rapidly decaying component with slow ones is stiff: an explicit method must keep small enough for the fast component long after it has died away. The step-size controller then takes tiny steps and the solver crawls. Implicit methods, the subject of the next entry, remove this restriction.

Algorithm

RK4 with steps: ; for each step, evaluate the four stages and update .

Dormand-Prince:

  1. Choose a starting step from the sizes of and (Hairer’s heuristic).
  2. Repeat until :
    1. Shorten if it would pass . Evaluate stages 2 to 7 (stage 1 is the previous stage 7).
    2. Form and the error estimate , and its weighted maximum .
    3. If , accept the step; otherwise count a rejection.
    4. ; fail if underflows.

Implementation

The RK4 step:

        let k1 = eval(t, &y)?;
        let k2 = eval(t + 0.5 * h, &axpy(&y, 0.5 * h, &k1))?;
        let k3 = eval(t + 0.5 * h, &axpy(&y, 0.5 * h, &k2))?;
        let k4 = eval(t + h, &axpy(&y, h, &k3))?;
        for i in 0..n {
            y[i] += h / 6.0 * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]);
        }

The adaptive Dormand-Prince step:

        h = h.min((t1 - t).abs());
        let hs = h * direction;
        k.truncate(1);
        for s in 1..7 {
            let stage: Vec<f64> = (0..n).map(|i| y[i] + hs * (0..s).map(|j| A[s][j] * k[j][i]).sum::<f64>()).collect();
            let t_stage = t + C[s] * hs;
            k.push(eval(t_stage, &stage)?);
        }
        solution.nfev += 6;
        // Stage 7 was evaluated at the fifth-order solution itself.
        let y_new: Vec<f64> = (0..n).map(|i| y[i] + hs * (0..6).map(|j| A[6][j] * k[j][i]).sum::<f64>()).collect();
        let local: Vec<f64> = (0..n).map(|i| hs * (0..7).map(|j| E[j] * k[j][i]).sum::<f64>()).collect();
        let error = weighted_max(&local, &y, &y_new, &options);
        if error <= 1.0 && y_new.iter().all(|v| v.is_finite()) {
            t = if (t1 - t).abs() <= h { t1 } else { t + hs };
            y = y_new;
            let last = k.pop().expect("seven stages");
            k = vec![last];
            solution.t.push(t);
            solution.y.push(y.clone());
        } else {
            solution.rejected_steps += 1;
        }
        let factor = if error.is_finite() { 0.9 * error.max(1e-10).powf(-0.2) } else { 0.1 };
        h *= factor.clamp(0.2, 5.0);
  • The state is a slice, so one routine handles scalar equations and systems alike. A higher-order equation such as is written as a first-order system for .
  • Integration may run backwards in time (); the step is applied with the sign of the span.
  • A non-finite trial solution is treated as a failed step, which shrinks ; if the step underflows, the solver reports an error (often a sign of stiffness or of a solution that blows up in finite time).
  • Version 2.0 removed the 1.x functions runge_kutta_4 and dormand_prince, which accepted only and so solved , which is quadrature rather than an ODE solver. Use rk4_solve and dormand_prince_solve.

In practice

The Lotka-Volterra predator-prey equations conserve the quantity , so its drift measures the accumulated error:

//! Initial value problems with the classical Runge-Kutta method and adaptive Dormand-Prince.
//!
//! Run with `cargo run -p lib_jsl_integration --example ode_runge_kutta`.

use lib_jsl_integration::dormand_prince::dormand_prince_solve;
use lib_jsl_integration::runge_kutta_4::rk4_solve;
use lib_jsl_integration::stiff_ode::OdeOptions;

fn main() {
    // Lotka-Volterra predator-prey model: x' = x − xy, y' = −y + xy.
    let predator_prey = |_t: f64, y: &[f64]| vec![y[0] - y[0] * y[1], -y[1] + y[0] * y[1]];
    // The quantity V = x − ln x + y − ln y is conserved exactly; its drift measures the error.
    let invariant = |y: &[f64]| y[0] - y[0].ln() + y[1] - y[1].ln();
    let start = [2.0, 1.0];

    for steps in [100, 200, 400] {
        let s = rk4_solve(predator_prey, 0.0, &start, 20.0, steps).unwrap();
        let drift = (invariant(s.y.last().unwrap()) - invariant(&start)).abs();
        println!("RK4, {steps:3} steps: invariant drift {drift:.1e} ({} evaluations)", s.nfev);
    }
    for tol in [1e-6, 1e-9, 1e-12] {
        let options = OdeOptions { relative_tolerance: tol, absolute_tolerance: tol, ..Default::default() };
        let s = dormand_prince_solve(predator_prey, 0.0, &start, 20.0, options).unwrap();
        let drift = (invariant(s.y.last().unwrap()) - invariant(&start)).abs();
        println!(
            "Dormand-Prince, tolerance {tol:.0e}: drift {drift:.1e} ({} steps, {} rejected, {} evaluations)",
            s.t.len() - 1,
            s.rejected_steps,
            s.nfev
        );
    }
}

Strengths

  • Simple, self-starting (no history of previous steps is needed), and easy to apply to any system.
  • Dormand-Prince adapts the step automatically and estimates its error at no extra cost.
  • High accuracy per evaluation for smooth, non-stiff problems.

Weaknesses

  • Explicit methods are inefficient for stiff problems.
  • The tolerance controls the local error per step; the global error can be larger, and grows with the length of the integration, especially for unstable or chaotic systems.
  • Long integrations of conservative systems drift (the invariant above is not exactly conserved); symplectic methods are designed to avoid this.

Exercises

  1. Show that the RK4 tableau satisfies the four order conditions for order 3 listed above.
  2. Find all two-stage explicit methods of order 2 (a one-parameter family). Which member is the midpoint method, and which is Heun’s method?
  3. Solve , , on with Dormand-Prince. How many steps does it take, and how does the number change with the tolerance? Explain using the stability bound of the Dormand-Prince method.
  4. Apply RK4 to with step and show that with the degree-4 Taylor polynomial of .
  5. Integrate the Arenstorf orbit over ten periods at tolerances and . How far from periodic is each result, and why does the error grow so much faster than linearly with time?
Hints and answers
  1. For RK4, and . Then , , , and .
  2. The conditions are and with : , . The midpoint method is , Heun’s is .
  3. The solution is smooth after a fast transient, but explicit methods are limited by stability, not accuracy: , so at least about 300 steps whatever the tolerance. Tightening the tolerance changes the step count only when accuracy becomes the stricter requirement.
  4. : with the four stages are polynomials in that multiply out to the degree-4 Taylor polynomial.
  5. Errors in the orbit’s period make the phase drift: the position error grows roughly in proportion to time, and the close approaches to the Earth amplify small deviations, so the growth is faster than linear over ten periods.

Further reading

  • C. Runge, “Über die numerische Auflösung von Differentialgleichungen”, Mathematische Annalen 46 (1895) 167–178.
  • W. Kutta, “Beitrag zur näherungsweisen Integration totaler Differentialgleichungen”, Zeitschrift für Mathematik und Physik 46 (1901) 435–453.
  • J. C. Butcher, “Coefficients for the study of Runge-Kutta integration processes”, Journal of the Australian Mathematical Society 3 (1963) 185–201.
  • J. R. Dormand and P. J. Prince, “A family of embedded Runge-Kutta formulae”, Journal of Computational and Applied Mathematics 6 (1980) 19–26.
  • L. F. Shampine and M. W. Reichelt, “The MATLAB ODE suite”, SIAM Journal on Scientific Computing 18 (1997) 1–22.
  • E. Hairer, S. P. Nørsett and G. Wanner, Solving Ordinary Differential Equations I: Nonstiff Problems, 2nd ed., Springer, 1993. The standard reference, the source of the Arenstorf example and of the step-size heuristics used here.