---
title: "Lab: stepping through time"
heading: Solving a rate equation by taking small steps
eyebrow: A5 · Lesson 38 · Lab: stepping through time
xp: 60
---

::: hook
The equation $y' = (y_\infty - y)/\tau$ has a formula for its solution, but change it slightly (a heater that switches off, a capacitor whose value depends on its voltage) and the formula disappears. A computer doesn't need one. It starts at the known value and takes small steps, each in the direction the equation gives. That's Euler's method, the simplest idea behind every circuit simulator's transient analysis. In this lab you'll write it, measure how its error shrinks with the step, and use it on two problems with no tidy formula.
:::

::: play
- The solid curve is the exact charging curve $5(1 - e^{-t/2})$. The dots are Euler's method with $n$ steps over 4 s: each step moves along the slope at its start.
- With few steps the dots run above the curve: each step uses the slope at its start, which is steeper than the average over the step, so it overshoots.
- Double $n$ and watch the error at the end roughly halve.
:::

```sim plot
view: graph
x: t = 0..4 s
y: y = 0..5.5
slider: n = 2..40 step 1 = 4
plot: 5*(1 - exp(-t/2)) | samples: 300 | label: exact
plot: 5*(1 - (1 - 2/n)^(floor(t*n/4 + 1e-9))) | samples: 600 | dashed | color: ch2 | label: Euler
readout: Euler at 4 s = 5*(1 - (1 - 2/n)^n) | digits: 4
readout: exact at 4 s = 5*(1 - exp(-2)) | digits: 4
```

::: predict
## Euler's method with 20 steps ends up 0.047 off. About how far off will it be with 40 steps?

- [x] About 0.023
- [ ] About 0.012
- [ ] About 0.003
- [ ] About 0.047, since the method is exact in the limit only

::: reveal
About 0.023, half as far. Euler's method is first order: each step's error goes as $h^2$, and there are $1/h$ steps, so the error at the end goes as $h$. Halving the step halves the error. That's slow, which is why simulators use higher-order methods such as Runge–Kutta (A4) for most work, but Euler's method shows the idea plainly.
:::
:::

::: nameit
## Euler's method

For $y' = f(t, y)$ with $y(0) = y_0$, choose a step $h$ and repeat

$$y_{k+1} = y_k + h\,f(t_k, y_k), \qquad t_{k+1} = t_k + h$$

Each step follows the tangent line at the start of the step. Over a span $T$ with $n = T/h$ steps, the error at the end is proportional to $h$.

## Checking a stepper

Run it on a problem with a known answer, at two step sizes. If the errors shrink by the factor the method promises (2 for Euler when $h$ halves), the code is right; if not, look for an off-by-one in the loop or a slope evaluated at the wrong time.

## Problems with no formula

- **A switched heater:** while the heater runs, $T' = (P\theta + T_a - T)/\tau$; when it switches off, $P = 0$. A stepper handles the switch by changing $P$ inside the loop at the right time.
- **A voltage-dependent capacitor:** charging through $R$ into a capacitor whose value falls with voltage, $C = C_0/(1 + v/2)$, gives $v' = \frac{(V_s - v)(1 + v/2)}{RC_0}$. It speeds up as the voltage rises. It can be integrated by partial fractions, which gives a check, but the stepper doesn't need that.

Stopping when a quantity first crosses a level is done in the loop too: step until $y$ passes the level, then interpolate between the last two points for the crossing time.
:::

::: example
## Take two Euler steps of $h = 0.5$ s on $y' = (5 - y)/2$ from $y = 0$.

::: solution
1. **First step.** At $y = 0$ the slope is 2.5:
   $$\begin{aligned} y_1 &= 0 + 0.5 \times 2.5 \\ &= 1.25 \end{aligned}$$
2. **Second step.** At $y = 1.25$ the slope is 1.875:
   $$\begin{aligned} y_2 &= 1.25 + 0.5 \times 1.875 \\ &= 2.1875 \end{aligned}$$
3. **Compare with the exact value.**
   $$\begin{aligned} y(1) &= 5(1 - e^{-0.5}) \\ &= 1.967 \end{aligned}$$
   so Euler is ahead of the curve at 2.19.
4. **Why it overshoots.** The curve flattens as it rises, and each step used the steeper slope from its start, so it overshot.

**Answer:** after two steps Euler gives $y_2 = 2.1875$, ahead of the exact 1.967.
:::
:::

::: example
## A heater with $P$ = 10 W, $\theta$ = 3 °C/W and $\tau$ = 60 s starts at room temperature, 25 °C, runs for 120 s and switches off. What does it read at 240 s?

