---
title: "Lab: numerical methods for circuits"
heading: Solving, integrating and stepping circuits, and knowing when to trust the answer
eyebrow: A4 · Lesson 43 · Lab: numerical methods for circuits
xp: 60
---

::: hook
A circuit simulator is lessons 36 to 42 bolted together: complex numbers for AC, Newton's method for diodes and transistors, stamped matrices for the network, integration for energy and charge, and time stepping for transients. Each piece can fail in its own way: Newton can wander, a step can be too big, a sum can miss half its area. This lab runs each one on a circuit with a known answer, so you can see it work, and sees one of them fail and fixes it.
:::

::: predict
## Newton's method solves a 1 kΩ resistor and a silicon diode across 5 V, iterating on the diode voltage from a guess of 0.6 V. The answer is 0.692 V. About how many steps does it take?

- [ ] 3 or 4, as Newton usually does
- [x] About 30
- [ ] It never converges
- [ ] 1, because 0.6 V is so close

::: reveal
About 30: 32 steps to twelve digits. The diode's current grows as $e^{V/V_T}$, so at 0.6 V the curve is nearly flat and the tangent line overshoots to 1.36 V. From there each step only comes back by about $V_T$ = 26 mV, because the exponential is so steep. Newton's fast convergence only starts once it's close. Limiting each step to a couple of $V_T$, or solving for the current instead, cuts this to a handful of steps.
:::
:::

::: nameit
## The tools, and how each one fails

| Tool | Use | Watch for |
|---|---|---|
| Newton's method | nonlinear parts: diodes, transistors | overshoot on exponentials; limit steps or change variables |
| Stamped matrices, `np.linalg.solve` | the network, DC or AC | a floating node makes the matrix singular |
| Complex arithmetic | AC steady state, $Z_C = 1/(j\omega C)$ | forgetting the `1j` turns a reactance into a resistance |
| Trapezoid rule | charge, energy, averages | too few points on a fast decay |
| RK4 stepping | transients | a step too long for the fastest time constant |

## Checking without knowing the answer

- **Residuals:** put the answer back into the equation it should satisfy.
- **Step halving:** run again with half the step; if the answer barely changes, the step was small enough. For a method of order $p$ the change is $2^p - 1$ times the remaining error.
- **A second method:** bisection after Newton, an exact formula on a simpler case, energy conservation.
:::

::: example
## Solve a 1 kΩ resistor and a diode ($I_s = 10^{-14}$ A, $V_T$ = 25.85 mV) across 5 V three ways: Newton on the diode voltage from 0.6 V, the same with each step limited to $2V_T$, and Newton on the current using $V_s = IR + V_T\ln(I/I_s + 1)$.

::: solution
1. **Write the equation and its slope.** `f` is the diode current minus the resistor current, zero at the answer, and `g` is the same circuit written for the current.
2. **Run the three versions.** Plain Newton on the voltage, the same with each step limited to $2V_T$, and Newton on the current.

```python
import math
Is, VT, Vs, R = 1e-14, 0.02585, 5.0, 1e3
f = lambda v: Is * (math.exp(v / VT) - 1) - (Vs - v) / R
df = lambda v: Is / VT * math.exp(v / VT) + 1 / R

def newton_v(v, limit=None):
    for k in range(200):
        step = f(v) / df(v)
        if limit and abs(step) > limit:
            step = math.copysign(limit, step)
        v -= step
        if abs(step) < 1e-12:
            return v, k + 1

print(newton_v(0.6))             # (0.69249, 32)
print(newton_v(0.6, 2 * VT))     # (0.69249, 7)

g = lambda I: I * R + VT * math.log(I / Is + 1) - Vs
dg = lambda I: R + VT / (I + Is)
I = Vs / R
for n in range(1, 50):
    step = g(I) / dg(I)
    I -= step
    if abs(step) < 1e-15:
        break
print(I, n)                      # 0.0043075, 4
```

3. **Compare the results.** All three land on 0.69249 V and 4.3075 mA.
4. **Compare the step counts.** Plain Newton takes 32 steps, limiting the step to $2V_T$ takes 7, and solving for the current takes 4.
5. **Why the current form is quickest.** In terms of current the equation is gentle: a logarithm instead of an exponential. SPICE limits its junction steps for exactly this reason.

**Answer:** all three give 0.69249 V and 4.3075 mA, in 32, 7 and 4 steps.
:::
:::

