---
title: Problem set 9
heading: "Problem set 9: complex numbers, equations and calculus in code"
eyebrow: A4 · Problem set 9
type: problems
---

::: hook
These labs use lessons 36 to 39: complex numbers in code, solving equations numerically, building circuit equations, and numerical derivatives and integrals. Each one checks a numerical answer against one you can work out by hand, which is the habit that catches most bugs. When a check fails, the hidden test's message says which case went wrong.
:::

::: pool
pick: 5

::: check
kind: python
given: L = 10 | 47; C = 0.1 | 1

## For a series RLC with $R$ = 50 Ω, `L` = {L} mH and `C` = {C} µF, set `f` to 20,001 frequencies spaced evenly in $\log f$ from 10 Hz to 1 MHz (`np.logspace`), `Z` to the complex impedances there, `f_min` to the frequency where $|Z|$ is smallest, and `f0` to $1/(2\pi\sqrt{LC})$.

```python starter
import numpy as np

f = np.array([1.0])
Z = np.array([0j])
f_min = 0
f0 = 0
print(f_min, f0)
```

```python solution
import numpy as np

f = np.logspace(1, 6, 20001)
w = 2 * np.pi * f
Z = 50 + 1j * w * L * 1e-3 + 1 / (1j * w * C * 1e-6)
f_min = f[np.argmin(np.abs(Z))]
f0 = 1 / (2 * np.pi * np.sqrt(L * 1e-3 * C * 1e-6))
print(f_min, f0)
```

```python tests
import numpy as np
assert len(f) == 20001 and np.isclose(f[0], 10) and np.isclose(f[-1], 1e6), "f should run from 10 Hz to 1 MHz in 20,001 log-spaced points."
assert np.isclose(abs(Z[np.argmin(np.abs(f - f0))]), 50, rtol=1e-3), "At resonance |Z| should be close to R = 50 ohms."
assert abs(np.log10(f_min / f0)) < 5 / 20000, f"f_min should be the grid point nearest resonance, {f0:.1f} Hz; got {f_min:.1f} Hz."
```
:::

::: check
kind: python
given: R = 1 | 4.7; C = 10 | 100; ph = 30 | 60 | 80

## An RC low-pass ($R$ = {R} kΩ, $C$ = {C} nF) shifts the phase by $-\arctan(2\pi fRC)$. Write `bisect(g, a, b)` (60 halvings), use it to set `f` to the frequency where the phase is $-\given{ph}°$, and set `f_formula` to the exact answer from $\tan$.

```python starter
import math

def bisect(g, a, b):
    return (a + b) / 2

f = 0
f_formula = 0
print(f, f_formula)
```

```python solution
import math

def bisect(g, a, b):
    ga = g(a)
    for _ in range(60):
        m = (a + b) / 2
        gm = g(m)
        if ga * gm <= 0:
            b = m
        else:
            a, ga = m, gm
    return (a + b) / 2

tau = R * 1e3 * C * 1e-9
phase = lambda f: -math.degrees(math.atan(2 * math.pi * f * tau))
f = bisect(lambda f: phase(f) + ph, 0, 100 / tau)
f_formula = math.tan(math.radians(ph)) / (2 * math.pi * tau)
print(f, f_formula)
```

```python tests
import math
tau = R * 1e3 * C * 1e-9
want = math.tan(math.radians(ph)) / (2 * math.pi * tau)
assert math.isclose(f_formula, want), "f_formula should be tan(ph) / (2 pi R C)."
assert math.isclose(f, want, rel_tol=1e-9), f"Bisection should find {want:.3f} Hz; got {f}."
assert math.isclose(bisect(lambda x: x * x - 2, 0, 2), math.sqrt(2), rel_tol=1e-12), "bisect should find the square root of 2 on [0, 2]."
```
:::

::: check
kind: python
given: f = 50 | 200 | 1000

## A sine $v = \sin(2\pi ft)$ with `f` = {f} Hz is sampled with step `h`. Write `central(v, h)` returning the central-difference derivative at the interior samples, `(v[2:] - v[:-2]) / (2*h)`. Set `err1` and `err2` to the largest error against the exact derivative with 100 and 200 samples per cycle, and `ratio = err1 / err2`.

```python starter
import numpy as np

def central(v, h):
    return np.diff(v) / h

err1 = err2 = ratio = 0
print(err1, err2, ratio)
```

```python solution
import numpy as np

def central(v, h):
    return (v[2:] - v[:-2]) / (2 * h)

def max_err(n):
    h = 1 / (f * n)
    t = np.arange(0, 2 / f, h)
    d = central(np.sin(2 * np.pi * f * t), h)
    return np.max(np.abs(d - 2 * np.pi * f * np.cos(2 * np.pi * f * t[1:-1])))

err1 = max_err(100)
err2 = max_err(200)
ratio = err1 / err2
print(err1, err2, ratio)
```

