---
title: "Lab: differential equations in code"
heading: Stepping equations you can and can't solve
eyebrow: A6 · Lesson 19 · Lab: differential equations in code
xp: 60
---

::: hook
Separation of variables solved the logistic equation, the draining tank and quadratic decay exactly. A computer can solve all of them, and the many that don't separate, by stepping: Runge–Kutta, which A4 introduced, takes four slope samples per step and is accurate enough for almost anything. In this lab you'll check it against the exact solutions you found, then use it where formulas run out: finding where a heating part settles, deciding whether it runs away, and timing a tank to the last drop.
:::

::: play
- The curve is the temperature rise of a part that heats itself, $\tau\Delta T' = \theta P_0(1 + \alpha\Delta T) - \Delta T$, for the loop gain $g = \alpha\theta P_0$ you choose.
- Below $g = 1$ it settles at $\frac{\theta P_0}{1 - g}$; at and above 1 it never settles.
- Move $g$ toward 1 and watch the settling level and the time it takes both grow.
:::

```sim plot
view: graph
x: t = 0..600 s
y: dT = 0..200
slider: g = 0.1..1.2 = 0.5
plot: 20/(1 - g)*(1 - exp(-(1 - g)*t/60))*step(0.999 - g) + 20*t/60*step(g - 0.999)*step(1.001 - g) + 20/(g - 1)*(exp((g - 1)*t/60) - 1)*step(g - 1.001) | samples: 400 | label: temperature rise
readout: settles at, if it does = 20/(1 - g) | digits: 4
```

::: predict
## A part's loop gain $\alpha\theta P_0$ rises from 0.5 to 0.9. How does its settling temperature rise change, and how long does it take to settle?

- [x] The rise grows 5 times larger and takes 5 times as long
- [ ] It grows by 80% and settles just as fast
- [ ] It doubles and settles twice as fast
- [ ] Nothing changes until the gain reaches 1

::: reveal
Both grow 5 times. The settled rise is $\frac{\theta P_0}{1 - g}$, which goes from $2\theta P_0$ to $10\theta P_0$, and the deviation decays as $e^{-(1 - g)t/\tau}$, with a time constant $\frac{\tau}{1 - g}$ that also grows from $2\tau$ to $10\tau$. Near $g = 1$ the system is barely stable: slow and very hot.
:::
:::

::: nameit
## Runge–Kutta 4

For $y' = f(t, y)$ with step $h$:

$$k_1 = f(t, y),\ k_2 = f\left(t + \tfrac h2, y + \tfrac h2k_1\right),\ k_3 = f\left(t + \tfrac h2, y + \tfrac h2k_2\right),\ k_4 = f(t + h, y + hk_3)$$
$$y \leftarrow y + \frac h6(k_1 + 2k_2 + 2k_3 + k_4)$$

Its error goes as $h^4$, so a modest number of steps gives many digits.

## Finding where it settles

Step until the rate $|y'|$ falls below a small tolerance, then report $y$. If $y$ grows past a cap instead, report that it runs away. That's an empirical stability test, and it agrees with the sign of $f'$ at the equilibrium.

## Events

To time an event, such as a tank running dry, step until the quantity crosses the level, then interpolate between the last two steps. For a tank with $h' = -c\sqrt h$, guard the square root with `max(h, 0)` so a step that overshoots below zero doesn't fail.
:::

::: example
## Check RK4 on the logistic equation with $K$ = 1000, $r$ = 0.5, $y_0$ = 100, out to $t$ = 8 with 80 steps.

::: solution
1. **Exact value.**
   $$\begin{aligned} y(8) &= \frac{1000}{1 + 9e^{-4}} \\ &= 858.486\,45 \end{aligned}$$
2. **RK4 with $h = 0.1$.** It gives 858.486 44, off by $6 \times 10^{-6}$.
3. **Halve the number of steps.** With 40 steps the error grows by about 16, as a fourth-order method's should.

**Answer:** RK4 with 80 steps gives 858.486 44, within $6 \times 10^{-6}$ of the exact 858.486 45.
:::
:::

::: example
## A part has $\theta P_0$ = 20 °C and $\alpha\theta P_0$ = 0.08. Where does it settle, numerically and exactly?

::: solution
1. **Step the equation.** Step it with $\tau$ = 60 s until the rate is below $10^{-9}$ °C/s:
   $$\tau\Delta T' = 20(1 + 0.004\Delta T) - \Delta T$$
   The stepper settles at 21.739 13 °C.
2. **Use the formula.**
   $$\frac{20}{1 - 0.08} = 21.739\,13$$
   the same value.
3. **Try the runaway case.** With $\alpha\theta P_0 = 1$ (say $\theta P_0$ = 250 °C), the stepper passes 1000 °C and reports a runaway.

