---
title: Stepping a system through time
heading: Simulating a circuit one small step at a time
eyebrow: A4 · Lesson 41 · Stepping through time
xp: 40
---

::: hook
A capacitor charging through a resistor has a neat formula. Add a diode, a temperature-dependent part or a second capacitor, and the formula is gone. Simulators don't need one: they know the *rate* at which things change right now, take a small step, and repeat. That's the whole idea behind every circuit simulator, and you can write one in five lines.
:::

::: predict
## A simulation of a capacitor charging takes steps much longer than its time constant: three times as long. What does it produce?

- [ ] A slightly less accurate curve
- [ ] The exact curve
- [x] Nonsense that swings back and forth and grows
- [ ] A straight line

::: reveal
Nonsense. With huge steps, each step overshoots the final voltage by more than it started out missing it, so the error flips sign and grows every step. For this simple method, steps longer than twice the time constant are unstable. It's the first lesson every simulator author learns: the step has to be small compared with the fastest thing happening.
:::
:::

::: nameit
## Euler's method

A capacitor $C$ charging from a source $V_s$ through $R$ obeys

$$\frac{dv}{dt} = \frac{V_s - v}{RC}$$

The rate of change is known from where you are now: big when $v$ is far from $V_s$, small as it gets close. **Euler's method** pretends that rate stays fixed for a short time $\Delta t$:

$$v_{k+1} = v_k + \Delta t \cdot \frac{V_s - v_k}{RC}$$

In code:

```
import numpy as np
tau, Vs, dt, N = 1e-3, 5.0, 1e-5, 500
v = np.zeros(N + 1)            # v[0] = 0, the starting voltage
for k in range(N):
    v[k + 1] = v[k] + dt * (Vs - v[k]) / tau
t = dt * np.arange(N + 1)
```

`for k in range(N):` repeats the indented line with k = 0, 1, ..., N − 1.

**How accurate?** Each step uses the rate at the start of the step, which is a little too high for a charging capacitor, so Euler runs slightly ahead of the true curve. The error shrinks in proportion to $\Delta t$: halve the step and the error halves. That makes Euler a **first-order** method. Real simulators use higher-order methods, where halving the step cuts the error 16 times or more, and pick the step size automatically.

**How stable?** For this equation, Euler's update multiplies the gap $V_s - v$ by $(1 - \Delta t/\tau)$ every step. If $\Delta t > 2\tau$, that factor is less than −1, and the gap grows while flipping sign. Hence the rule: keep the step well below the fastest time constant.
:::

::: example
## Take three Euler steps of $dv/dt = (1 - v)/\tau$ from $v = 0$, with $\tau = 1$ and $\Delta t = 0.1$, by hand and in code.

::: solution
1. **Write the Euler step.** Each step adds $\Delta t \times (1 - v)$.
2. **Step by hand.**
   $$\begin{aligned} v_1 &= 0 + 0.1 \times 1 \\ &= 0.1 \\ v_2 &= 0.1 + 0.1 \times 0.9 \\ &= 0.19 \\ v_3 &= 0.19 + 0.1 \times 0.81 \\ &= 0.271 \end{aligned}$$
3. **Step in code.**

```
v = 0.0
for k in range(3):
    v = v + 0.1 * (1 - v)
print(v)      # 0.271
```

4. **Compare with the exact value.**
   $$\begin{aligned} v(0.3) &= 1 - e^{-0.3} \\ &= 0.259 \end{aligned}$$
   Euler overshoots by 0.012 here, an error that halves when the step halves.

**Answer:** three steps give 0.1, 0.19 and 0.271, by hand and in code, against the exact 0.259.
:::
:::

::: example
## What happens to Euler's method on $dv/dt = -v/\tau$ with $\Delta t = 3\tau$?

::: solution
1. **Find the factor per step.** Each step multiplies $v$ by
   $$\begin{aligned} 1 - \frac{\Delta t}{\tau} &= 1 - 3 \\ &= -2 \end{aligned}$$
2. **Run it from 1.** The values go −2, 4, −8, ...: the "simulation" explodes while the real voltage decays to zero.
3. **Know the limits.** Euler's method on this equation is only stable for $\Delta t < 2\tau$, and only accurate for $\Delta t$ much smaller than $\tau$.

**Answer:** the simulation blows up, flipping sign and doubling every step, because $\Delta t = 3\tau$ is past the stability limit of $2\tau$.
:::
:::

::: check
kind: python
given: Vs = 3..12 int; tau = 1..5 int

## Simulate a capacitor charging toward $V_s$ = {Vs} V from 0 V, with $\tau$ = {tau} ms, using Euler's method with $\Delta t$ = 0.01 ms for 1000 steps. Store the voltages in `v` (1001 values, starting at 0).

`Vs` and `tau` (in ms) are already defined. Work in milliseconds throughout.

```python starter
import numpy as np

dt = 0.01        # ms
N = 1000
v = np.zeros(N + 1)
for k in range(N):
    v[k + 1] = v[k]   # replace: one Euler step
print(v[-1])
```

