Deriving Runge–Kutta methods from Euler’s method

Environment

Python 3.14.6, NumPy 2.5.4, SymPy 1.14.0, Matplotlib 3.11.2.

This article is a rewrite of a post from around 2013–2016, with calculations performed in the environment described above.

Overview

Starting from Euler’s method, we derive second-order methods and the classical fourth-order Runge–Kutta method by matching Taylor coefficients. Python examples compare solutions, errors, computational cost, and stability.

Setup

Run the code in Jupyter Notebook from top to bottom.

Imports and plotting setup
import platform
from pathlib import Path
from pprint import pprint

import numpy as np
import sympy as sp
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
from IPython.display import display
from matplotlib_inline.backend_inline import set_matplotlib_formats

%matplotlib inline
set_matplotlib_formats("svg")

print("Python:", platform.python_version())
for package in (np, sp, matplotlib):
    print(f"{package.__name__}: {package.__version__}")

# Prepare the figure output directory.
out = Path("105_nb_files")
out.mkdir(exist_ok=True)

def sig(value):
    return f"{value:#.3g}"

plt.rcParams.update({"figure.figsize": (7, 4), "font.size": 11})

def formula(tex):
    # Use the appropriate delimiters for LaTeX and HTML output.
    display({"text/latex": r"\(" + tex + r"\)",
             "text/html": "<div>$$" + tex + "$$</div>"}, raw=True)

def save(fig, name):
    for ax in fig.axes:
        ax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: sig(x)))
        ax.yaxis.set_major_formatter(FuncFormatter(lambda x, _: sig(x)))
        ax.minorticks_off()
        ax.grid(alpha=0.300)
        ax.legend()
    fig.tight_layout()
    fig.savefig(out / f"{name}.svg", format="svg")
    plt.show()
    plt.close(fig)
Python: 3.14.6
numpy: 2.5.4
sympy: 1.14.0
matplotlib: 3.11.2

1. Euler’s method approximates an integral with a rectangle

Consider the initial-value problem $y^{\prime}=f(t,y),\ y(t_0)=y_0$. Let the step size be $h\gt 0$, with $t_n=t_0+nh$ and $y_n\approx y(t_n)$. Assume $f$ is sufficiently smooth and locally Lipschitz continuous in $y$.

Integrating over one interval gives

$$ y(t_n+h)-y(t_n)=\int_{t_n}^{t_n+h}f(t,y(t))\,dt. $$

Replacing the slope by its left-endpoint value approximates the integral by $hf(t_n,y_n)$, giving the explicit Euler method.

formula(r"\boxed{y_{n+1}=y_n+hf(t_n,y_n)}")

$$ \boxed{y_{n+1}=y_n+hf(t_n,y_n)} $$

Below, evaluate $f$ and its partial derivatives at the starting point.

$$ \begin{aligned} y^{\prime\prime}&=\frac{d}{dt}f(t,y(t))=f_t+f_y y^{\prime}=f_t+f_yf,\\ y(t+h)&=y(t)+hf+\frac{h^2}{2}(f_t+f_yf)+O(h^3). \end{aligned} $$

Euler’s method omits the $h^2$ term. Define local error as the error from one numerical step starting at the exact value; it is $O(h^2)$. Under the conditions given later, the error over a fixed interval is $O(h)$.

2. Evaluating one more slope

Consider a two-stage formula. Each $k_i$ is a slope and does not include $h$.

$$ k_1=f(t_n,y_n),\quad k_2=f(t_n+ch,y_n+ahk_1),\quad y_{n+1}=y_n+h(b_1k_1+b_2k_2). $$

Taylor expansion gives

$$ \begin{aligned} k_2&=f+chf_t+ahff_y+O(h^2),\\ y_{n+1}&=y_n+h(b_1+b_2)f+h^2(b_2cf_t+b_2aff_y)+O(h^3). \end{aligned} $$

Matching the coefficients of $f,f_t,ff_y$ gives

$$ b_1+b_2=1,\quad b_2c=\frac12,\quad b_2a=\frac12. $$

Thus $c=a\ne0$, $b_2=1/(2a)$, and $b_1=1-1/(2a)$. Choosing $a=1/2$ gives the explicit midpoint method; choosing $a=1$ gives Heun’s method.

$$ \begin{aligned} \text{Midpoint: }&y_{n+1}=y_n+h f\left(t_n+\frac h2,y_n+\frac h2 f(t_n,y_n)\right),\\ \text{Heun: }&y_{n+1}=y_n+\frac h2\{f(t_n,y_n)+f(t_n+h,y_n+hf(t_n,y_n))\}. \end{aligned} $$