**Answer:** it settles 21.739 13 °C above ambient, both numerically and from the formula.
:::
:::

::: check
given: g = 0.2 | 0.5 | 0.8; th = 10 | 20
answer: th/(1 - g)
unit: °C
tolerance: 0.5%

## A part's rise without feedback would be {th} °C; its loop gain is {g}. Where does it settle?

::: right
Right. $\frac{\theta P_0}{1 - g}$ = {answer}.
:::

::: misses
- [th*(1 + g)] Close for small gains, but the feedback compounds: $\frac{1}{1 - g}$.
- [any] Not yet. The settled rise is $\frac{\theta P_0}{1 - g}$.
:::
:::

::: check
given: g = 0.2 | 0.5 | 0.8; tau = 30 | 60
answer: tau/(1 - g)
unit: s
tolerance: 0.5%

## For the same part, with $\tau$ = {tau} s, what is the time constant of its settling?

::: right
Right. $\frac{\tau}{1 - g}$ = {answer}.
:::

::: misses
- [tau] The feedback slows the settling too.
- [any] Not yet. The deviation decays as $e^{-(1 - g)t/\tau}$.
:::
:::

::: check
kind: python

## Write `rk4(f, y0, t_end, n)` returning $y(t_\text{end})$ for $y' = f(t, y)$. Check it on the logistic equation ($K$ = 1000, $r$ = 0.5, $y_0$ = 100) at $t$ = 8, and set `ratio` to its error with 40 steps divided by its error with 80.

```python starter
import math

def rk4(f, y0, t_end, n):
    return y0

f = lambda t, y: 0.5 * y * (1 - y / 1000)
exact = 1000 / (1 + 9 * math.exp(-4))
ratio = abs(rk4(f, 100, 8, 40) - exact) / abs(rk4(f, 100, 8, 80) - exact)
print(ratio)
```

```python solution
import math

def rk4(f, y0, t_end, n):
    h = t_end / n
    t, y = 0.0, y0
    for _ in range(n):
        k1 = f(t, y)
        k2 = f(t + h / 2, y + h * k1 / 2)
        k3 = f(t + h / 2, y + h * k2 / 2)
        k4 = f(t + h, y + h * k3)
        y += h * (k1 + 2 * k2 + 2 * k3 + k4) / 6
        t += h
    return y

f = lambda t, y: 0.5 * y * (1 - y / 1000)
exact = 1000 / (1 + 9 * math.exp(-4))
ratio = abs(rk4(f, 100, 8, 40) - exact) / abs(rk4(f, 100, 8, 80) - exact)
print(ratio)
```

```python tests
import math
f = lambda t, y: 0.5 * y * (1 - y / 1000)
exact = 1000 / (1 + 9 * math.exp(-4))
assert abs(rk4(f, 100, 8, 80) - exact) < 1e-4, "With 80 steps RK4 should be within 1e-4 of 858.486."
assert 12 < ratio < 20, f"A fourth-order method's error should fall by about 16 when the step halves; got {ratio:.2f}."
assert abs(rk4(lambda t, y: -2 * y, 1, 1, 50) - math.exp(-2)) < 1e-8, "y' = -2y from 1 gives e^-2 at t = 1."
```

::: right
Right. Fourth order: halving the step cuts the error by about 16.
:::
:::

::: check
kind: python
given: th = 10 | 20 | 50

## Write `settle(th, a, P0=1, tau=60)`: step $\tau\Delta T' = \theta P_0(1 + \alpha\Delta T) - \Delta T$ from 0 with Euler steps of 0.5 s until the rate is below $10^{-9}$ (return $\Delta T$) or $\Delta T$ passes 1000 (return `None`). Set `d1 = settle(th, 0.004)` and `d2 = settle(th, 0.02)` for $\theta P_0$ = {th} °C.

```python starter
def settle(th, a, P0=1, tau=60):
    return th * P0

d1 = settle(th, 0.004)
d2 = settle(th, 0.02)
print(d1, d2)
```

```python solution
def settle(th, a, P0=1, tau=60):
    d = 0.0
    for _ in range(10**6):
        rate = (th * P0 * (1 + a * d) - d) / tau
        if abs(rate) < 1e-9:
            return d
        d += 0.5 * rate
        if d > 1000:
            return None
    return d

d1 = settle(th, 0.004)
d2 = settle(th, 0.02)
print(d1, d2)
```

```python tests
g1 = 0.004 * th
assert abs(d1 - th / (1 - g1)) < 1e-5, f"With loop gain {g1}, it should settle at {th / (1 - g1):.4f}; got {d1}."
g2 = 0.02 * th
if g2 < 1:
    assert d2 is not None and abs(d2 - th / (1 - g2)) < 1e-5, f"With loop gain {g2} it still settles, at {th / (1 - g2):.4f}; got {d2}."
else:
    assert d2 is None, f"With loop gain {g2} >= 1 it runs away; settle should return None, got {d2}."
```