```python tests
import numpy as np
h = 1e-3
t = np.arange(0, 1, h)
assert np.allclose(central(t**2, h), 2 * t[1:-1]), "Central differences are exact for a parabola: the derivative of t^2 is 2t."
assert abs(ratio - 4) < 0.05, f"Halving the step should cut the error by about 4, since it goes as h^2; got {ratio}."
assert np.isclose(err1, 2 * np.pi * f * (2 * np.pi / 100)**2 / 6, rtol=0.01), "err1 should match the h^2 error estimate, w (w h)^2 / 6."
```
:::

::: check
kind: python
given: Vp = 5 | 10 | 170

## A half-wave rectified sine is $v = \max(V_p\sin\theta, 0)$. Over one cycle, sampled at 10,001 points from 0 to $2\pi$, set `rms_num` to its RMS by the trapezoid rule (written with slices), `rms_exact` to $V_p/2$, and `avg` to its average value by the same rule.

```python starter
import numpy as np

rms_num = rms_exact = avg = 0
print(rms_num, rms_exact, avg)
```

```python solution
import numpy as np

th = np.linspace(0, 2 * np.pi, 10001)
v = np.maximum(Vp * np.sin(th), 0)

def trap(y, x):
    return np.sum((y[1:] + y[:-1]) / 2 * np.diff(x))

rms_num = np.sqrt(trap(v**2, th) / (2 * np.pi))
rms_exact = Vp / 2
avg = trap(v, th) / (2 * np.pi)
print(rms_num, rms_exact, avg)
```

```python tests
import numpy as np
assert np.isclose(rms_exact, Vp / 2), "The RMS of a half-wave rectified sine is Vp / 2."
assert abs(rms_num - Vp / 2) / (Vp / 2) < 1e-6, f"The trapezoid RMS should match Vp / 2 closely; got {rms_num}."
assert abs(avg - Vp / np.pi) / (Vp / np.pi) < 1e-6, f"The average of a half-wave rectified sine is Vp / pi; got {avg}."
```
:::

::: check
kind: python
given: R = 20 | 100 | 2000; L = 10; C = 1

## A series RLC circuit with $R$ = {R} Ω, $L$ = {L} mH and $C$ = {C} µF has the characteristic polynomial $s^2 + (R/L)s + 1/(LC)$. Set `roots` to its roots with `np.roots`, `kind` to `"under"`, `"critical"` or `"over"` (underdamped if the roots are complex), and `zeta` to $\frac{R}{2}\sqrt{C/L}$.

```python starter
import numpy as np

roots = np.array([])
kind = ""
zeta = 0
print(roots, kind, zeta)
```

```python solution
import numpy as np

Lh, Cf = L * 1e-3, C * 1e-6
roots = np.roots([1, R / Lh, 1 / (Lh * Cf)])
zeta = R / 2 * np.sqrt(Cf / Lh)
if np.isclose(zeta, 1):
    kind = "critical"
elif np.any(np.abs(np.imag(roots)) > 0):
    kind = "under"
else:
    kind = "over"
print(roots, kind, zeta)
```

```python tests
import numpy as np
Lh, Cf = L * 1e-3, C * 1e-6
assert np.allclose(np.sort_complex(roots), np.sort_complex(np.roots([1, R / Lh, 1 / (Lh * Cf)]))), "roots should be the two roots of the characteristic polynomial."
assert np.isclose(zeta, R / 2 * np.sqrt(Cf / Lh)), "zeta should be (R/2) sqrt(C/L)."
assert kind == ("under" if zeta < 1 else "over"), f"With zeta = {zeta:.3f} the circuit is {'under' if zeta < 1 else 'over'}damped; got {kind!r}."
```
:::

::: check
kind: python
given: V = 5 | 12; R = 100 | 1000; C = 1 | 10

## A capacitor `C` = {C} µF charges from 0 toward `V` = {V} V through `R` = {R} Ω. Sample 10 time constants at 20,001 points. With $i = (V/R)e^{-t/RC}$ and $v_C = V(1 - e^{-t/RC})$, set `E_source` to $\int Vi\,dt$, `E_cap` to $\int v_Ci\,dt$ and `E_res` to $\int i^2R\,dt$, each by the trapezoid rule, then `half = E_cap / E_source`.

```python starter
import numpy as np

E_source = E_cap = E_res = half = 0
print(E_source, E_cap, E_res, half)
```

```python solution
import numpy as np

tau = R * C * 1e-6
t = np.linspace(0, 10 * tau, 20001)
i = V / R * np.exp(-t / tau)
vc = V * (1 - np.exp(-t / tau))

def trap(y):
    return np.sum((y[1:] + y[:-1]) / 2 * np.diff(t))

E_source = trap(V * i)
E_cap = trap(vc * i)
E_res = trap(i**2 * R)
half = E_cap / E_source
print(E_source, E_cap, E_res, half)
```