::: example
## A 1 kΩ resistor feeds a 100 nF capacitor, loaded by 10 kΩ, from 1 V at 1 kHz. Find the output by complex nodal analysis and check it against the impedance formula.

::: solution
1. **Turn the source into a Norton current.** The source becomes a current of $1\text{ V}/1\text{ k}\Omega$ in parallel with the 1 kΩ, leaving one node.
2. **Stamp the capacitor like a conductance.** It adds $j\omega C$ to the node's 1 kΩ and 10 kΩ conductances.

```python
import numpy as np
w = 2 * np.pi * 1e3
G = np.array([[1 / 1e3 + 1j * w * 100e-9 + 1 / 10e3]])
i = np.array([1 / 1e3])          # the source and 1 kΩ, as a Norton current
v = np.linalg.solve(G, i)[0]
print(abs(v), np.degrees(np.angle(v)))    # 0.7894, -29.73
```

3. **Read the output.**
   $$\begin{aligned} v &= 0.6855 - j0.3915\ \text{V} \\ &= 0.789\ \text{V} \angle -29.7° \end{aligned}$$
4. **Check with the divider formula.** $Z_p/(R + Z_p)$, with $Z_p$ the capacitor in parallel with the load, gives the same number, so the stamping is right.

**Answer:** the output is 0.789 V at −29.7°.
:::
:::

::: check
kind: python
given: Vs = 3 | 5 | 12; R = 220 | 1000 | 10000

## A resistor `R` = {R} Ω and a diode ($I_s = 10^{-14}$ A, $V_T$ = 0.02585 V) are in series across `Vs` = {Vs} V. Write `newton_v(v0, limit=None)` from the first example, returning `(v, steps)`. Set `plain = newton_v(0.6)`, `limited = newton_v(0.6, 2 * VT)`, and `I` to the diode current from the limited answer.

```python starter
import math
Is, VT = 1e-14, 0.02585
def newton_v(v0, limit=None):
    return v0, 0

plain = newton_v(0.6)
limited = newton_v(0.6, 2 * VT)
I = 0
print(plain, limited, I)
```

```python solution
import math
Is, VT = 1e-14, 0.02585
f = lambda v: Is * (math.exp(v / VT) - 1) - (Vs - v) / R
df = lambda v: Is / VT * math.exp(v / VT) + 1 / R

def newton_v(v0, limit=None):
    v = v0
    for k in range(500):
        step = f(v) / df(v)
        if limit and abs(step) > limit:
            step = math.copysign(limit, step)
        v -= step
        if abs(step) < 1e-12:
            return v, k + 1

plain = newton_v(0.6)
limited = newton_v(0.6, 2 * VT)
I = (Vs - limited[0]) / R
print(plain, limited, I)
```

```python tests
import math
lo, hi = 0.0, Vs
for _ in range(200):
    m = (lo + hi) / 2
    if 1e-14 * (math.exp(m / 0.02585) - 1) > (Vs - m) / R: hi = m
    else: lo = m
vd = (lo + hi) / 2
assert abs(plain[0] - vd) < 1e-9 and abs(limited[0] - vd) < 1e-9, f"Both should reach the diode voltage {vd:.6f} V (checked by bisection)."
assert limited[1] <= plain[1], "Limiting the step should never take more steps than plain Newton from 0.6 V here."
assert abs(I - (Vs - vd) / R) < 1e-12, "I is (Vs - v)/R."
```

::: right
Right. Bisection, slow but sure, confirms the answer independently. The step limit doesn't change where Newton ends up, only how directly it gets there: with a small current the first step is already short and the limit never acts, but at tens of milliamps it saves dozens of steps.
:::
:::

::: check
kind: python
given: C = 1 | 10 | 100; V0 = 5 | 12; n = 10 | 40 | 160

## A `C` = {C} µF capacitor charged to `V0` = {V0} V discharges through 1 kΩ. Integrate the power $v^2/R$ from 0 to $5\tau$ with the trapezoid rule on `n` = {n} intervals, and set `E_trap`, `E_exact` (the exact integral over the same interval, $\frac12CV_0^2(1 - e^{-10})$) and `rel` to the relative error.

```python starter
import numpy as np
E_trap = 0.5 * C * 1e-6 * V0**2
E_exact = E_trap
rel = 0
print(E_trap, E_exact, rel)
```