```python solution
import numpy as np

dt = 0.01
N = 1000
v = np.zeros(N + 1)
for k in range(N):
    v[k + 1] = v[k] + dt * (Vs - v[k]) / tau
print(v[-1])
```

```python tests
import numpy as np
w = np.zeros(1001)
for k in range(1000):
    w[k + 1] = w[k] + 0.01 * (Vs - w[k]) / tau
assert np.shape(v) == (1001,), "v should hold 1001 values, from step 0 to step 1000."
assert abs(v[0]) < 1e-12, "Start from 0 V: v[0] should be 0."
assert np.allclose(v, w), "Each step should add dt·(Vs − v[k])/tau to v[k]."
exact = Vs * (1 - np.exp(-0.01 * np.arange(1001) / tau))
assert np.max(np.abs(v - exact)) < 0.02 * Vs, "Euler should stay close to the exact curve with steps this small."
```

::: right
Right. Five lines, and you have a working simulator for this circuit.
:::
:::

::: check
kind: python
given: tau = 1..5 int

## Measure Euler's error. Run the discharge $dv/dt = -v/\tau$ from 1 V over $5\tau$ twice, with $\Delta t = \tau/20$ and $\Delta t = \tau/40$. Set `err1` and `err2` to each run's largest error against the exact $e^{-t/\tau}$, and `ratio` to `err1 / err2`.

```python starter
import numpy as np

def run(dt):
    n = int(round(5 * tau / dt))
    v = np.zeros(n + 1)
    v[0] = 1.0
    for k in range(n):
        v[k + 1] = v[k] - dt * v[k] / tau
    t = dt * np.arange(n + 1)
    return 0   # replace: the largest error against np.exp(-t / tau)

err1 = run(tau / 20)
err2 = run(tau / 40)
ratio = 0
print(err1, err2, ratio)
```

```python solution
import numpy as np

def run(dt):
    n = int(round(5 * tau / dt))
    v = np.zeros(n + 1)
    v[0] = 1.0
    for k in range(n):
        v[k + 1] = v[k] - dt * v[k] / tau
    t = dt * np.arange(n + 1)
    return np.max(np.abs(v - np.exp(-t / tau)))

err1 = run(tau / 20)
err2 = run(tau / 40)
ratio = err1 / err2
print(err1, err2, ratio)
```

```python tests
assert err1 > err2 > 0, "The smaller step should give a smaller, nonzero error."
assert abs(ratio - err1 / err2) < 1e-12, "ratio should be err1 / err2."
assert 1.8 < ratio < 2.2, f"For a first-order method, halving the step should roughly halve the error; your ratio is {ratio:.3f}."
```

::: right
Right. A ratio near 2: halving the step halves the error, the signature of a first-order method.
:::
:::

::: check
kind: choice

## Euler's method steps a discharge $dv/dt = -v/\tau$ with $\Delta t = 3\tau$. What does each step multiply the voltage by?

- [ ] 3
- [x] −2
- [ ] $e^{-3}$
- [ ] 0.25

::: right
Right. $v_{k+1} = v_k(1 - \Delta t/\tau) = v_k(1 - 3) = -2v_k$: the voltage flips sign and doubles every step. That's the instability.
:::

::: misses
- [1] The update is $v_k(1 - \Delta t/\tau)$. Put $\Delta t/\tau = 3$ in.
- [3] That's the exact factor over a time of $3\tau$. Euler's straight-line step gets it badly wrong.
- [4] Work out $1 - \Delta t/\tau$ with $\Delta t = 3\tau$.
:::
:::

::: check
kind: python
given: V = 5 | 12; R = 10 | 47 | 100; L = 1 | 10

## An inductor `L` = {L} mH in series with `R` = {R} Ω is switched onto `V` = {V} V at $t = 0$, so $di/dt = (V - Ri)/L$. Step it with Euler's method from $i = 0$ for 5 time constants ($\tau = L/R$), with $\Delta t = \tau/100$. Set `i_end` to the final current and `err` to its difference from the exact $\frac{V}{R}(1 - e^{-5})$.

```python starter
import math
Lh = L * 1e-3
tau = Lh / R
dt = tau / 100
i = 0.0
for k in range(500):
    i = i + dt * (V - R * i)
i_end = i
err = 0
print(i_end, err)
```

```python solution
import math
Lh = L * 1e-3
tau = Lh / R
dt = tau / 100
i = 0.0
for k in range(500):
    i = i + dt * (V - R * i) / Lh
i_end = i
err = abs(i_end - V / R * (1 - math.exp(-5)))
print(i_end, err)
```

