---
title: Numerical solutions (Euler, RK4)
heading: Solving any state equation with small steps
eyebrow: A8 · Lesson 45 · Numerical solutions
xp: 50
---

::: hook
Most circuits have no neat formula for their response: a diode, a transistor or a dozen parts is enough to make the algebra hopeless. A computer solves them anyway, by stepping the state equation forward in small steps, the way A4 stepped one capacitor. But try Euler's method on a lossless LC circuit and something strange happens: the simulated circuit gains energy every cycle, out of nowhere. A better recipe for each step fixes that almost completely, and it's the one used across science and engineering.

::: play
- The exact path of an ideal LC circuit in its state plane (scaled so the radius is 1) is a circle, traveled clockwise. The spiral is where Euler's method takes it, step by step. RK4's path sits so close to the circle that it hides it.
- Raise the step size h (in units of $1/\omega_0$). What does Euler's path do? Does RK4's path leave the circle?
- Raise the number of steps. The readouts show how much energy each method has gained or lost.
:::
:::

```sim plot
view: complex
range: 2
slider: h = 0.05..0.5 step 0.05 = 0.2
slider: N = 1..40 step 1 = 30
curve: exp(-j*h*u) | over: u = 0..N | color: ch3
curve: (1 - j*h)^u | over: u = 0..N | color: ch1
curve: (1 - j*h - h^2/2 + j*h^3/6 + h^4/24)^u | over: u = 0..N | color: ch2
dot: (1 - j*h)^N | label: Euler | color: ch1
dot: (1 - j*h - h^2/2 + j*h^3/6 + h^4/24)^N | label: RK4 | color: ch2
readout: Euler energy × = (1 + h^2)^N
readout: RK4 energy × = abs(1 - j*h - h^2/2 + j*h^3/6 + h^4/24)^(2*N) | digits: 6
```

::: predict
## Euler's method steps an ideal LC circuit with $h = 0.2/\omega_0$. After many steps, what has happened to the simulated energy?

- [ ] It's exactly the same
- [x] It has grown, a little more every step
- [ ] It has shrunk, a little every step
- [ ] It swings up and down but averages out

::: reveal
It has grown. Each Euler step heads along the tangent to the circle, and a tangent line always ends up outside the circle, so every step lands a little farther out. For this system the energy grows by a factor $1 + h^2$ per step, 4% at $h = 0.2$, and it compounds: after 30 steps it's more than three times what it should be. Shrinking h only slows the drift. RK4's error per step is about $h^6/72$, so tiny that it barely moves off the circle.
:::
:::

::: nameit
## Stepping a state equation

**Euler for systems.** The state equation $\dot{\mathbf{x}} = \mathbf{f}(t, \mathbf{x})$ gives the rate of change of the whole state vector. Euler's method uses the rate at the start of each step for the whole step:

$$\mathbf{x}_{k+1} = \mathbf{x}_k + h\,\mathbf{f}(t_k, \mathbf{x}_k)$$

That's A4's method with vectors in place of numbers, and it has the same weakness: its error shrinks only in proportion to $h$. For the LC circuit in its scaled state form ($\dot x = y$, $\dot y = -x$), each step multiplies the state by a matrix whose size is $\sqrt{1 + h^2}$, so the amplitude creeps outward.

**Runge–Kutta (RK4).** Sample the rate four times in each step and take a weighted average:

$$\begin{aligned}
\mathbf{k}_1 &= \mathbf{f}(t_k, \mathbf{x}_k) \\
\mathbf{k}_2 &= \mathbf{f}(t_k + h/2,\ \mathbf{x}_k + \tfrac{h}{2}\mathbf{k}_1) \\
\mathbf{k}_3 &= \mathbf{f}(t_k + h/2,\ \mathbf{x}_k + \tfrac{h}{2}\mathbf{k}_2) \\
\mathbf{k}_4 &= \mathbf{f}(t_k + h,\ \mathbf{x}_k + h\mathbf{k}_3) \\
\mathbf{x}_{k+1} &= \mathbf{x}_k + \tfrac{h}{6}(\mathbf{k}_1 + 2\mathbf{k}_2 + 2\mathbf{k}_3 + \mathbf{k}_4)
\end{aligned}$$