Both have local error $O(h^3)$. Figure 1 uses $y^{\prime}=-y,\ y(0)=1,\ h=0.800$. The midpoint state is predicted by Euler’s method. Evaluating the slope again at this predicted point is what distinguishes the midpoint method from Euler’s method.

h = 0.800
t = np.linspace(0, h, 100)
mid_y = 1 - h / 2
fig, ax = plt.subplots()
ax.plot(t, np.exp(-t), "k", label="Exact")
ax.plot([0, h], [1, 1 - h], "o--", label="Euler")
ax.plot([0, h], [1, 1 - h * mid_y], "o-", label="Midpoint update")
ax.scatter([h / 2], [mid_y], marker="s", label="Predicted midpoint")
dt = np.array([-1, 1]) * h / 5
ax.plot(h / 2 + dt, mid_y - mid_y * dt,
        ":", color="tab:green", label="Slope at midpoint")
ax.set(xlabel="$t$", ylabel="$y$", title="1. One step: h = 0.800")
save(fig, "01_one_step")

3. Finding the fourth-order Runge–Kutta coefficients

Expanding the four stage slopes

Choose a method that evaluates slopes at the start, midpoint, midpoint, and end. We determine the weights and check agreement through fourth order.

$$ \begin{aligned} k_1&=f(t,y),&k_2&=f(t+h/2,y+hk_1/2),\\ k_3&=f(t+h/2,y+hk_2/2),&k_4&=f(t+h,y+hk_3),\\ y_{n+1}&=y+h\sum_{i=1}^4b_i k_i.&& \end{aligned} $$

Abbreviate $t=t_n,y=y_n$ and define

$$ \begin{aligned} q&=f_y,& A&=f_t+qf,&D&=f_{ty}+f_{yy}f,\\ B&=f_{tt}+2f_{ty}f+f_{yy}f^2,\\ C&=f_{ttt}+3f_{tty}f+3f_{tyy}f^2+f_{yyy}f^3. \end{aligned} $$

Use the chain rule to find derivatives along the exact solution.

$$ \begin{aligned} \frac{dq}{dt}&=D,\\ \frac{dA}{dt}&=f_{tt}+f_{ty}f+(f_{yt}+f_{yy}f)f+qA=B+qA,\\ \frac{dB}{dt}&=f_{ttt}+f_{tty}f+2(f_{tty}+f_{tyy}f)f +2f_{ty}A+(f_{tyy}+f_{yyy}f)f^2+2f_{yy}fA\\ &=C+2DA,\\ y^{(4)}&=\frac{d}{dt}(B+qA)=C+2DA+DA+q(B+qA)\\ &=C+3DA+qB+q^2A. \end{aligned} $$

The exact solution therefore has the expansion

$$ y(t+h)=y+hf+\frac{h^2}{2}A+\frac{h^3}{6}(B+qA) +\frac{h^4}{24}(C+3DA+qB+q^2A)+O(h^5). $$

For each stage, use the following Taylor expansion in two variables.

$$ \begin{aligned} f(t+u,y+v)={}&f+uf_t+vf_y +\frac12(u^2f_{tt}+2uvf_{ty}+v^2f_{yy})\\ &+\frac16(u^3f_{ttt}+3u^2vf_{tty}+3uv^2f_{tyy}+v^3f_{yyy})+O(h^4), \end{aligned} $$

Assume $u,v=O(h)$. For $k_2$, use $(u,v)=(h/2,hf/2)$. For $k_3$ and $k_4$, use the following expressions.

$$ \begin{aligned} \frac h2 k_2&=\frac h2f+\frac{h^2}{4}A+\frac{h^3}{16}B+O(h^4),\\ hk_3&=hf+\frac{h^2}{2}A+h^3\left(\frac B8+\frac{qA}4\right)+O(h^4) \end{aligned} $$

Substitute these successively for $v$ and collect terms.

$$ \begin{aligned} k_1={}&f,\\ k_2={}&f+\frac h2A+\frac{h^2}{8}B+\frac{h^3}{48}C+O(h^4),\\ k_3={}&f+\frac h2A+h^2\left(\frac B8+\frac{qA}4\right) +h^3\left(\frac C{48}+\frac{DA}8+\frac{qB}{16}\right)+O(h^4),\\ k_4={}&f+hA+h^2\left(\frac B2+\frac{qA}2\right) +h^3\left(\frac C6+\frac{DA}2+\frac{qB}8+\frac{q^2A}4\right)+O(h^4). \end{aligned} $$

