---
title: Transient solver lab
heading: Stepping circuits through time in NumPy, and why step size matters
eyebrow: C2 · Lesson 25 · Transient solver lab
xp: 50
---

::: hook
Every transient sim in this course, and every SPICE run, does the same thing: it starts from the circuit's state and takes small steps through time, using the differential equations of lessons 7 to 17 to decide each step. How it takes those steps matters a great deal. The obvious method can be wrong by a few percent with small steps and explode with large ones, while a slightly different one stays stable at any step. In this lab you'll write three steppers and see both effects.
:::

::: play
- The exact RC charging curve (dashed) and the forward Euler approximation with a time step Δt (dots joined by lines).
- Small steps track the curve closely. Push Δt past τ and Euler overshoots; past 2τ it oscillates with growing swings.
- That instability isn't about accuracy: the exact answer never goes above 5 V, whatever the step.
:::
:::

```sim plot
view: graph
x: t = 0..10 ms
y: v = -2..10 V
slider: tau = 0.5..5 step 0.1 = 1 ms
slider: dt = 0.1..3 step 0.05 = 0.5 ms
plot: 5*(1 - exp(-t/tau)) | label: exact | dashed | color: ch2 | samples: 400
plot: 5*(1 - (1 - dt/tau)^floor(t/dt)) | label: forward Euler | samples: 2000
readout: steps per time constant = tau/dt | digits: 3
readout: Euler's growth factor per step = 1 - dt/tau | digits: 3
```

::: predict
## Forward Euler steps an RC circuit with a time step three times its time constant. What happens?

- [ ] It's less accurate but still settles
- [x] It oscillates with growing swings: it's unstable
- [ ] It settles faster than the real circuit
- [ ] Nothing: step size doesn't matter for a linear circuit

::: reveal
It blows up. Each Euler step multiplies the error by $1 - \Delta t/\tau = -2$, so the error flips sign and doubles every step. Forward Euler is stable only for $\Delta t < 2\tau$. Circuits with both fast and slow parts (stiff circuits) force such tiny steps that simulators use implicit methods instead.
:::
:::

::: nameit
## Forward Euler

Write the circuit as $\frac{dx}{dt} = f(x)$, here $\frac{dv}{dt} = \frac{V - v}{\tau}$ for an RC charging toward $V$. Forward Euler takes the slope at the start of each step:

$$v_{k+1} = v_k + \Delta t\,\frac{V - v_k}{\tau}$$

so $v_k = V\left[1 - (1 - \Delta t/\tau)^k\right]$. Its error per unit time shrinks in proportion to Δt (first order), and it's stable only if $|1 - \Delta t/\tau| < 1$, that is $\Delta t < 2\tau$.

## Backward Euler

Use the slope at the *end* of the step instead, and solve for it:

$$v_{k+1} = v_k + \Delta t\,\frac{V - v_{k+1}}{\tau} \quad\Rightarrow\quad v_{k+1} = \frac{v_k + \Delta tV/\tau}{1 + \Delta t/\tau}$$

The error now shrinks by $\frac{1}{1 + \Delta t/\tau}$ per step, which is less than 1 for any step: unconditionally stable, though still first order. Methods like this, which solve an equation at each step, are **implicit**; circuit simulators use implicit methods (trapezoidal, Gear, SDIRK) for exactly this reason.

## Second order and RK4

An RLC circuit has two state variables, the inductor current $i$ and the capacitor voltage $v$:

$$\frac{di}{dt} = \frac{V - Ri - v}{L} \qquad \frac{dv}{dt} = \frac iC$$

The classical **Runge–Kutta** method (RK4) samples the slope four times per step and combines them; its error shrinks as $\Delta t^4$, so modest steps give very accurate answers.

```python
k1 = f(x); k2 = f(x + dt/2*k1); k3 = f(x + dt/2*k2); k4 = f(x + dt*k3)
x = x + dt/6*(k1 + 2*k2 + 2*k3 + k4)
```
:::

::: example
## Forward Euler charges a 1 kΩ, 1 µF circuit toward 5 V with Δt = 10 µs. What does it give after 100 steps, against the exact 1 ms value?

::: solution
1. **Forward Euler after 100 steps.**
   $$\begin{aligned} v &= 5[1 - (1 - 0.01)^{100}]\ \text{V} \\ &= 3.170\ \text{V} \end{aligned}$$
2. **Exact value at 1 ms.**
   $$\begin{aligned} v &= 5(1 - e^{-1})\ \text{V} \\ &= 3.161\ \text{V} \end{aligned}$$
