---
title: Runge-Kutta and step size
heading: Four looks per step instead of one
eyebrow: A4 · Lesson 42 · Runge-Kutta and step size
xp: 40
---

::: hook
Euler's method (lesson 41) takes the slope at the start of each step and walks in a straight line. It's simple and it works, but its error only halves when you halve the step, so accurate answers take a huge number of steps. The classical Runge-Kutta method takes four slope samples per step and combines them; halving its step cuts the error sixteenfold. Most circuit simulators, orbit calculators and physics engines use a method of this family.
:::

::: predict
## Euler's method gives an error of 1% with some step size. Halving the step, what does RK4's error do, compared with Euler's?

- [ ] Both halve
- [x] Euler's halves; RK4's falls about sixteenfold
- [ ] Both fall fourfold
- [ ] RK4's doubles, because it does more arithmetic

::: reveal
Euler's error is proportional to the step $h$, so it halves. RK4's is proportional to $h^4$, so halving $h$ divides it by $2^4 = 16$. That's why RK4 with a modest step usually beats Euler with a tiny one, even though each RK4 step costs four evaluations.
:::
:::

::: nameit
## The method

For $\dfrac{dy}{dt} = f(t, y)$, one RK4 step from $(t, y)$ to $t + h$:

$$k_1 = f(t, y)$$
$$k_2 = f\!\left(t + \tfrac{h}{2},\ y + \tfrac{h}{2}k_1\right)$$
$$k_3 = f\!\left(t + \tfrac{h}{2},\ y + \tfrac{h}{2}k_2\right)$$
$$k_4 = f(t + h,\ y + hk_3)$$
$$y_{\text{next}} = y + \frac{h}{6}(k_1 + 2k_2 + 2k_3 + k_4)$$

$k_1$ is Euler's slope; $k_2$ and $k_3$ are slopes at the middle of the step, using trial values; $k_4$ looks at the end. The weighted average matches the true solution's Taylor series up to $h^4$.

```
def rk4_step(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)
```

## Systems: several variables at once

Higher-order equations become first-order systems. A series RLC circuit driven by $V_s$ has two states, the capacitor voltage $v$ and the current $i$:

$$\frac{dv}{dt} = \frac{i}{C} \qquad \frac{di}{dt} = \frac{V_s - Ri - v}{L}$$

Write $y$ as a NumPy array `[v, i]` and `f` returning `np.array([i / C, (Vs - R*i - v) / L])`; the same `rk4_step` works unchanged, because the arithmetic is elementwise.

## Choosing the step

- The step must be small compared with the fastest thing happening: a time constant, or a period of ringing. A tenth of it is a reasonable start.
- **Check by halving.** Run with $h$ and $h/2$. For RK4, the error of the finer run is about $|y_h - y_{h/2}|/15$. If it's not small enough, halve again.
- Very stiff problems (fast and slow time constants together) want implicit methods, as this course's circuit engine uses; A8 and C2 come back to this.
:::

::: example
## Discharge $dv/dt = -v/\tau$ from 1 V over one time constant with 10 steps, by Euler and by RK4. Compare the errors.

::: solution
1. **Run both methods side by side.** Ten steps of $0.1\tau$, then compare each with $e^{-1}$.

```
import math
tau, h = 1.0, 0.1
f = lambda t, v: -v / tau
ve = vr = 1.0
for k in range(10):
    ve = ve + h * f(0, ve)
    vr = rk4_step(f, k * h, vr, h)
print(abs(ve - math.exp(-1)), abs(vr - math.exp(-1)))   # 0.0192, 3.3e-7
```

2. **Compare the errors.** Euler is off by 0.0192 and RK4 by $3.3 \times 10^{-7}$: in the same ten steps, RK4 is about 60,000 times more accurate here.

**Answer:** Euler's error is 0.0192 and RK4's is $3.3 \times 10^{-7}$, about 60,000 times smaller.
:::
:::

::: example
## A series RLC (R = 20 Ω, L = 10 mH, C = 1 µF) gets a 1 V step. Simulate it with RK4 and find the first peak of the capacitor voltage.