Determining the weights

Compare $y+h\sum b_i k_i$ with the exact solution. The coefficients of $hf,h^2A,h^3B,h^3qA$ give

$$ \sum b_i=1,\quad \frac{b_2+b_3}{2}+b_4=\frac12,\quad \frac{b_2+b_3}{8}+\frac{b_4}{2}=\frac16,\quad \frac{b_3}{4}+\frac{b_4}{2}=\frac16. $$

Multiply the third equation by four and subtract the second to obtain $b_4=2/3-1/2=1/6$. The second equation gives $b_2+b_3=2/3$, and the fourth gives $b_3=4(1/6-1/12)=1/3$. Thus $b_2=1/3$ and $b_1=1/6$.

Check the four remaining terms of order $h^4$.

$$ \begin{aligned} C:&\quad\frac{b_2+b_3}{48}+\frac{b_4}{6}=\frac1{72}+\frac1{36}=\frac1{24},\\ DA:&\quad\frac{b_3}{8}+\frac{b_4}{2}=\frac1{24}+\frac1{12}=\frac18,\\ qB:&\quad\frac{b_3}{16}+\frac{b_4}{8}=\frac1{48}+\frac1{48}=\frac1{24},\\ q^2A:&\quad\frac{b_4}{4}=\frac1{24}. \end{aligned} $$

All coefficients agree, so the local error is $O(h^5)$. This gives the classical fourth-order Runge–Kutta method, RK4. It is not the only fourth-order method.

formula(r"\boxed{y_{n+1}=y_n+\frac h6(k_1+2k_2+2k_3+k_4)}")

$$ \boxed{y_{n+1}=y_n+\frac h6(k_1+2k_2+2k_3+k_4)} $$

From local error to global error

Assume that the local error is bounded by $Kh^{p+1}$ and that the one-step map has Lipschitz constant $1+Lh$. With zero initial error, $L\gt 0$, and $Nh=T$,

$$ \begin{aligned} |e_{n+1}|&\le(1+Lh)|e_n|+Kh^{p+1},\\ |e_N|&\le Kh^{p+1}\sum_{j=0}^{N-1}(1+Lh)^j =\frac K L h^p\{(1+Lh)^N-1\}\\ &\le\frac K L(e^{LT}-1)h^p=O(h^p). \end{aligned} $$

Euler’s method is first order, midpoint and Heun are second order, and RK4 is fourth order. This estimate applies for sufficiently small steps over a fixed interval on which the solution exists.

4. Comparing solutions and errors in Python

Implement one step and repeated integration. Here $n$ is the number of steps.

def step(f, t, y, h, name):
    k1 = f(t, y)
    if name == "Euler":
        return y + h * k1
    if name == "Heun":
        k2 = f(t + h, y + h * k1)
        return y + h * (k1 + k2) / 2
    k2 = f(t + h / 2, y + h * k1 / 2)
    if name == "Midpoint":
        return y + h * k2
    if name != "RK4":
        raise ValueError(name)
    k3 = f(t + h / 2, y + h * k2 / 2)
    k4 = f(t + h, y + h * k3)
    return y + h * (k1 + 2 * k2 + 2 * k3 + k4) / 6


def solve(f, end, y0, n, name):
    h = end / n
    t = np.linspace(0, end, n + 1)
    y = np.empty(n + 1)
    y[0] = y0
    for i in range(n):
        y[i + 1] = step(f, t[i], y[i], h, name)
    return t, y


# The stage count equals the function evaluation count per step.
stages = {"Euler": 1, "Midpoint": 2, "Heun": 2, "RK4": 4}

Separate variables in the nonlinear example $y^{\prime}=(1+2t)y(1-y),\ y(0)=1/4$.

$$ \frac{dy}{y(1-y)}=(1+2t)dt,\quad \log\frac{y}{1-y}=t+t^2-\log3,\quad y(t)=\frac1{1+3e^{-t-t^2}}. $$

Figure 2 shows the solutions and Figure 3 the absolute errors. The initial point has zero error and is omitted from the logarithmic axis.

def rhs(t, y):
    return (1 + 2 * t) * y * (1 - y)


def exact(t):
    return 1 / (1 + 3 * np.exp(-t - t**2))


solutions = {m: solve(rhs, 2, 1 / 4, 10, m) for m in stages}
fig, ax = plt.subplots()
dense = np.linspace(0, 2, 400)
ax.plot(dense, exact(dense), "k--", label="Exact")
for name, (t, y) in solutions.items():
    ax.plot(t, y, ".-", label=name)
