Fundamentals / Numerical mathematics / Numerical ordinary differential equations

Runge–Kutta stages and order

Construct a two-stage second-order integrator from Taylor conditions and calculate how different stage choices affect autonomous and time-dependent problems.

From first principles

Choose a second slope so that the curvature term is correct

A rate at the start of a step gives a tangent. To see what a single tangent misses, differentiate \(y'=f(t,y)\) along the solution. Time changes the slope directly and the moving state changes it through the Jacobian \(f_y\). For a smooth right-hand side the exact increment begins

\[y(t+h)-y(t)=hf+\frac{h^2}{2}(f_t+f_y f)+O(h^3).\]

Construct a second slope at a fraction \(c\) of the interval. The exact intermediate state is unknown, so predict it with the first slope \(k_1=f(t,y)\). Expand the new evaluation:

\[k_2=f(t+ch,y+ch k_1)=f+ch(f_t+f_y f)+O(h^2).\]

Take a weighted average of both slopes,

\[y_{n+1}=y_n+h(b_1 k_1+b_2 k_2).\]

Matching the exact coefficients of \(h\) and \(h^2\) imposes two conditions:

\[b_1+b_2=1,\]
\[b_2c=\tfrac12 .\]

Choose \(c=1/2\) and the first slope guides the midpoint location while the second supplies the whole update. Choose \(c=1\) and the two slopes receive equal weights. Both constructions have local defect \(O(h^3)\); they can disagree at the next order because slope matching has imposed no condition on cubic terms.

Derivation and applications

Why two second-order Runge–Kutta formulas diverge on a nonlinear system

A linear decay test cannot distinguish every pair of Runge–Kutta methods. Compare a family of explicit two-stage schemes on a smooth autonomous scalar equation \(y'=f(y)\). Starting from the same \(y\), choose a nonzero stage location \(a\), compute \(k_1=f(y)\) and \(k_2=f(y+ahk_1)\), and update with weights \(b_1,b_2\). Expand the internal slope at the unperturbed state:

\[k_2=f+ah f'f+\tfrac12a^2h^2 f''f^2+O(h^3).\]

Insert this expansion into \(y_+=y+h(b_1k_1+b_2k_2)\). Matching the coefficients of \(h\) and \(h^2\) with the exact Taylor series requires \(b_1+b_2=1\) and \(ab_2=1/2\). The update for every such method then reads

\[y_+=y+hf+\tfrac12h^2f'f+\tfrac14ah^3f''f^2+O(h^4).\]

Differentiate the differential equation twice to obtain the exact cubic term. This isolates two distinct effects of nonlinearity and slope propagation:

\[y'''=f''f^2+(f')^2 f,\]
\[y(t+h)=y+hf+\tfrac12h^2f'f+\tfrac16h^3[f''f^2+(f')^2f]+O(h^4).\]

Changing \(a\) can adjust the coefficient of \(f''f^2\). No choice supplies the missing \((f')^2f\) term for arbitrary \(f\), explaining why a third independent stage is needed for a general third-order explicit method. When \(f\) is linear, \(f''=0\), so this two-stage family gives the same output regardless of \(a\).

Worked example

Compare one nonlinear growth step

For \(y'=y^2\), \(y(0)=1\) and \(h=0.100\), explicit midpoint uses \(a=1/2\) and \(y_+=1+0.1(1.05)^2=1.11025\). Heun uses \(a=1\), averages \(1\) and \((1.10)^2\), and gives \(1.11050\). The exact solution \(1/(1-t)\) yields \(1.11111\). Both underpredict; Heun happens to be closer on this step. That comparison alone does not establish a generally higher order.

Second application

Construct a test unable to separate the methods

With \(y'=-2y\), \(y(0)=3\) and \(h=0.100\), every second-order member has amplification \(1+z+z^2/2\) at \(z=-0.200\). The output is \(3(0.820)=2.46\). The exact result is

\[3e^{-0.2}=2.45619.\]

Matching between midpoint and Heun in this test checks their shared polynomial but cannot test the implementation of their nonlinear stage terms.

OneSimulation laboratory

Compare time-step error with conservation

Start from this chapter. Halve the step at the same final time. Use the fourth-order Runge–Kutta prediction for the error ratio and compare it with the maximum error over the whole trajectory.

Compare recorded OneSimulation runs on this page. To test your own inputs, download the Python model and run the model in an activated OneSimulation environment.

Run the isothermal reaction from \(A=1,\ B=0\) mol/m³ to \(t=5/k=6.25\) s. Measure the maximum A error over all stored times and the drift of \(A+B\). First double the number of RK4 steps. Then restore 100 steps and change the time integrator. Download the Python experiment · OneSimulation first-order decay model.

python ordinary-differential-equations.py
python ordinary-differential-equations.py --steps 200
python ordinary-differential-equations.py --method euler
Errors in species A and in the conserved sum over five decay times.
Method, stepsFinal A (mol/m³)Max. A error (mol/m³)Max. drift (mol/m³)
RK4, 1000.006737948832.00 × 10⁻⁸4.44 × 10⁻¹⁶
RK4, 2000.006737947111.22 × 10⁻⁹3.33 × 10⁻¹⁶
Euler, 1000.005920529229.39 × 10⁻³4.44 × 10⁻¹⁶
Halving the RK4 step reduces the largest concentration error by about sixteen. The logarithmic axis also shows the much larger Euler error at 100 steps.
Halving the RK4 step reduces the largest concentration error by about sixteen. The logarithmic axis also shows the much larger Euler error at 100 steps.

As a fourth run, try --method euler --steps 5. This lands exactly on the nonnegativity limit. Predict both the final concentration and the largest error before running it.

Change parameters · Change the laboratory inputs

Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.

Problem sheet 1 · Predict when a conservative calculation loses all reactant

Read the model setup and preparatory problems

Reproduce a four-stage time integration in OneSimulation

Release a 1 kg mass from 10 mm at rest on a 4 N/m spring. Introduce damping \(c=2\zeta\sqrt{km}\). With \(v=\dot x\) one step must advance the coupled vector \((x,v)\). Each Runge–Kutta stage evaluates both \(v\) and \(-4x-4\zeta v\) at the same intermediate state. Using a new velocity with an old displacement changes the method. Predict whether a displacement zero crossing is possible for \(\zeta=0.5,1,2\).

The plot integrates six seconds with a step of 0.01 s. Its independent reference comes from the roots of \(s^2+4\zeta s+4=0\). At the repeated root \(\zeta=1\), use \(x=10(1+2t)e^{-2t}\) mm. Take the same damping into the downloadable OneSimulation release model and compare individual CSV rows. If you modify its time step, compare the largest error on shared output times and check the fourth-order ratio while the error remains above roundoff.

Sample slopes without solving a new differential equation

Euler uses a single slope at the start of a step. If the direction changes significantly over the interval, a second evaluation at a predicted point can estimate that change. Consider \(k_1=f(t,y)\), \(k_2=f(t+ch,y+ahk_1)\) and \(y_{new}=y+h(b_1k_1+b_2k_2)\). The time and state arguments of a stage must both be specified. In a forced system, evaluating a source at the old time while using a midpoint state can remove the expected order.

Expand around the start of the step. The second stage is \(f+h(cf_t+af_y f)+O(h^2)\). The exact trajectory has \(y(t+h)=y+hf+h^2(f_t+f_y f)/2+O(h^3)\). Comparing coefficients gives

\[b_1+b_2=1,\ b_2c=1/2,\ b_2a=1/2.\]

For the usual internally consistent stages \(a=c\). The explicit midpoint rule takes \(a=c=1/2,\ b_2=1\); the explicit trapezoidal or Heun rule takes \(a=c=1,\ b_1=b_2=1/2\). Both have order two globally under regularity and stable error propagation.

Compute two different approximations of equal order

For \(y'=y^2,\ y(0)=1\), use \(h=0.1\). The exact solution \(1/(1-t)\) gives 1.111111 at \(t=0.1\). Explicit midpoint predicts a midpoint value 1.05, evaluates slope \(1.05^2=1.1025\) there and returns \(1+0.1(1.1025)=1.11025\). Heun predicts an endpoint value 1.1, averages endpoint and initial slopes to obtain 1.105 and returns 1.11050. Both improve on Euler’s 1.1. Equal formal order allows different error constants, even for the same step size.

The exact solution develops a pole at \(t=1\). Approaching that time its derivatives grow and a step that was satisfactory at the start can perform poorly. This illustrates the dependence of all Taylor estimates on bounds over the interval of interest. A finite numerical value beyond the exact blow-up time is not automatically a valid continuation of the continuous solution. The physical or mathematical existence interval is part of any convergence claim.

Check what a higher-order stage sequence buys

Classical RK4 evaluates one initial slope, two midpoint slopes based on successive predictions and one endpoint slope. It averages them with weights \(1,2,2,1\) divided by six. For a constant linear scalar mode \(y'=\lambda y\), substitution gives

\[R(z)=1+z+z^2/2+z^3/6+z^4/24,\]
\[z=h\lambda.\]

Its first missing exponential term has degree five. This test explains fourth order on that mode. General nonlinear fourth order requires additional stage conditions because derivatives such as \(f_{yy}(f,f)\) and \(f_y f_y f\) are independent.

Take \(\lambda=-1,\ h=1\) and \(y_0=1\). The four slopes are \(-1,-0.5,-0.75,-0.25\), yielding \(y_1=0.375\) against \(e^{-1}=0.36788\). The two-stage midpoint rule gives 0.5 at the same endpoint. Cost matters: a comparison at equal steps lets RK4 use twice as many right-hand-side evaluations as a two-stage scheme. At equal evaluation budgets one can instead compare one RK4 step with two midpoint steps. Over a complex trajectory it is the measured work for an agreed error tolerance that answers which method is economical.

OneSimulation · Measure numerical damping in a lossless oscillator

An undamped 1 kg oscillator has angular frequency 2 rad/s. The initial displacement is 1 m and the initial velocity is zero, giving constant energy 2 J. In energy-scaled coordinates the exact motion is a rotation. A classical RK4 step multiplies the two complex modes by \(R(\pm i z)\), with \(z=\omega h\). Consequently one step changes the energy by the exact factor

\[\frac{E_{j+1}}{E_j}=|R(iz)|^2=1-\frac{z^6}{72}+\frac{z^8}{576}.\]

OneSimulation advances the original position–velocity equations. For each step size the code checks the computed energy at 20 s against the factor raised to the number of steps. The accumulated losses are 15.44%, 0.556% and 0.0177% as the step is halved twice. For fixed final time and small \(h\), the number of steps grows like \(1/h\), so the leading energy loss is proportional to \(h^5\). This diagnostic has its own convergence rate even though the method is fourth order in the state.

"""Measure artificial energy loss over 20 seconds in an undamped oscillator."""
import matplotlib.pyplot as plt
import numpy as np
from onesim.numerics.time import ClassicalRungeKutta4TimeIntegrator

omega = 2.0  # rad/s
mass = 1.0  # kg
duration = 20.0  # s
method = ClassicalRungeKutta4TimeIntegrator()

def dynamics(state, time):
    position, velocity = state
    return (velocity, -omega**2 * position)

fig, ax = plt.subplots(figsize=(6.8, 3.8), constrained_layout=True)
losses = []
for n, colour in [(50, "#a4492b"), (100, "#176879"), (200, "#3868a0")]:
    h = duration / n
    state = (1.0, 0.0)  # metres, metres per second
    energies = []
    for j in range(n + 1):
        x, v = state
        energies.append(0.5 * mass * (v*v + omega**2*x*x))
        if j < n:
            state = method.advance(state, dynamics, h, time=j*h)
    fraction = np.array(energies) / energies[0]
    z = omega*h
    assert np.isclose(fraction[-1], (1 - z**6/72 + z**8/576)**n)
    losses.append(1 - fraction[-1])
    ax.plot(np.arange(n + 1)*h, 100*(1 - fraction), color=colour, label=f"h = {h:g} s")
print("Final percentage losses:", np.round(100*np.array(losses), 5))
ax.set(xlabel="Time (s)", ylabel="Artificial energy loss (%)")
ax.legend()
ax.grid(alpha=0.2)
fig.savefig("ordinary-differential-equations.png", dpi=160)
Cumulative artificial energy loss over 20 seconds is largest for 0.4 second steps and nearly zero for the smallest step.
Energy decreases most with 0.4 s steps. The exact loss is zero at every time; the curves therefore measure damping introduced entirely by the discrete update.

Download the Python example

Check a linear invariant at the internal stages

Suppose \(y=(A,B)\) and the right-hand side obeys \(f_A+f_B=0\) at every admissible state. At any explicitly constructed stage the vector of slopes still has zero component sum. In the Runge–Kutta update \(y_{n+1}=y_n+h\sum_j b_j k_j\), the sum of the increments therefore vanishes for any weights. Every method of this form preserves the linear invariant \(A+B\) in exact arithmetic, regardless of its order.

A protection against negative concentrations is a different requirement. With \(A'=-kA\) and \(kh=3\), explicit midpoint forms the internal value \(A_{\rm mid}=A_n(1-3/2)=-0.5A_n\) even though the final polynomial \(1-3+9/2\) is positive. A nonlinear rate law involving a logarithm of concentration would be undefined at this intermediate evaluation. Checking final stored states alone misses the problem. This is why a useful stage test examines both admissibility of intermediate evaluations and the conservation of the accepted update.

Compare work at a fixed endpoint

Comparing two Runge–Kutta schemes on the same step size need not compare the same computational budget. Record the number of right-hand-side evaluations and the actual endpoint error. When evaluating the model dominates all other costs, four one-stage steps and one four-stage step cost roughly the same, yet respond quite differently to curvature of the solution. Some implementations reuse a stage across accepted steps; count evaluations actually made.

Derive implicit stages from polynomial collocation

Let \(U(\theta)\) denote a polynomial approximation to \(y(t_n+h\theta)\) on one time slab, with \(U(0)=y_n\). At \(s\) distinct nodes \(c_i\), require

\[U'(c_i)=h f(t_n+hc_i,U(c_i))=hK_i.\]

A polynomial \(U\) of degree at most \(s\) has a derivative determined by those \(s\) values. With cardinal polynomials \(\ell_j\) through the nodes, integration gives

\[U(\theta)=y_n+h\sum_j K_j\int_0^\theta\ell_j(r)\,dr.\]

Evaluating at the nodes and at the endpoint turns a polynomial matching problem into a Runge–Kutta scheme:

\[a_{ij}=\int_0^{c_i}\ell_j(r)\,dr,\]
\[b_j=\int_0^1\ell_j(r)\,dr,\]
\[K_i=f(t_n+hc_i,y_n+h\sum_j a_{ij}K_j).\]

The stage values generally depend on one another and must be solved simultaneously. With the single midpoint node this gives the implicit midpoint step, since \(\ell_1=1\), \(a_{11}=1/2\) and \(b_1=1\). With two Gaussian nodes \(c_{1,2}=1/2\mp\sqrt3/6\), integrating their linear cardinal functions gives weights \(1/2,1/2\), diagonal entries \(1/4\), and off-diagonal entries \(1/4-\sqrt3/6,\ 1/4+\sqrt3/6\) in row order.

For \(y'=\lambda y\), write \(z=h\lambda\) and \(Y={\bf1}y_n+z A Y\) for the stage states. Solving this two-by-two system and substituting in \(y_{n+1}=y_n+z(Y_1+Y_2)/2\) gives amplification \((1+z/2+z^2/12)/(1-z/2+z^2/12)\). For \(y_0=1,\lambda=-3,h=1\), the result is \(1/13\approx0.07692\), against \(e^{-3}\approx0.04979\). The endpoint formula is fourth order as \(h\to0\). For arbitrarily large negative \(z\) this ratio tends to one. Accurate integration of smooth resolved trajectories and rapid removal of unresolved stiff modes remain distinct design goals.

Practise on sheet 1 · Measure a collocation curve between its Gaussian nodes. Further reading · ETH Zürich · Numerical Methods for Ordinary Differential Equations · §4.4.1.1 Collocation methods, pp. 53–54.

Match the two independent third-order terms

For an autonomous smooth vector field write \(J=f_y\) and \(f''\) for its second derivative. Differentiating \(y'=f(y)\) twice gives \(y''=Jf\) and \(y'''=f''(f,f)+J(Jf)\). A third-order step has to reproduce both distinct vector expressions. For Runge–Kutta stages \(k_i=f(y+h\sum_j a_{ij}k_j)\), put \(c_i=\sum_j a_{ij}\). Stage expansion gives

\[k_i=f+h c_iJf+h^2[\sum_j a_{ij}c_j J(Jf)+(c_i^2/2) f''(f,f)]+O(h^3).\]

Multiplying by the output weights \(hb_i\) and comparing independent Taylor terms gives the conditions.

Besides \(\sum b_i=1\) and \(\sum b_ic_i=1/2\), they are \(\sum b_i c_i^2=1/3\) and \(\sum_{ij}b_i a_{ij}c_j=1/6\). The first additional condition concerns curvature of the vector field along a displacement; the second concerns propagation of one derivative through another stage. A single test equation with linear \(f\) makes the curvature term vanish, so matching an exponential stability polynomial cannot alone certify third order on general nonlinear systems. Smoothness over the region visited by all stages underlies the Taylor argument.

Verify a three-stage method on nonlinear growth

Use the stages \(k_1=f(y)\), \(k_2=f(y+hk_1/2)\), \(k_3=f(y-hk_1+2hk_2)\) and output \(y+h(k_1+4k_2+k_3)/6\). The stage abscissae are \(0,1/2,1\). The squared-abscissa sum is

\[(4/6)(1/4)+(1/6)=1/3.\]

For the nested derivative only the third stage contributes:

\[b_3 a_{32}c_2=(1/6)(2)(1/2)=1/6.\]

The two lower-order conditions are checked by summing the weights and their first moments. Together these calculations show why the intermediate stages are arranged this way.

Take \(y'=y^2,\ y(0)=1,\ h=0.1\). The exact value is

\[1/(1-h)=1.111111\ldots.\]

The stages are

\[k_1=1,\ k_2=1.05^2=1.1025,\]
\[k_3=(1-0.1+0.2\cdot1.1025)^2=1.1205^2=1.25552025.\]

Their weighted combination gives

\[y_1=1+0.1(1+4.41+1.25552025)/6\approx1.11109200.\]

The local error is about \(-1.91\times10^{-5}\), small despite appreciable curvature in the vector field. The stages themselves are sampling states for evaluating slopes; their individual values are not third-order predictions at those times.

Near \(t=1\) the exact solution becomes unbounded, and the derivatives used to bound the truncation error grow sharply. A method's algebraic order is a local smoothness statement, not a promise that a fixed step will remain accurate up to a singularity. Comparing errors at successively refined fixed observation times below the singularity tests the claimed order under the assumptions actually used in the derivation.

There is a quick nonlinear comparison showing why the two third-order conditions are genuinely needed. For a constant matrix equation the term \(f''(f,f)\) vanishes identically, so only the nested derivative contributes at cubic order. For a scalar quadratic field, both terms are generally nonzero. The exact-series test in the worked example can thus reveal defects that would escape every linear growth or decay test using the same code. One can isolate the curvature term more sharply by placing the initial state at a point where \(J=0\) but \(f\ne0\) and \(f''\ne0\), for example \(y'=1+y^2\) at \(y=0\). Its solution begins \(y=t+t^3/3+\cdots\), providing an independent check purely on the squared-abscissa moment.

In fact \(y=\tan t\) in this test, and the coefficient of its cubic term can be measured directly without numerical reference integration.

Measure fourth order against a conserved decay

The OneSimulation run transfers A into B at rate 0.8 per second. Start with one mole of A per cubic metre and no B. Compare the recorded A values at every time node with the exponential solution. Both integrators conserve the total A+B, so a total-mass test alone cannot distinguish their time accuracy.

Measure fourth order against a conserved decay. Horizontal axis: Equal time steps across five decay times. Vertical axis: Maximum nodal concentration error (mol/m³). Data follow the figure.
Doubling the number of steps reduces the fine-grid Euler error by about two and the RK4 error by about sixteen. Read the last two points to estimate the order yourself. Each RK4 step evaluates four slopes, so compare 40 Euler steps with 10 RK4 steps when counting right-hand-side evaluations.
Read values from the plot
Maximum nodal concentration error (mol/m³) at selected values of Equal time steps across five decay times.
Equal time steps across five decay timesEULERRK4
100.117880.0002914
200.0514731.4758e−5
400.0242718.3075e−7
1600.00582423.0008e−9
3200.00289291.8512e−10

Download all 6 plotted samples (CSV)

Download the OneSimulation model (Python)

Change parameters · Measure fourth order against a conserved decay

Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.

Study the full derivation

Find a crossing between accepted time steps · Dynamics and numerical time integration

An integrator can approximate a trajectory accurately yet report a poor switch time. Construct a continuous interpolant, relate a state error to an event-time error and inspect what happens when a trajectory merely touches a threshold.