::: solution
1. **Write the circuit as two first-order equations.** The state is the capacitor voltage $v$ and the current $i$:
   $$\frac{dv}{dt} = \frac{i}{C}, \quad \frac{di}{dt} = \frac{V_s - Ri - v}{L}$$
2. **Step it with RK4 and keep the voltages.** A thousand steps of 1 µs.

```
import numpy as np
R, L, C, Vs = 20, 10e-3, 1e-6, 1.0
f = lambda t, y: np.array([y[1] / C, (Vs - R * y[1] - y[0]) / L])
h, y, vs = 1e-6, np.array([0.0, 0.0]), []
for k in range(1000):
    y = rk4_step(f, k * h, y, h)
    vs.append(y[0])
print(max(vs))      # 1.72925
```

3. **Find the damping ratio.**
   $$\begin{aligned} \zeta &= \frac{R}{2}\sqrt{C/L} \\ &= 0.1 \end{aligned}$$
4. **Compare with theory.**
   $$\begin{aligned} v_{pk} &= 1 + e^{-\pi\zeta/\sqrt{1 - \zeta^2}} \\ &= 1.72925\ \text{V} \end{aligned}$$
5. **Judge the agreement.** The simulation agrees to six figures with a step of a six-hundredth of the ringing period.

**Answer:** the capacitor voltage first peaks at 1.72925 V.
:::
:::

::: check
kind: python
given: tau = 1 | 2 | 5; n = 5 | 10 | 20

## Write `rk4_step(f, t, y, h)` and use it to integrate $dv/dt = -v/\tau$ from $v = 1$ over one time constant (`tau` = {tau}) in `n` = {n} steps. Set `v` to the final value and `err` to $|v - e^{-1}|$.

```python starter
import math

def rk4_step(f, t, y, h):
    return y + h * f(t, y)

v = 1.0
err = 0
print(v, err)
```

```python solution
import math

def rk4_step(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)

h = tau / n
v = 1.0
for k in range(n):
    v = rk4_step(lambda t, y: -y / tau, k * h, v, h)
err = abs(v - math.exp(-1))
print(v, err)
```

```python tests
import math
one = rk4_step(lambda t, y: -y, 0, 1.0, 0.1)
assert abs(one - (1 - 0.1 + 0.005 - 0.1**3 / 6 + 0.1**4 / 24)) < 1e-15, "One RK4 step of dy/dt = −y should match the Taylor series of e^{-h} up to h⁴. Check the four slopes and the weights 1, 2, 2, 1 over 6."
assert err < 1e-4, "After n RK4 steps the error should be tiny."
assert abs(v - (1 - 1 / n + 0.5 / n**2 - 1 / (6 * n**3) + 1 / (24 * n**4))**n) < 1e-12, "v should be n RK4 steps from 1."
```
:::

::: check
kind: python
given: n = 10 | 20 | 40

## Integrate $dv/dt = -v$ from $v = 1$ to $t = 2$ with Euler and with RK4, using `n` = {n} and then `2 * n` steps. Set `ratio_euler` and `ratio_rk4` to (error with n steps) / (error with 2n steps) for each method.

```python starter
import math

def rk4_step(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)

ratio_euler = ratio_rk4 = 0
print(ratio_euler, ratio_rk4)
```

```python solution
import math

def rk4_step(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)

f = lambda t, y: -y

def run(steps, rk):
    h, y = 2 / steps, 1.0
    for k in range(steps):
        y = rk4_step(f, k * h, y, h) if rk else y + h * f(k * h, y)
    return abs(y - math.exp(-2))

ratio_euler = run(n, False) / run(2 * n, False)
ratio_rk4 = run(n, True) / run(2 * n, True)
print(ratio_euler, ratio_rk4)
```

```python tests
assert 1.8 < ratio_euler < 2.2, "Euler is first order, so halving the step should roughly halve the error: a ratio near 2."
assert 14 < ratio_rk4 < 18, "RK4 is fourth order, so halving the step should cut the error about 16 times."
```
:::

::: check
kind: python
given: R = 10 | 20 | 50; L = 10 | 22