The first sample is at the start, two are at the middle (the second using the first to get there), and one is at the end. The weights 1, 2, 2, 1 are Simpson's rule from A6. The result matches the true solution's Taylor series through the $h^4$ term, so RK4 is a **fourth-order** method: halving the step cuts the error by $2^4 = 16$.

| Method | Rate samples per step | Halve h and the error falls by |
|---|---|---|
| Euler | 1 | 2 |
| midpoint (RK2) | 2 | 4 |
| RK4 | 4 | 16 |

Four samples per step costs four times the work of Euler, but for the same accuracy RK4 can usually take steps hundreds of times longer, or more.

**Choosing the step.** A good step is small compared with the fastest thing the circuit does: its shortest time constant or ringing period. Real simulators estimate their own error each step and adjust $h$ automatically. Circuits with both very fast and very slow parts, called **stiff**, need special implicit methods that stay stable with long steps. The circuit simulator in this course uses the exact solution for linear circuits and an adaptive, implicit fourth-order method once diodes and transistors are involved.
:::

::: example
## Euler's method on $\dot y = -y$ from $y(0) = 1$ with $h = 0.1$: what does it give at $t = 1$?

::: solution
1. **One step.** Each step multiplies by $0.9$.
2. **Ten steps.**
   $$\begin{aligned} y(1) &\approx 0.9^{10} \\ &= 0.3487 \end{aligned}$$
3. **Compare.** The exact value is $e^{-1} = 0.3679$: an error of 0.019, about 5%.

**Answer:** Euler gives 0.3487 against the exact 0.3679, an error of about 5%.
:::
:::

::: example
## One RK4 step of $h = 0.1$ on $\dot y = -y$ from 1. How close is it?

::: solution
1. **The RK4 step.** RK4 gives
   $$\begin{aligned} y_1 &= 1 - 0.1 + \frac{0.01}{2} \\ &\quad - \frac{0.001}{6} + \frac{0.0001}{24} \\ &= 0.9048375 \end{aligned}$$
2. **Compare.** The exact value is $e^{-0.1} = 0.9048374$: an error of $8 \times 10^{-8}$, from a single step.

**Answer:** RK4 gives 0.9048375, within $8 \times 10^{-8}$ of the exact value.
:::
:::

::: example
## Euler's method on $\dot y = -y$ from $y(0) = 1$: compare the error at $t = 1$ for $h$ = 0.1 and $h$ = 0.05.

::: solution
1. **The step factor.** Each step multiplies by $1 - h$.
2. **With $h = 0.1$.** Ten steps give
   $$0.9^{10} = 0.34868$$
   against $e^{-1} = 0.36788$: an error of 0.0192.
3. **With $h = 0.05$.** Twenty steps give
   $$0.95^{20} = 0.35849$$
   an error of 0.0094.
4. **Compare.** Halving the step halves the error, the signature of a first-order method. RK4, being fourth order, would cut it by 16.

**Answer:** the error is 0.0192 with $h$ = 0.1 and 0.0094 with $h$ = 0.05: halving the step halves the error.
:::
:::

::: check
kind: python
given: h = 0.05 | 0.1 | 0.2; N = 50 | 100 | 200

## Simulate the scaled ideal LC circuit $\dot x = y$, $\dot y = -x$ from $(x, y) = (1, 0)$ with Euler's method, step $h$ = {h}, for {N} steps. Fill the arrays `x` and `y`, and set `ratio` to the energy $x^2 + y^2$ at the end divided by the energy at the start.

```python starter
import numpy as np

x = np.zeros(N + 1)   # capacitor voltage, scaled
y = np.zeros(N + 1)   # inductor current, scaled
x[0], y[0] = 1.0, 0.0
for k in range(N):
    x[k + 1] = x[k]   # replace: Euler step for dx/dt = y
    y[k + 1] = y[k]   # replace: Euler step for dy/dt = -x
ratio = 0             # replace: final energy over starting energy
print(ratio)
```

```python solution
import numpy as np

x = np.zeros(N + 1)
y = np.zeros(N + 1)
x[0], y[0] = 1.0, 0.0
for k in range(N):
    x[k + 1] = x[k] + h * y[k]
    y[k + 1] = y[k] - h * x[k]
ratio = (x[-1]**2 + y[-1]**2) / (x[0]**2 + y[0]**2)
print(ratio)
```