3. **The error.** Euler is 0.3% high after one time constant, and halving the step roughly halves the error.

**Answer:** forward Euler gives 3.170 V against the exact 3.161 V, 0.3% high.
:::
:::

::: example
## Backward Euler takes the same circuit with Δt = 3 ms, three time constants. What are its first values?

::: solution
1. **The update.** Each step is
   $$v_{k+1} = \frac{v_k + 15}{4}$$
2. **First values.** 3.75, 4.69, 4.92, 4.98 V.
3. **How it behaves.** Crude, but it never overshoots 5 V.
4. **Forward Euler with the same step.** It gives 15, −15, 45, −75 V.

**Answer:** 3.75, 4.69, 4.92 and 4.98 V, closing in on 5 V without overshooting.
:::
:::

::: check
given: dt = 0.5 | 1.5 | 3; tau = 1 | 2
answer: 1 - dt/tau
tolerance: 0.5%

## Forward Euler steps an RC circuit (τ = {tau} ms) with Δt = {dt} ms. By what factor does the error change each step?

::: right
Right. $1 - \Delta t/\tau$ = {answer}.
:::

::: misses
- [1/(1 + dt/tau)] That's backward Euler's factor.
- [any] Not yet. Substitute $v_k = V + e_k$ into the Euler update.
:::
:::

::: check
given: tau = 0.1 | 1 | 47
answer: 2*tau
unit: ms
tolerance: 0.5%

## Above what time step does forward Euler become unstable for an RC with τ = {tau} ms?

::: right
Right. $|1 - \Delta t/\tau| < 1$ needs $\Delta t < 2\tau$ = {answer}.
:::

::: misses
- [tau] At Δt = τ, Euler jumps straight to the final value in one step, which is still stable.
- [any] Not yet. Find where $1 - \Delta t/\tau = -1$.
:::
:::

::: check
given: dt = 0.5 | 3 | 10; tau = 1 | 2
answer: 1/(1 + dt/tau)
tolerance: 0.5%

## Backward Euler steps an RC (τ = {tau} ms) with Δt = {dt} ms. By what factor does the error shrink each step?

::: right
Right. $\frac{1}{1 + \Delta t/\tau}$ = {answer}, always below 1.
:::

::: misses
- [1 - dt/tau] That's forward Euler.
- [any] Not yet. Solve the implicit update for $v_{k+1}$.
:::
:::

::: check
given: V = 5 | 12; k = 10 | 20; r = 0.05 | 0.1
answer: V*(1 - (1 - r)^k)
unit: V
tolerance: 0.1%

## Forward Euler charges toward {V} V from 0 with Δt/τ = {r}. What does it give after {k} steps?

::: right
Right. $V[1 - (1 - \Delta t/\tau)^k]$ = {answer}.
:::

::: misses
- [V*(1 - exp(-k*r))] That's the exact answer; Euler's differs slightly.
- [any] Not yet. Each step multiplies the remaining gap by $1 - \Delta t/\tau$.
:::
:::

::: check
given: e1 = 1 | 4; r = 2 | 10
answer: e1/r^4
tolerance: 0.5%

## RK4's error goes as $\Delta t^4$. An RK4 run has error {e1} mV. What error do you expect with steps {r} times smaller?

::: right
Right. $e/r^4$ = {answer} mV.
:::

::: misses
- [e1/r] That's first order, like Euler.
- [any] Not yet. Fourth order.
:::
:::

::: check
kind: python

## Write `euler_rc(R, C, V, dt, n)` and `backward_rc(R, C, V, dt, n)`: each returns an array of `n + 1` capacitor voltages, starting from 0, for an RC charging toward `V`.

```python starter
import numpy as np

def euler_rc(R, C, V, dt, n):
    t = np.arange(n + 1) * dt
    return V * (1 - np.exp(-t / (R * C)))

def backward_rc(R, C, V, dt, n):
    return euler_rc(R, C, V, dt, n)

print(euler_rc(1e3, 1e-6, 5, 3e-3, 4))
```

```python solution
import numpy as np

def euler_rc(R, C, V, dt, n):
    tau = R * C
    v = np.zeros(n + 1)
    for k in range(n):
        v[k + 1] = v[k] + dt * (V - v[k]) / tau
    return v

def backward_rc(R, C, V, dt, n):
    tau = R * C
    v = np.zeros(n + 1)
    for k in range(n):
        v[k + 1] = (v[k] + dt * V / tau) / (1 + dt / tau)
    return v

print(euler_rc(1e3, 1e-6, 5, 3e-3, 4))
```