::: solution
1. **While it's on.** It heads toward $25 + 30 = 55$ °C. After 120 s:
   $$\begin{aligned} T &= 25 + 30(1 - e^{-2}) \\ &= 50.94\ \text{°C} \end{aligned}$$
2. **After it switches off.** It decays toward 25 °C. After another 120 s:
   $$\begin{aligned} T &= 25 + 25.94e^{-2} \\ &= 28.51\ \text{°C} \end{aligned}$$
3. **In a stepper.** A stepper reproduces this by setting $P = 0$ once $t$ passes 120 s.

**Answer:** it reads 28.51 °C at 240 s.
:::
:::

::: check
given: e = 0.01 | 0.05 | 0.2
answer: e/2
tolerance: 0.5%

## Euler's method has an error of {e} at the end with step $h$. About what is it with step $h/2$?

::: right
Right. Euler's method is first order, so the error halves: {answer}.
:::

::: misses
- [e/4] That's for a second-order method.
- [any] Not yet. The end error is proportional to $h$.
:::
:::

::: check
given: y0 = 0 | 1; yinf = 5 | 10; tau = 1 | 2; h = 0.5 | 1
answer: y0 + h*(yinf - y0)/tau
tolerance: 0.5%

## Take one Euler step of $h$ = {h} on $y' = (\given{yinf} - y)/\given{tau}$ from $y$ = {y0}. Where does it land?

::: right
Right. $y_0 + h\,\frac{y_\infty - y_0}{\tau}$ = {answer}.
:::

::: misses
- [yinf + (y0 - yinf)*exp(-h/tau)] That's the exact value. One Euler step follows the tangent.
- [any] Not yet. Add $h$ times the slope at the start.
:::
:::

::: check
kind: python

## Write `euler(f, y0, t_end, n)` returning $y$ at `t_end` after `n` steps of Euler's method on $y' = f(t, y)$ from $y(0) = $ `y0`. Test it on $y' = (5 - y)/2$.

```python starter
def euler(f, y0, t_end, n):
    return y0

print(euler(lambda t, y: (5 - y) / 2, 0, 2, 20))
```

```python solution
def euler(f, y0, t_end, n):
    h = t_end / n
    t, y = 0.0, y0
    for _ in range(n):
        y += h * f(t, y)
        t += h
    return y

print(euler(lambda t, y: (5 - y) / 2, 0, 2, 20))
```

```python tests
import math
f = lambda t, y: (5 - y) / 2
assert abs(euler(f, 0, 1, 2) - 2.1875) < 1e-12, "Two steps of 0.5 from 0 should give 2.1875."
exact = 5 * (1 - math.exp(-1))
e20, e40 = abs(euler(f, 0, 2, 20) - exact), abs(euler(f, 0, 2, 40) - exact)
assert abs(e20 / e40 - 2) < 0.1, f"Halving the step should halve the error; got a ratio of {e20 / e40:.3f}."
assert abs(euler(lambda t, y: 2 * t, 0, 1, 1000) - 1) < 0.002, "For y' = 2t, y(1) should be close to 1."
```

::: right
Right. The ratio of about 2 confirms it's a correct first-order method.
:::
:::

::: check
kind: python
given: P = 5 | 10; t1 = 60 | 120

## A heater ($\theta$ = 3 °C/W, $\tau$ = 60 s) starts at 25 °C, runs at `P` = {P} W until `t1` = {t1} s, then switches off. Step $T' = (P\theta + 25 - T)/60$ with $h$ = 0.01 s, switching $P$ to 0 once $t \ge$ `t1`, and set `T_end` to the temperature at 240 s and `T_peak` to the highest temperature reached.

```python starter
T_end = 25
T_peak = 25
print(T_end, T_peak)
```

```python solution
h = 0.01
t, T = 0.0, 25.0
T_peak = T
for _ in range(24000):
    p = P if t < t1 else 0
    T += h * (p * 3 + 25 - T) / 60
    t += h
    T_peak = max(T_peak, T)
T_end = T
print(T_end, T_peak)
```

```python tests
import math
Tp = 25 + P * 3 * (1 - math.exp(-t1 / 60))
want = 25 + (Tp - 25) * math.exp(-(240 - t1) / 60)
assert abs(T_peak - Tp) < 0.01, f"The peak, at switch-off, should be {Tp:.3f} C; got {T_peak}."
assert abs(T_end - want) < 0.01, f"At 240 s it should read {want:.3f} C; got {T_end}."
```