```python solution
import numpy as np
Cf, R = C * 1e-6, 1e3
tau = R * Cf
t = np.linspace(0, 5 * tau, n + 1)
p = (V0 * np.exp(-t / tau))**2 / R
h = t[1] - t[0]
E_trap = h * (p[0] / 2 + p[1:-1].sum() + p[-1] / 2)
E_exact = 0.5 * Cf * V0**2 * (1 - np.exp(-10))
rel = abs(E_trap - E_exact) / E_exact
print(E_trap, E_exact, rel)
```

```python tests
import numpy as np
Cf = C * 1e-6; tau = 1e3 * Cf
tt = np.linspace(0, 5 * tau, n + 1); pp = (V0 * np.exp(-tt / tau))**2 / 1e3; hh = tt[1] - tt[0]
Et = hh * (pp[0] / 2 + pp[1:-1].sum() + pp[-1] / 2)
Ee = 0.5 * Cf * V0**2 * (1 - np.exp(-10))
assert abs(E_trap - Et) < 1e-12 * Ee, "Use the trapezoid rule on n intervals of the power V0² e^(-2t/τ)/R."
assert abs(E_exact - Ee) < 1e-15 * Ee and abs(rel - abs(Et - Ee) / Ee) < 1e-12, "E_exact is ½CV0²(1 - e^-10)."
```

::: right
Right. The power decays twice as fast as the voltage, with time constant $\tau/2$, so a coarse grid overestimates it badly at the start. Quadrupling $n$ cuts the error by about 16, the trapezoid rule's $h^2$ behavior.
:::
:::

::: check
kind: python
given: tau = 0.5 | 1 | 2; tol = 1e-6 | 1e-9

## Integrate $dv/dt = (1 - v)/\tau$ from $v = 0$ to $t = 5$ with RK4 (`tau` = {tau}), starting with 5 steps and doubling the number until two successive answers differ by less than `tol` = {tol}. Set `n` to the final number of steps, `v_end` to that answer, and `err` to its true error against $1 - e^{-5/\tau}$.

```python starter
import math
n = 5
v_end = 1 - math.exp(-5 / tau)
err = 0
print(n, v_end, err)
```

```python solution
import math
def run(n):
    h, v = 5 / n, 0.0
    f = lambda v: (1 - v) / tau
    for _ in range(n):
        k1 = f(v); k2 = f(v + h / 2 * k1); k3 = f(v + h / 2 * k2); k4 = f(v + h * k3)
        v += h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
    return v

n, prev = 5, run(5)
while True:
    cur = run(2 * n)
    n *= 2
    if abs(cur - prev) < tol:
        break
    prev = cur
v_end = cur
err = abs(v_end - (1 - math.exp(-5 / tau)))
print(n, v_end, err)
```

```python tests
import math
def rr(m):
    h, v = 5 / m, 0.0
    for _ in range(m):
        k1 = (1 - v) / tau; k2 = (1 - (v + h / 2 * k1)) / tau; k3 = (1 - (v + h / 2 * k2)) / tau; k4 = (1 - (v + h * k3)) / tau
        v += h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
    return v
m, p = 5, rr(5)
while True:
    c = rr(2 * m); m *= 2
    if abs(c - p) < tol: break
    p = c
assert n == m and abs(v_end - c) < 1e-15, f"Doubling from 5 steps, the answers first agree within {tol} at n = {m}."
assert err < tol, "The true error should be smaller than the tolerance the doubling test used."
```

::: right
Right. The change between successive answers is about 15 times the finer one's error for a fourth-order method, so stopping when the change is under the tolerance leaves the true error well under it too.
:::
:::

::: check
kind: python
given: R1 = 1k | 2.2k; R2 = 1k | 4.7k; C1 = 10 | 47; C2 = 10 | 22; f = 300 | 1000 | 3000

## An RC ladder has `R1` = {R1} Ω from a 1 V source to node 1, `C1` = {C1} nF from node 1 to ground, `R2` = {R2} Ω from node 1 to node 2 and `C2` = {C2} nF from node 2 to ground. At `f` = {f} Hz, build the 2 × 2 complex nodal matrix (the source through R1 as a Norton current into node 1) and set `v2` to the complex voltage at node 2. Then set `formula` to $1/\left(1 + j\omega(R_1C_1 + R_2C_2 + R_1C_2) - \omega^2R_1R_2C_1C_2\right)$ to compare.

```python starter
import numpy as np
w = 2 * np.pi * f
v2 = 0
formula = 0
print(v2, formula)
```