ax.set(xlabel="$t$", ylabel="$y$", title="2. Solutions: h = 0.200")
save(fig, "02_solutions")

fig, ax = plt.subplots()
for name, (t, y) in solutions.items():
    error = np.abs(y - exact(t))
    ax.semilogy(t[1:], error[1:], ".-", label=name)
ax.set(xlabel="$t$", ylabel="Absolute error", title="3. Error in time")
save(fig, "03_errors")
pprint({m: sig(np.max(np.abs(y - exact(t))))
        for m, (t, y) in solutions.items()})
{'Euler': '0.0507', 'Heun': '0.0102', 'Midpoint': '0.00477', 'RK4': '0.000230'}

Step size and function evaluation counts

On $[0,1]$, compute $E(h)=\max_n|y_n-y(t_n)|$. If $E(h)\approx Ch^p$, then

$$ \frac{E(h)}{E(h/2)}\approx2^p,\qquad p_{\mathrm{obs}}=\frac{\log(E(h)/E(h/2))}{\log2}. $$

Figure 4 checks the order, and Figure 5 compares error with function evaluation count. At the same step size, RK4 uses four times as many evaluations as Euler’s method.

counts = np.array([5, 10, 20, 40, 80])
hs = 1 / counts
errors = {}
for name in stages:
    values = []
    for n in counts:
        t, y = solve(rhs, 1, 1 / 4, int(n), name)
        values.append(np.max(np.abs(y - exact(t))))
    errors[name] = np.array(values)

for cost in (False, True):
    fig, ax = plt.subplots()
    for name, error in errors.items():
        x = counts * stages[name] if cost else hs
        ax.loglog(x, error, "o-", label=name)
    ax.set(xlabel="Function evaluations" if cost else "$h$",
           ylabel="Maximum error",
           title="5. Cost and error" if cost else "4. Convergence")
    if not cost:
        ax.set_xticks(hs)
    save(fig, "05_cost" if cost else "04_convergence")

# Observed order from the last two points.
pprint({m: sig(np.log2(e[-2] / e[-1])) for m, e in errors.items()})
{'Euler': '1.01', 'Heun': '1.99', 'Midpoint': '1.99', 'RK4': '4.00'}

5. Higher order still has step size limits

Apply the methods to $y^{\prime}=\lambda y$ and set $z=h\lambda$. The update becomes $y_{n+1}=R(z)y_n$. Euler has $R(z)=1+z$, and midpoint has $1+z(1+z/2)=1+z+z^2/2$. Set $y_n=1,h=1,\lambda=z$ to compute each amplification factor symbolically.

z = sp.symbols("z")
poly = {}
for name in stages:
    r = sp.expand(step(lambda t, y: z * y, 0, sp.Integer(1), 1, name))
    poly[name] = r
    formula(r"R_{\mathrm{" + name + r"}}(z)=" + sp.latex(r))

grid = np.linspace(-3, 0, 500)
fig, ax = plt.subplots()
for name in ("Euler", "Midpoint", "RK4"):
    r = sp.lambdify(z, poly[name], "numpy")
    ax.plot(grid, np.abs(r(grid)), label=name)
ax.axhline(1, color="black", linestyle="--", label="$|R|=1$")
ax.set(xlabel="$z=h\\lambda$", ylabel="$|R(z)|$", ylim=(0, 3),
       title="6. Stability on the negative real axis")
save(fig, "06_stability")

$$ R_{\mathrm{Euler}}(z)=z + 1 $$

$$ R_{\mathrm{Midpoint}}(z)=\frac{z^{2}}{2} + z + 1 $$

$$ R_{\mathrm{Heun}}(z)=\frac{z^{2}}{2} + z + 1 $$

$$ R_{\mathrm{RK4}}(z)=\frac{z^{4}}{24} + \frac{z^{3}}{6} + \frac{z^{2}}{2} + z + 1 $$

In Figure 6, perturbations do not grow where $|R(z)|\le1$. For real $\lambda\lt 0$, this corresponds to $-2\le z\le0$ for Euler and both second-order methods, and approximately $-2.79\le z\le0$ for RK4. The RK4 endpoint is rounded and should not be used to test boundary membership. At $|R|=1$, values may fail to decay. Even a high-order method may need small steps for a rapidly decaying problem.

Conclusion

We derived second-order methods and classical RK4 from Euler’s method by matching Taylor coefficients.

The numerical examples also confirmed the convergence orders. Function evaluation counts and stability need to be considered alongside accuracy.