## Simulate a series RLC (`R` = {R} Ω, `L` = {L} mH, `C` = 1 µF) driven by a 1 V step from rest, with RK4, state `[v, i]`, step 1 µs, for 2000 steps. Set `v` to the array of capacitor voltages after each step and `peak` to its largest value.

```python starter
import numpy as np

def rk4_step(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)

v = np.zeros(2000)
peak = 0
print(peak)
```

```python solution
import numpy as np

def rk4_step(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)

Lh, C = L * 1e-3, 1e-6
f = lambda t, y: np.array([y[1] / C, (1.0 - R * y[1] - y[0]) / Lh])
h = 1e-6
y = np.array([0.0, 0.0])
v = np.zeros(2000)
for k in range(2000):
    y = rk4_step(f, k * h, y, h)
    v[k] = y[0]
peak = v.max()
print(peak)
```

```python tests
import numpy as np
zeta = R / 2 * np.sqrt(1e-6 / (L * 1e-3))
want = 1 + np.exp(-np.pi * zeta / np.sqrt(1 - zeta**2))
assert len(v) == 2000, "v should hold 2000 voltages."
assert abs(peak - want) < 0.01, f"The peak should be close to {want:.4f}, the theory for a damping ratio of {zeta:.3f}. Check dv/dt = i/C and di/dt = (1 − Ri − v)/L, with L in henries."
assert abs(v[-1] - 1) < 0.5, "The voltage should be settling toward 1 V."
```
:::

::: check
kind: python
given: th0 = 10 | 45 | 90 | 150; Lp = 0.5 | 1 | 2

## A pendulum of length `Lp` = {Lp} m obeys $\ddot\theta = -(g/L)\sin\theta$ with $g$ = 9.81 m/s². Released from rest at `th0` = {th0}°, integrate it with RK4 (state `[theta, omega]`, step 1 ms) until $\theta$ has crossed zero going downward twice. Set `T` to the time between those two crossings (interpolate linearly within each step), and `ratio` to `T` divided by the small-angle period $2\pi\sqrt{L/g}$.

```python starter
import math
g = 9.81
T = 2 * math.pi * math.sqrt(Lp / g)
ratio = 1
print(T, ratio)
```

```python solution
import math
g = 9.81

def f(y):
    return [y[1], -g / Lp * math.sin(y[0])]

def rk4(y, h):
    k1 = f(y)
    k2 = f([y[i] + h / 2 * k1[i] for i in range(2)])
    k3 = f([y[i] + h / 2 * k2[i] for i in range(2)])
    k4 = f([y[i] + h * k3[i] for i in range(2)])
    return [y[i] + h / 6 * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]) for i in range(2)]

h = 1e-3
y = [math.radians(th0), 0.0]
t = 0.0
downs = []
while len(downs) < 2:
    y2 = rk4(y, h)
    if y[0] > 0 >= y2[0]:
        downs.append(t + h * y[0] / (y[0] - y2[0]))
    y, t = y2, t + h
T = downs[1] - downs[0]
ratio = T / (2 * math.pi * math.sqrt(Lp / g))
print(T, ratio)
```

```python tests
import math
def agm(a, b):
    while abs(a - b) > 1e-15 * a:
        a, b = (a + b) / 2, math.sqrt(a * b)
    return a
k = math.sin(math.radians(th0) / 2)
exact = 4 * math.sqrt(Lp / 9.81) * math.pi / (2 * agm(1, math.sqrt(1 - k * k)))
assert abs(T - exact) < 1e-5 * exact, f"T should be {exact:.6f} s. Detect each downward crossing (theta > 0 before the step, <= 0 after) and interpolate."
assert abs(ratio - exact / (2 * math.pi * math.sqrt(Lp / 9.81))) < 1e-5, "ratio is T over 2π√(L/g)."
```

::: right
Right. The small-angle formula assumes $\sin\theta \approx \theta$; at {th0}° the real swing is slower, and RK4 measures by how much without any approximation. The exact answer needs an elliptic integral, which is how the check knows yours is right.
:::
:::

::: check
kind: python
given: n = 4 | 5 | 10 | 20