```python tests
import numpy as np
v = euler_rc(1e3, 1e-6, 5, 1e-5, 100)
assert len(v) == 101, "Return n + 1 values, starting with v = 0."
assert abs(v[100] - 3.1698382936) < 1e-8, f"After 100 Euler steps of τ/100 the voltage is 3.16984 V; got {v[100]:.5f}."
v = euler_rc(1e3, 1e-6, 5, 3e-3, 4)
assert np.allclose(v, [0, 15, -15, 45, -75]), f"With Δt = 3τ, forward Euler should blow up: 0, 15, -15, 45, -75; got {v}."
v = backward_rc(1e3, 1e-6, 5, 3e-3, 4)
assert np.allclose(v, [0, 3.75, 4.6875, 4.921875, 4.98046875]), f"Backward Euler with Δt = 3τ: 0, 3.75, 4.69, 4.92, 4.98; got {v}."
```

::: right
Right. The starter's exact formula is what you'd want, but a simulator doesn't have one for a general circuit: it has only the update rule.
:::
:::

::: check
kind: python

## Write `rk4_rlc(R, L, C, V, dt, n)`: step a series RLC from rest after a step to `V`, with state `[i, v]`, and return an array of `n + 1` capacitor voltages.

```python starter
import numpy as np

def rk4_rlc(R, L, C, V, dt, n):
    out = np.zeros(n + 1)
    i = v = 0.0
    for k in range(n):
        i += dt * (V - R * i - v) / L
        v += dt * i / C
        out[k + 1] = v
    return out

print(rk4_rlc(373.9, 10e-3, 100e-9, 5, 20e-6, 50).max())
```

```python solution
import numpy as np

def rk4_rlc(R, L, C, V, dt, n):
    def f(x):
        i, v = x
        return np.array([(V - R * i - v) / L, i / C])
    x = np.zeros(2)
    out = np.zeros(n + 1)
    for k in range(n):
        k1 = f(x)
        k2 = f(x + dt / 2 * k1)
        k3 = f(x + dt / 2 * k2)
        k4 = f(x + dt * k3)
        x = x + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
        out[k + 1] = x[1]
    return out

print(rk4_rlc(373.9, 10e-3, 100e-9, 5, 20e-6, 50).max())
```

```python tests
import numpy as np
v = rk4_rlc(373.9, 10e-3, 100e-9, 5, 0.5e-6, 2000)
assert len(v) == 2001, "Return n + 1 voltages."
assert abs(v.max() - 5.5) < 0.005, f"Designed for 10% overshoot, the peak should be 5.50 V; got {v.max():.4f}."
assert abs(v[-1] - 5) < 0.001, f"After 1 ms it should have settled at 5 V; got {v[-1]:.4f}."
v = rk4_rlc(373.9, 10e-3, 100e-9, 5, 20e-6, 50)
assert abs(v.max() - 5.5) < 0.01, f"RK4 should find the peak to within 10 mV even with 20 µs steps; got {v.max():.4f}."
```

::: right
Right. With 20 µs steps, only about 16 per ringing period, RK4 still finds the peak within 2 mV. The semi-implicit Euler starter needs far smaller steps for the same accuracy.
:::
:::

::: explain
## Why does a circuit simulator use an implicit method rather than forward Euler, even though each implicit step costs more?

::: model
Forward Euler is stable only when its time step is shorter than about twice the circuit's fastest time constant. Real circuits mix fast and slow parts, nanosecond parasitics alongside millisecond filters, so forward Euler would need nanosecond steps for the whole simulation even after the fast parts have settled, millions of steps for a millisecond. An implicit method stays stable at any step size, so the simulator can take large steps whenever nothing fast is happening and small ones only where the waveforms change quickly. Solving an equation each step is far cheaper than taking a million tiny steps.
:::
:::

::: practice

::: check
given: T = 1 | 10; dt = 0.01 | 0.1
answer: T/dt
tolerance: 0.5%

## How many steps of {dt} µs cover {T} µs?

::: misses
- [any] $T/\Delta t$.
:::
:::

::: check
given: L = 1 | 10; C = 10 | 100
answer: 2*pi*sqrt(L*1e-3*C*1e-9)*1e6
unit: µs
tolerance: 0.5%

## What is the ringing period of {L} mH with {C} nF, ignoring damping?

::: misses
- [any] $2\pi\sqrt{LC}$.
:::
:::

::: check
given: e1 = 2 | 8; r = 2 | 4
answer: e1/r
tolerance: 0.5%

## A first-order method has error {e1} mV. What error do you expect with steps {r} times smaller?

::: misses
- [any] First order: error ∝ Δt.
:::
:::
:::