::: right
Right. A stepper handles the switch with one `if`; the formula needs the problem split in two.
:::
:::

::: check
kind: python
given: V = 3 | 4 | 4.5

## A capacitor whose value falls with voltage charges as $v' = \frac{(5 - v)(1 + v/2)}{RC_0}$, with $RC_0$ = 1 ms, from 0 V. Step it with $h = 10^{-7}$ s until $v$ first reaches `V` = {V} V, and set `t_cross` to the crossing time, interpolated between the last two steps.

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

```python solution
h, RC = 1e-7, 1e-3
t, v = 0.0, 0.0
while v < V:
    v_old, t_old = v, t
    v += h * (5 - v) * (1 + v / 2) / RC
    t += h
t_cross = t_old + (V - v_old) / (v - v_old) * h
print(t_cross)
```

```python tests
import math
exact = 1e-3 / (1 + 5 / 2) * (math.log(5 / (5 - V)) + math.log(1 + V / 2))
assert abs(t_cross - exact) / exact < 1e-3, f"Partial fractions give {exact * 1e3:.4f} ms; got {t_cross * 1e3:.4f} ms."
assert t_cross < 1e-3 * math.log(5 / (5 - V)), "It charges faster than a fixed capacitor C0 would, since its capacitance falls."
```

::: right
Right. The stepper didn't need the partial fractions; the formula was only there to check it.
:::
:::

::: check
kind: python

## Write `heun(f, y0, t_end, n)`, the improved Euler method: from each point, take an Euler step to get a trial value, then use the average of the slopes at the start and at the trial point. Show it's second order: set `ratio` to the error with 10 steps divided by the error with 20, for $y' = (5 - y)/2$ from 0 to $t$ = 2.

```python starter
import math

def heun(f, y0, t_end, n):
    h = t_end / n
    t, y = 0.0, y0
    for _ in range(n):
        y += h * f(t, y)
        t += h
    return y

f = lambda t, y: (5 - y) / 2
exact = 5 * (1 - math.exp(-1))
ratio = abs(heun(f, 0, 2, 10) - exact) / abs(heun(f, 0, 2, 20) - exact)
print(ratio)
```

```python solution
import math

def heun(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, y + h * k1)
        y += h * (k1 + k2) / 2
        t += h
    return y

f = lambda t, y: (5 - y) / 2
exact = 5 * (1 - math.exp(-1))
ratio = abs(heun(f, 0, 2, 10) - exact) / abs(heun(f, 0, 2, 20) - exact)
print(ratio)
```

```python tests
import math
assert 3.8 < ratio < 4.3, f"A second-order method's error should fall by about 4 when the step halves; got {ratio:.3f}."
f = lambda t, y: (5 - y) / 2
exact = 5 * (1 - math.exp(-1))
assert abs(heun(f, 0, 2, 20) - exact) < 0.002, "With 20 steps Heun's method should be within 0.002."
assert abs(heun(lambda t, y: 2 * t, 0, 1, 4) - 1) < 1e-12, "It's exact for y' = 2t, a straight-line slope."
```

::: right
Right. One extra slope per step turns a first-order method into a second-order one: the idea Runge–Kutta methods take further.
:::
:::

::: explain
## Why does halving the step only halve Euler's error, when each step's own error shrinks by four?

::: model
Within one step, Euler's method follows the tangent line, and the curve departs from its tangent by an amount proportional to $h^2$, so each step adds an error of order $h^2$. Halving $h$ cuts that per-step error by four, but it also doubles the number of steps needed to cover the same span. The errors accumulate over all $T/h$ steps, so the total is about $(T/h) \times h^2 = Th$, proportional to $h$. Halving the step therefore only halves the final error. Methods that match the curve's bending within each step, like the midpoint method or Runge–Kutta, make the per-step error a higher power of $h$ and so improve much faster as the step shrinks.
:::
:::

::: practice

::: check
given: y0 = 0..10; yinf = 0..10; tau = 0.1..10; h = 0.001..0.5
answer: y0 + h*(yinf - y0)/tau
tolerance: 0.5%

## One Euler step: $h$ = {h}, $y' = (\given{yinf} - y)/\given{tau}$, from {y0}?

::: misses
- [any] $y_0 + h(y_\infty - y_0)/\tau$.
:::
:::

::: check
given: e = 0.0001..1
answer: e/2
tolerance: 0.5%

## Euler error {e}; halve the step?

::: misses
- [any] First order: it halves.
:::
:::
:::