```python tests
assert len(x) == N + 1 and len(y) == N + 1, "x and y should each hold N + 1 values."
assert abs(x[1] - 1.0) < 1e-12 and abs(y[1] + h) < 1e-12, f"One Euler step from (1, 0) should land at (1, {-h}); yours is ({x[1]}, {y[1]})."
expected = (1 + h * h) ** N
assert abs(ratio - expected) < 1e-9 * expected, f"Each Euler step multiplies the energy by 1 + h², so the ratio should be {expected:.6f}; yours is {ratio}."
```

::: right
Right. The energy grew by exactly $(1 + h^2)^N$: Euler's method creates energy in a lossless circuit.
:::
:::

::: check
kind: python
given: zeta = 0.2 | 0.5 | 0.7

## Write `rk4(f, t, s, h)`, one RK4 step for a state vector `s`. Use it to find the step response of $\ddot x + 2\zeta\dot x + x = 1$ with ζ = {zeta}, from rest, at $t = 10$ (200 steps of 0.05). Set `x_end`.

```python starter
import numpy as np

def f(t, s):
    x, v = s
    return np.array([v, 1 - 2 * zeta * v - x])

def rk4(f, t, s, h):
    return s + h * f(t, s)   # replace: this is an Euler step

h = 0.05
s = np.array([0.0, 0.0])
t = 0.0
for k in range(200):
    s = rk4(f, t, s, h)
    t += h
x_end = s[0]
print(x_end)
```

```python solution
import numpy as np

def f(t, s):
    x, v = s
    return np.array([v, 1 - 2 * zeta * v - x])

def rk4(f, t, s, h):
    k1 = f(t, s)
    k2 = f(t + h / 2, s + h / 2 * k1)
    k3 = f(t + h / 2, s + h / 2 * k2)
    k4 = f(t + h, s + h * k3)
    return s + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

h = 0.05
s = np.array([0.0, 0.0])
t = 0.0
for k in range(200):
    s = rk4(f, t, s, h)
    t += h
x_end = s[0]
print(x_end)
```

```python tests
wd = np.sqrt(1 - zeta**2)
exact = 1 - np.exp(-zeta * 10) * (np.cos(wd * 10) + zeta / wd * np.sin(wd * 10))
assert abs(x_end - exact) < 1e-6, f"x(10) should match the exact {exact:.8f} to within 1e-6; yours is {x_end:.8f}."
```

::: right
Right. With 200 steps RK4 matches the exact step response from lesson 18 to better than a millionth.
:::
:::

::: check
kind: python
given: h1 = 0.1 | 0.2 | 0.25

## The function below runs RK4 on $dv/dt = -v$ from $v = 1$ to $t = 5$. Find its error against $e^{-5}$ with step {h1} (`err1`) and with half that step (`err2`), and set `ratio` to `err1 / err2`.

```python starter
import numpy as np

def rk4_decay(h):
    n = int(round(5 / h))
    v = 1.0
    for k in range(n):
        k1 = -v
        k2 = -(v + h / 2 * k1)
        k3 = -(v + h / 2 * k2)
        k4 = -(v + h * k3)
        v = v + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
    return v

err1 = 0   # replace
err2 = 0   # replace
ratio = 0
print(err1, err2, ratio)
```

```python solution
import numpy as np

def rk4_decay(h):
    n = int(round(5 / h))
    v = 1.0
    for k in range(n):
        k1 = -v
        k2 = -(v + h / 2 * k1)
        k3 = -(v + h / 2 * k2)
        k4 = -(v + h * k3)
        v = v + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
    return v

err1 = abs(rk4_decay(h1) - np.exp(-5))
err2 = abs(rk4_decay(h1 / 2) - np.exp(-5))
ratio = err1 / err2
print(err1, err2, ratio)
```

```python tests
assert err1 > err2 > 0, "The smaller step should give a smaller, nonzero error."
assert abs(err1 - abs(rk4_decay(h1) - np.exp(-5))) < 1e-15, "err1 should be the error with step h1."
assert abs(ratio - err1 / err2) < 1e-9, "ratio should be err1 / err2."
assert 14 < ratio < 18, f"A fourth-order method's error should fall about 16 times when the step halves; your ratio is {ratio:.2f}."
```

::: right
Right. A ratio near 16, the signature of a fourth-order method.
:::
:::

::: check
given: h = 0.1 | 0.2 | 0.3 | 0.5
answer: sqrt(1 + h^2)
tolerance: 0.01%