```python tests
import numpy as np
Cf = C * 1e-6
assert abs(E_cap - 0.5 * Cf * V**2) / (0.5 * Cf * V**2) < 1e-4, f"The capacitor ends with (1/2) C V^2 = {0.5 * Cf * V**2:.4g} J; got {E_cap}."
assert abs(E_source - E_cap - E_res) / E_source < 1e-6, "The source's energy should split between the capacitor and the resistor."
assert abs(half - 0.5) < 1e-4, f"Exactly half the source's energy reaches the capacitor, whatever R is; got {half}."
```
:::

::: check
kind: python
given: n = 4 | 8 | 16

## Integrate $\sin x$ from 0 to $\pi$ (exactly 2) with `n` = {n} intervals. Write `trapezoid(f, a, b, n)` and `simpson(f, a, b, n)` (n even), and set `e_t` and `e_s` to their errors, `abs(result - 2)`.

```python starter
import math

def trapezoid(f, a, b, n):
    return 0

def simpson(f, a, b, n):
    return 0

e_t = abs(trapezoid(math.sin, 0, math.pi, n) - 2)
e_s = abs(simpson(math.sin, 0, math.pi, n) - 2)
print(e_t, e_s)
```

```python solution
import math

def trapezoid(f, a, b, n):
    h = (b - a) / n
    return h * (f(a) / 2 + sum(f(a + k * h) for k in range(1, n)) + f(b) / 2)

def simpson(f, a, b, n):
    h = (b - a) / n
    s = f(a) + f(b)
    s += 4 * sum(f(a + k * h) for k in range(1, n, 2))
    s += 2 * sum(f(a + k * h) for k in range(2, n, 2))
    return h / 3 * s

e_t = abs(trapezoid(math.sin, 0, math.pi, n) - 2)
e_s = abs(simpson(math.sin, 0, math.pi, n) - 2)
print(e_t, e_s)
```

```python tests
import math
assert math.isclose(trapezoid(lambda x: 3 * x + 1, 0, 2, 3), 8), "The trapezoid rule is exact for straight lines."
assert math.isclose(simpson(lambda x: x**3, 0, 2, 2), 4), "Simpson's rule is exact for cubics."
assert math.isclose(e_t, abs(trapezoid(math.sin, 0, math.pi, n) - 2)) and e_s < e_t / 20, f"Simpson should be far more accurate; got e_t = {e_t}, e_s = {e_s}."
assert math.isclose(trapezoid(math.sin, 0, math.pi, 4), 1.896118897, rel_tol=1e-8), "With 4 intervals the trapezoid gives 1.8961."
```
:::

::: check
kind: python
given: n = 3 | 4 | 6 | 8; code = 1 | 5 | 11 | 37; Vref = 2.5 | 5

## An R-2R ladder DAC has nodes 1 to `n` ({n} bits). Node 1 has a 2R resistor to ground; each node $k$ also has a 2R resistor driven by bit $k - 1$ of the code (`Vref` = {Vref} V if the bit is 1, 0 V if it's 0); and an R resistor joins each node to the next. Using a stamped conductance matrix with each bit source as a Norton current, set `vout` to the voltage at node `n` for `code` = {code} (only its low `n` bits count) with R = 10 kΩ, and `ideal` to $V_{ref}\cdot\text{code}/2^n$ for those bits.

```python starter
import numpy as np
vout = 0
ideal = 0
print(vout, ideal)
```

```python solution
import numpy as np
R = 10e3
c = code % 2**n
G = np.zeros((n, n))
i = np.zeros(n)
G[0, 0] += 1 / (2 * R)
for k in range(n):
    G[k, k] += 1 / (2 * R)
    i[k] += ((c >> k) & 1) * Vref / (2 * R)
    if k:
        G[k, k] += 1 / R
        G[k - 1, k - 1] += 1 / R
        G[k, k - 1] -= 1 / R
        G[k - 1, k] -= 1 / R
vout = np.linalg.solve(G, i)[-1]
ideal = Vref * c / 2**n
print(vout, ideal)
```

```python tests
c = code % 2**n
assert abs(ideal - Vref * c / 2**n) < 1e-15, "ideal is Vref * (code mod 2**n) / 2**n."
assert abs(vout - ideal) < 1e-9 * Vref, f"The ladder's output should equal {Vref * c / 2**n:.6g} V. Stamp each 2R as a conductance to ground at its node, with its bit's current Vbit/(2R) injected there, and each R between neighbors."
```

::: right
Right. Each step along the ladder halves a bit's contribution, so the output is exactly the code times $V_{ref}/2^n$. The nodal solution shows it without any of the ladder's clever Thevenin arguments.
:::
:::
:::