::: right
Right. The stepper finds the equilibrium where it exists and reports the runaway where it doesn't, agreeing with the stability test.
:::
:::

::: check
kind: python
given: h0 = 1 | 2 | 4; c = 0.05 | 0.1

## Step a tank $h' = -c\sqrt{\max(h, 0)}$ from $h_0$ = {h0} m with $c$ = {c}, using Euler steps of 1 ms, until $h \le 0$. Set `t_empty` to the time, interpolated within the last step, and `exact` to $2\sqrt{h_0}/c$.

```python starter
import math

t_empty = exact = 0
print(t_empty, exact)
```

```python solution
import math

dt = 1e-3
h, t = float(h0), 0.0
while h > 0:
    h_old = h
    h -= dt * c * math.sqrt(max(h, 0))
    t += dt
t_empty = t - dt + h_old / (h_old - h) * dt
exact = 2 * math.sqrt(h0) / c
print(t_empty, exact)
```

```python tests
import math
assert abs(exact - 2 * math.sqrt(h0) / c) < 1e-12, "exact should be 2 sqrt(h0) / c."
assert abs(t_empty - exact) < 0.05, f"The stepped tank should empty within 0.05 s of {exact:.3f} s; got {t_empty:.4f}."
```

::: right
Right. The square root makes the last stretch tricky, since the rate falls to zero exactly at empty, but small steps still land within a few hundredths of a second.
:::
:::

::: check
kind: python
given: k = 0.2 | 1; y0 = 2 | 5

## Use your `rk4` (in the starter) on $y' = -ky^2$ from {y0} to $t$ = 4 with 40 steps. Set `y_num` and `y_exact`, and `half` to the time it reaches half its start, from the exact solution.

```python starter
def rk4(f, y0, t_end, n):
    h = t_end / n
    t, y = 0.0, y0
    for _ in range(n):
        k1 = f(t, y)
        k2 = f(t + h / 2, y + h * k1 / 2)
        k3 = f(t + h / 2, y + h * k2 / 2)
        k4 = f(t + h, y + h * k3)
        y += h * (k1 + 2 * k2 + 2 * k3 + k4) / 6
        t += h
    return y

y_num = y_exact = half = 0
print(y_num, y_exact, half)
```

```python solution
def rk4(f, y0, t_end, n):
    h = t_end / n
    t, y = 0.0, y0
    for _ in range(n):
        k1 = f(t, y)
        k2 = f(t + h / 2, y + h * k1 / 2)
        k3 = f(t + h / 2, y + h * k2 / 2)
        k4 = f(t + h, y + h * k3)
        y += h * (k1 + 2 * k2 + 2 * k3 + k4) / 6
        t += h
    return y

y_num = rk4(lambda t, y: -k * y * y, y0, 4, 40)
y_exact = y0 / (1 + k * y0 * 4)
half = 1 / (k * y0)
print(y_num, y_exact, half)
```

```python tests
assert abs(y_exact - y0 / (1 + k * y0 * 4)) < 1e-12, "y_exact should be y0 / (1 + k y0 t)."
assert abs(y_num - y_exact) < 1e-4, f"RK4 should match the exact {y_exact:.6f}; got {y_num:.6f}."
assert abs(half - 1 / (k * y0)) < 1e-12, "It halves at t = 1/(k y0)."
```

::: right
Right. The exact solution checks the code, and the code would handle the same equation with any added term that ruined the separation.
:::
:::

::: explain
## Why test a numerical solver on equations you can already solve exactly?

::: model
A solver's output looks equally confident whether it's right or wrong: a bug in a coefficient or a step that uses the wrong time still produces smooth, plausible curves. Equations with known solutions are the only way to measure its actual error, and to check that the error shrinks as it should (by 16 for RK4 when the step halves). Once it passes on the logistic equation, quadratic decay and the tank, you can trust it on the nonlinear thermal problem or any other where no formula exists, because the code is the same and only the right-hand side changes. Engineers do the same with simulators: validate on circuits with closed-form answers before believing them on the ones that matter.
:::
:::

::: practice

::: check
given: th = 1..100; g = 0.01..0.95
answer: th/(1 - g)
tolerance: 0.5%

## Settled rise: {th} °C without feedback, loop gain {g}?

::: misses
- [any] $\frac{\theta P_0}{1 - g}$.
:::
:::

::: check
given: h0 = 0.1..10; c = 0.01..1
answer: 2*sqrt(h0)/c
tolerance: 0.5%

## Tank empty time: $h_0$ = {h0}, $c$ = {c}?

::: misses
- [any] $2\sqrt{h_0}/c$.
:::
:::
:::