```python tests
import math
Lh = L * 1e-3
tau = Lh / R
w = 0.0
for _ in range(500):
    w += tau / 100 * (V - R * w) / Lh
assert abs(i_end - w) < 1e-12 * V / R, f"i_end should be {w:.6g} A. The slope is (V - R*i)/L, with L in henries."
assert abs(err - abs(w - V / R * (1 - math.exp(-5)))) < 1e-15 * V / R + 1e-15, "err is abs(i_end - V/R*(1 - exp(-5)))."
assert err < 0.002 * V / R, "With 100 steps per time constant Euler should be within a fraction of a percent."
```

::: right
Right. It's the capacitor's equation in disguise: the current rises toward $V/R$ with $\tau = L/R$. Dividing by $L$ in henries is the step that's easy to miss.
:::
:::

::: check
kind: python

## Euler's method on $dv/dt = -v/\tau$ multiplies $v$ by $1 - r$ each step, with $r = \Delta t/\tau$. For each `r` in the starter's list, run 60 steps from $v = 1$. Set `decays` to a list of booleans saying whether $|v|$ ended below 1, and `flips` to a list saying whether $v$ changed sign on the first step.

```python starter
rs = [0.5, 1.5, 1.9, 2.1, 3.0]
decays = []
flips = []
for r in rs:
    v = 1.0
    for k in range(60):
        v = v * r
    decays.append(v < 1)
    flips.append(False)
print(decays, flips)
```

```python solution
rs = [0.5, 1.5, 1.9, 2.1, 3.0]
decays = []
flips = []
for r in rs:
    v = 1.0
    first = 1.0 - r
    for k in range(60):
        v = v * (1 - r)
    decays.append(abs(v) < 1)
    flips.append(first < 0)
print(decays, flips)
```

```python tests
assert decays == [True, True, True, False, False], "Euler decays only while |1 - r| < 1, that is for 0 < r < 2."
assert flips == [False, True, True, True, True], "The voltage flips sign every step once r > 1, since 1 - r is negative."
```

::: right
Right. Between $r = 1$ and $2$ the answer still decays but flips sign every step, which no real capacitor does; above $r = 2$ it grows without bound. A stable-looking result isn't necessarily a right one.
:::
:::

::: check
given: r = 0.1 | 0.5 | 1.5 | 2.5; n = 3 | 4
answer: (1 - r)^n
tolerance: 1%

## Euler's method steps $dv/dt = -v/\tau$ from $v = 1$ V with $\Delta t = \given{r}\tau$. What is $v$ after {n} steps?

::: right
Right. Each step multiplies by $1 - \given{r}$, so after {n} steps $v = (1 - \given{r})^{\given{n}}$ = {answer} V. The exact answer, $e^{-\given{r} \cdot \given{n}}$, is always positive.
:::

::: misses
- [exp(-r*n)] That's the exact solution. Euler multiplies by $1 - \given{r}$ each step instead.
- [1 - r*n] That takes one big step of $\given{n}\Delta t$. Euler multiplies by $1 - \given{r}$ at every step.
- [any] Not yet. Multiply 1 V by $(1 - \given{r})$ once for each step.
:::
:::

::: explain
## Why does Euler's method get more accurate as the step gets smaller?

::: model
Euler assumes the rate of change stays at its starting value for the whole step, but the true rate drifts during the step. The shorter the step, the less it can drift, so the straight-line guess stays closer to the real curve. Each step's error shrinks roughly with the square of the step, and there are proportionally more steps, so the total error shrinks in proportion to the step size.
:::
:::

::: practice

::: check
kind: python
given: V0 = 2..9 int; tau = 1..5 int

## Simulate a discharge from {V0} V, $dv/dt = -v/\tau$, $\tau$ = {tau} ms, with $\Delta t$ = 0.05 ms for 400 steps. Set `v` (401 values).

```python starter
import numpy as np

v = np.zeros(401)
print(v[-1])
```

```python solution
import numpy as np

v = np.zeros(401)
v[0] = V0
for k in range(400):
    v[k + 1] = v[k] - 0.05 * v[k] / tau
print(v[-1])
```

```python tests
import numpy as np
w = np.zeros(401); w[0] = V0
for k in range(400):
    w[k + 1] = w[k] - 0.05 * w[k] / tau
assert abs(v[0] - V0) < 1e-12, "Start from V0."
assert np.allclose(v, w), "Each step should subtract dt·v[k]/tau."
```
:::

::: check
kind: python
given: Vs = 5..12 int; tau = 1..4 int; th = 0.5..0.95 sig 2

## Using Euler with $\Delta t$ = 0.001 ms on a capacitor charging toward {Vs} V ($\tau$ = {tau} ms), set `steps` to the number of steps until $v$ first reaches {th} × {Vs} V.

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

```python solution
v, steps = 0.0, 0
while v < th * Vs:
    v += 0.001 * (Vs - v) / tau
    steps += 1
print(steps)
```

```python tests
import math
v, n = 0.0, 0
while v < th * Vs:
    v += 0.001 * (Vs - v) / tau
    n += 1
assert steps == n, f"Count the steps until v first reaches th·Vs (a while loop is natural here). Expected about {n}."
```
:::
:::