```python solution
import numpy as np
w = 2 * np.pi * f
c1, c2 = C1 * 1e-9, C2 * 1e-9
G = np.array([[1 / R1 + 1j * w * c1 + 1 / R2, -1 / R2],
              [-1 / R2, 1 / R2 + 1j * w * c2]])
i = np.array([1 / R1, 0])
v2 = np.linalg.solve(G, i)[1]
formula = 1 / (1 + 1j * w * (R1 * c1 + R2 * c2 + R1 * c2) - w**2 * R1 * R2 * c1 * c2)
print(v2, formula)
```

```python tests
import numpy as np
w = 2 * np.pi * f; a, b = C1 * 1e-9, C2 * 1e-9
F = 1 / (1 + 1j * w * (R1 * a + R2 * b + R1 * b) - w**2 * R1 * R2 * a * b)
assert abs(formula - F) < 1e-12, "formula is 1/(1 + jω(R1C1 + R2C2 + R1C2) - ω²R1R2C1C2)."
assert isinstance(v2, complex) or np.iscomplexobj(v2), "v2 should be complex: the capacitors stamp jωC."
assert abs(v2 - F) < 1e-12, "The nodal answer should match the formula. Each capacitor adds jωC to its node's diagonal entry."
```

::: right
Right. The capacitors stamp $j\omega C$ on the diagonal exactly as resistors stamp $1/R$, and the solved node voltage matches the ladder's transfer function to rounding error, phase and all.
:::
:::

::: check
kind: python
given: V = 5 | 3.3; T = 1 | 2 | 4; tau = 0.5 | 1

## A square wave switching between 0 and `V` = {V} V with period `T` = {T} ms and 50% duty drives an RC with `tau` = {tau} ms. Step it exactly, $v \leftarrow u + (v - u)e^{-\Delta t/\tau}$ with $u$ the input, using 1000 steps per period, for 40 periods from 0 V. Over the last period, set `vpp` to the capacitor voltage's peak-to-peak, and `exact` to $V\tanh\left(T/(4\tau)\right)$.

```python starter
import math
vpp = V
exact = 0
print(vpp, exact)
```

```python solution
import math
steps = 1000
dt = T / steps
a = math.exp(-dt / tau)
v, last = 0.0, []
for p in range(40):
    for s in range(steps):
        u = V if s < steps // 2 else 0.0
        v = u + (v - u) * a
        if p == 39:
            last.append(v)
vpp = max(last) - min(last)
exact = V * math.tanh(T / (4 * tau))
print(vpp, exact)
```

```python tests
import math
E = V * math.tanh(T / (4 * tau))
assert abs(exact - E) < 1e-12, "exact is V·tanh(T/(4τ))."
assert abs(vpp - E) < 1e-9 * V, f"The settled ripple should be {E:.6f} V. Use the exact update with u = V for the first half of each period and 0 for the second."
```

::: right
Right. Because each step uses the exact solution for a constant input, there's no step-size error at all: the ripple matches $V\tanh(T/4\tau)$ to rounding. When the input is piecewise constant, an exact update beats any general-purpose integrator.
:::
:::

::: check
given: e0 = 2 | 5 | 8; m = 2 | 4 | 10
answer: e0*1e-6/m^4
tolerance: 1%

## An RK4 simulation has an error of {e0} × 10⁻⁶ with some step. What error should it have with the step {m} times smaller?

::: right
Right. RK4 is fourth order, so dividing the step by {m} divides the error by {m}⁴: {answer}.
:::

::: misses
- [e0*1e-6/m] That's first order, like Euler's method. RK4's error goes as $h^4$.
- [e0*1e-6/m^2] That's second order, like the trapezoid rule. RK4's error goes as $h^4$.
- [any] Not yet. Divide the error by the step ratio raised to the method's order, 4.
:::
:::

::: explain
## Newton's method converges in a handful of steps on most problems but took 32 on the diode. What is it about the diode's equation that slows it down, and why does solving for the current instead fix it?

::: model
Newton replaces the function by its tangent line and jumps to where the tangent crosses zero. The diode's current is exponential in its voltage, so at a voltage below the answer the curve is nearly flat and the tangent shoots far past it, to 1.36 V; up there the curve is so steep that each new tangent only reaches back about one thermal voltage, so the return takes dozens of steps. Written in terms of current, the diode voltage is a logarithm, a gently curving function whose tangent is a good guide everywhere, so Newton takes the direct route. The answer is the same; only the shape of the function Newton walks along changes.
:::
:::