## Integrate $dv/dt = -v$ from $v = 1$ to $t = 1$ with RK4, once with `n` = {n} steps (`y1`) and once with `2 * n` (`y2`). For a fourth-order method, the error in `y2` (that is, `y2` minus the exact answer) is about $(y_1 - y_2)/15$. Set `est` to that estimate and `true_err` to `y2 - math.exp(-1)`.

```python starter
import math

def rk4_run(n):
    return math.exp(-1)

y1, y2 = rk4_run(n), rk4_run(2 * n)
est = 0
true_err = 0
print(est, true_err)
```

```python solution
import math

def rk4_run(n):
    h = 1 / n
    y = 1.0
    for _ in range(n):
        k1 = -y
        k2 = -(y + h / 2 * k1)
        k3 = -(y + h / 2 * k2)
        k4 = -(y + h * k3)
        y += h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
    return y

y1, y2 = rk4_run(n), rk4_run(2 * n)
est = (y1 - y2) / 15
true_err = y2 - math.exp(-1)
print(est, true_err)
```

```python tests
import math
def run(m):
    h, y = 1 / m, 1.0
    for _ in range(m):
        k1 = -y; k2 = -(y + h / 2 * k1); k3 = -(y + h / 2 * k2); k4 = -(y + h * k3)
        y += h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
    return y
a, b = run(n), run(2 * n)
assert abs(true_err - (b - math.exp(-1))) < 1e-15, "true_err is y2 - exp(-1), with y2 from 2n RK4 steps."
assert abs(est - (a - b) / 15) < 1e-15, "est is (y1 - y2) / 15."
assert abs(est / true_err - 1) < 0.15, "The estimate should be within 15% of the true error."
```

::: right
Right. Halving the step divides a fourth-order method's error by 16, so the change between the two runs is 15 times the finer run's error. That's how adaptive solvers judge their own accuracy without knowing the answer.
:::
:::

::: check
kind: choice

## How many times does one step of classical RK4 evaluate the slope function $f$?

- [x] 4
- [ ] 1
- [ ] 2
- [ ] 16

::: right
Right. It samples the slope at the start, twice at the midpoint and once at the end, then takes a weighted average. Four evaluations buy fourth-order accuracy.
:::

::: misses
- [2] That's Euler's method: one slope per step.
- [3] Two evaluations give a second-order method such as the midpoint method or Heun's.
- [4] Four evaluations make one RK4 step; the "4" is also its order.
:::
:::

::: explain
## RK4 needs four evaluations of $f$ per step and Euler needs one. Why is RK4 usually cheaper for a given accuracy?

::: model
Euler's error shrinks only in proportion to the step, so to get ten times more accurate you need ten times more steps. RK4's error shrinks as the fourth power of the step, so a modest reduction in step size buys a large gain: ten times more accurate needs only about 1.8 times more steps. For any accuracy beyond the crudest, RK4 reaches it with so many fewer steps that its four evaluations per step still cost far less in total.
:::
:::

::: practice

::: check
kind: python
given: a = 0.5 | 1 | 1.2 | 1.5 | 2

## Use RK4 with 100 steps to integrate $dy/dt = a\,y$ (`a` = {a}) from $y = 1$ over $t \in [0, 1]$; set `y` to the result.

```python starter
y = 1.0
print(y)
```

```python solution
def rk4_step(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)

y = 1.0
for k in range(100):
    y = rk4_step(lambda t, y: a * y, k * 0.01, y, 0.01)
print(y)
```

```python tests
import math
assert abs(y - math.exp(a)) < 1e-7, "y should be very close to e^a."
```
:::

::: check
kind: python
given: y1 = 0.60653066 | 0.6065307; y2 = 0.6065306597 | 0.6065306602

## Two RK4 runs with step $h$ and $h/2$ gave `y1` = {y1} and `y2` = {y2}. Set `est` to the estimated error of `y2`, $|y_1 - y_2|/15$.

```python starter
est = 0
print(est)
```

```python solution
est = abs(y1 - y2) / 15
print(est)
```

```python tests
assert abs(est - abs(y1 - y2) / 15) < 1e-18, "est is |y1 − y2| / 15 for a fourth-order method."
```
:::
:::