## Euler's method steps the scaled LC circuit with $h$ = {h}. By what factor does each step multiply the amplitude?

::: right
Right. Each step multiplies the size of the state by $\sqrt{1 + h^2}$ = {answer}, and the energy by $1 + h^2$.
:::

::: misses
- [1 + h^2] That's the energy factor. The amplitude grows by its square root.
- [1] Euler's steps run along tangents, which always end up outside the circle.
- [any] Not yet. From $(x, y)$ one step lands at $(x + hy, y - hx)$. Compare the sizes.
:::
:::

::: check
kind: choice

## RK4 gives an error of $10^{-6}$ with a step of 1 µs. Roughly what error would a step of 0.5 µs give?

- [ ] $5 \times 10^{-7}$
- [ ] $2.5 \times 10^{-7}$
- [x] About $6 \times 10^{-8}$
- [ ] $10^{-12}$

::: right
Right. A fourth-order method's error falls by $2^4 = 16$ when the step halves.
:::

::: misses
- [1] That's what a first-order method like Euler gives.
- [2] That's a second-order method. RK4 is fourth order.
- [4] That's squaring the error. The step halved, so the error falls by $2^4$.
:::
:::

::: check
kind: parts
given: h = 0.1 | 0.2 | 0.05; a = 1 | 2

## Euler's method steps $\dot y = -\given{a}y$ from $y(0) = 1$ to $t = 1$ with $h$ = {h}.

::: part
answer: (1 - a*h)^(1/h)
tolerance: 0.5%

### What does it give?

::: misses
- [exp(-a)] That's the exact value.
- [any] Each step multiplies by $1 - ah$.
:::
:::

::: part
answer: exp(-a) - (1 - a*h)^(1/h)
tolerance: 1%

### What is its error?

::: misses
- [any] Exact minus computed.
:::
:::
:::

::: check
kind: derivation
vars: h = 0.01..0.5, l = -5..-0.1

## Find the factor each step multiplies by on $\dot y = \lambda y$.

::: step
answer: 1 + l*h

### For forward Euler?
:::

::: step
answer: 1/(1 - l*h)

### For backward Euler?
:::

::: right
Right. Forward Euler is stable only while $|1 + \lambda h| \le 1$; backward Euler's factor is below 1 for every $h$.
:::
:::

::: explain
## Why does Euler's method make a lossless LC circuit gain energy, and why doesn't making the step smaller fully fix it?

::: model
Each Euler step moves along the tangent to the true path, which for an LC circuit is a circle in the state plane. A tangent always leads outside the circle, so every step lands slightly farther from the center: the simulated energy grows by a factor $1 + h^2$ per step. A smaller step makes each gain smaller, but it also takes more steps to cover the same time, and the gains compound, so the energy still drifts upward, just more slowly. A higher-order method like RK4 follows the curve so closely that the drift is negligible for practical step sizes.
:::
:::

::: practice

::: check
given: x = 2 | 4 | 6; y = -3 | -1 | 1 | 3 | 5; h = 0.1 | 0.2
answer: x + h*y
tolerance: 0.5%

## For $\dot x = y$, $\dot y = -x$, one Euler step of {h} starts at $(x, y)$ = ({x}, {y}). What is the new $x$?

::: misses
- [x - h*y] The rate of x is $+y$.
- [x + h*x] The rate of x is y, not x.
- [any] $x_{k+1} = x_k + h\,y_k$.
:::
:::

::: check
given: k = 2 | 3 | 4 | 10
answer: k^4
tolerance: 0.5%

## You shrink an RK4 step by a factor of {k}. By roughly what factor does the error fall?

::: misses
- [k] That's a first-order method.
- [k^2] That's a second-order method.
- [any] RK4 is fourth order: error goes as $h^4$.
:::
:::

::: check
given: h = 0.2 | 0.3 | 0.4; N = 10 | 20 | 50
answer: (1 + h^2)^N
tolerance: 0.5%

## Euler's method runs the scaled LC circuit for {N} steps of {h}. By what factor has the energy grown?

::: misses
- [1 + N*h^2] The growth compounds: it's $(1 + h^2)^N$.
- [(1 + h)^N] Each step multiplies the energy by $1 + h^2$.
- [any] Each step multiplies the energy by $1 + h^2$.
:::
:::
:::
