---
title: Problem set 12
heading: "Problem set 12: longer labs"
eyebrow: A4 · Problem set 12
type: problems
---

::: hook
Longer labs that combine the whole course: functions and data structures, arrays, complex numbers, root finding, simulation, statistics and the FFT. Each uses your own values. Plan each one on paper before you write code.
:::

::: pool
pick: 5

::: check
kind: python
given: R = 1k..10k E12 Ω; C = 10n..100n E6 F

## Find the RC low-pass filter's −3 dB frequency numerically: write the magnitude in dB as a function of f, and use bisection between 1 Hz and 10 MHz to find where it equals −3.0103 dB. Set `f3`. (Check it against $1/2\pi RC$.)

```python starter
import numpy as np

def mag_db(f):
    return 0   # replace this

f3 = 0
print(f3, 1 / (2 * np.pi * R * C))
```

```python solution
import numpy as np

def mag_db(f):
    return 20 * np.log10(abs(1 / (1 + 1j * 2 * np.pi * f * R * C)))

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

f3 = bisect(lambda f: mag_db(f) + 10 * np.log10(2), 1, 1e7)
print(f3, 1 / (2 * np.pi * R * C))
```

```python tests
import numpy as np
fc = 1 / (2 * np.pi * R * C)
assert abs(mag_db(fc) + 10 * np.log10(2)) < 1e-6, "mag_db(f) should be 20·log10|H|; at the corner it's about −3.01 dB."
assert abs(f3 - fc) < 1e-6 * fc, "f3 should come out at 1/(2πRC). Bisect on mag_db(f) + 3.0103."
```
:::

::: check
kind: python
given: R = 10..100 sig 2; L = 1m..10m E6 H; Vs = 5 | 10 | 12

## An inductor current builds up as $di/dt = (V_s - Ri)/L$. Simulate it with Euler's method from 0 A, with a step of $L/(100R)$ for 500 steps, store the currents in `i` (501 values), and set `err` to the largest difference from the exact $\frac{V_s}{R}\left(1 - e^{-tR/L}\right)$.

```python starter
import numpy as np

dt = L / (100 * R)
i = np.zeros(501)
err = 0
print(i[-1], err)
```

```python solution
import numpy as np

dt = L / (100 * R)
i = np.zeros(501)
for k in range(500):
    i[k + 1] = i[k] + dt * (Vs - R * i[k]) / L
t = dt * np.arange(501)
err = np.max(np.abs(i - Vs / R * (1 - np.exp(-t * R / L))))
print(i[-1], err)
```

```python tests
import numpy as np
dt = L / (100 * R)
w = np.zeros(501)
for k in range(500):
    w[k + 1] = w[k] + dt * (Vs - R * w[k]) / L
assert np.allclose(i, w), "Each Euler step adds dt·(Vs − R·i[k])/L."
t2 = dt * np.arange(501)
assert abs(err - np.max(np.abs(w - Vs / R * (1 - np.exp(-t2 * R / L))))) < 1e-12, "err should be the largest absolute difference from the exact curve."
assert err < 0.01 * Vs / R, "With a hundred steps per time constant, Euler should stay within 1% of the final current."
```
:::

::: check
kind: python
given: C = 1u..100u E6 F; R = 1k..10k E12 Ω

## A capacitor discharges through an unknown resistor. The arrays `t` (s) and `v` (V) are noisy readings, and `C` is known. Fit the time constant from $\ln v$ against $t$, then set `R_fit` to the resistance.

```python starter
import numpy as np

rng = np.random.default_rng(13)
t = np.linspace(0, 3 * R * C, 40)
v = 9 * np.exp(-t / (R * C)) * (1 + rng.normal(0, 0.005, 40))
R_fit = 0
print(R_fit)
```

```python solution
import numpy as np

rng = np.random.default_rng(13)
t = np.linspace(0, 3 * R * C, 40)
v = 9 * np.exp(-t / (R * C)) * (1 + rng.normal(0, 0.005, 40))
tau = -1 / np.polyfit(t, np.log(v), 1)[0]
R_fit = tau / C
print(R_fit)
```

```python tests
import numpy as np
tau = -1 / np.polyfit(t, np.log(v), 1)[0]
assert abs(R_fit - tau / C) < 1e-6 * R, "Fit τ from ln v against t (τ = −1/slope), then R = τ / C."
assert abs(R_fit - R) < 0.03 * R, "R_fit should land within a few percent of the true resistance."
```
:::
::: check
kind: python
given: R = 1000 | 4700; C = 10 | 47; L = 10 | 47

## For a series RLC with `R` = {R} Ω, `C` = {C} nF and `L` = {L} mH, compute the voltage across the capacitor for a 1 V input as a complex transfer function over 400 log-spaced frequencies from 100 Hz to 1 MHz. Set `f_peak` to the frequency of the largest gain on that grid, `gain_peak` to the gain there, and `Q` to the theoretical $\frac{1}{R}\sqrt{L/C}$.

```python starter
import numpy as np
f = np.logspace(2, 6, 400)
f_peak = gain_peak = Q = 0
print(f_peak, gain_peak, Q)
```

```python solution
import numpy as np
f = np.logspace(2, 6, 400)
w = 2 * np.pi * f
Lh, Cf = L * 1e-3, C * 1e-9
H = (1 / (1j * w * Cf)) / (R + 1j * w * Lh + 1 / (1j * w * Cf))
g = np.abs(H)
k = np.argmax(g)
f_peak, gain_peak = f[k], g[k]
Q = np.sqrt(Lh / Cf) / R
print(f_peak, gain_peak, Q)
```

```python tests
import numpy as np
f = np.logspace(2, 6, 400)
w = 2 * np.pi * f
H = (1 / (1j * w * C * 1e-9)) / (R + 1j * w * L * 1e-3 + 1 / (1j * w * C * 1e-9))
k = np.argmax(np.abs(H))
assert abs(f_peak - f[k]) < 1e-9 * f[k] and abs(gain_peak - np.abs(H)[k]) < 1e-9, "Use the divider H = Z_C / (R + Z_L + Z_C) and find its largest magnitude on the grid."
assert abs(Q - np.sqrt(L * 1e-3 / (C * 1e-9)) / R) < 1e-12, "Q = √(L/C)/R, with L in henries and C in farads."
```
:::

::: check
kind: python
given: f1 = 50 | 60; h = 3 | 5; a = 0.1 | 0.2

## A mains current is a fundamental at `f1` = {f1} Hz (amplitude 1 A) plus a harmonic `h` = {h} times higher with amplitude `a` = {a} A, sampled at 12 kHz for exactly 10 cycles of the fundamental. From the FFT, set `I1` and `Ih` to the two amplitudes, `thd` to the total harmonic distortion $I_h/I_1$, and `irms` to the RMS current computed from the samples.

```python starter
import numpy as np
fs = 12000
N = int(10 * fs / f1)
t = np.arange(N) / fs
i = np.sin(2 * np.pi * f1 * t) + a * np.sin(2 * np.pi * h * f1 * t + 0.4)
I1 = Ih = thd = irms = 0
print(I1, Ih, thd, irms)
```

```python solution
import numpy as np
fs = 12000
N = int(10 * fs / f1)
t = np.arange(N) / fs
i = np.sin(2 * np.pi * f1 * t) + a * np.sin(2 * np.pi * h * f1 * t + 0.4)
A = 2 * np.abs(np.fft.rfft(i)) / N
f = np.fft.rfftfreq(N, 1 / fs)
I1 = A[np.argmin(np.abs(f - f1))]
Ih = A[np.argmin(np.abs(f - h * f1))]
thd = Ih / I1
irms = np.sqrt(np.mean(i**2))
print(I1, Ih, thd, irms)
```

```python tests
import numpy as np
assert abs(I1 - 1) < 1e-9 and abs(Ih - a) < 1e-9, "Read the amplitudes from the bins at f1 and h·f1, scaled by 2/N."
assert abs(thd - a) < 1e-9, "thd is Ih / I1."
assert abs(irms - np.sqrt((1 + a**2) / 2)) < 1e-9, "irms is √(mean(i²)), which equals √((1 + a²)/2)."
```
:::

::: check
kind: python
given: k = 0..2 int

## The starter's netlist is a list of `(name, a, b, ohms)` resistors with a 1 A current source into node `"1"` (returning through ground `"0"`). Build the nodal conductance matrix for the non-ground nodes (sorted by name) and set `v` to a dictionary from node to voltage, using `np.linalg.solve`.

```python starter
import numpy as np
net = [[("R1", "1", "0", 10), ("R2", "1", "2", 20), ("R3", "2", "0", 20)],
       [("R1", "1", "2", 5), ("R2", "2", "0", 10), ("R3", "2", "3", 10), ("R4", "3", "0", 10)],
       [("R1", "1", "0", 100), ("R2", "1", "2", 50), ("R3", "2", "0", 50), ("R4", "1", "2", 50)]][k]
v = {}
print(v)
```

```python solution
import numpy as np
net = [[("R1", "1", "0", 10), ("R2", "1", "2", 20), ("R3", "2", "0", 20)],
       [("R1", "1", "2", 5), ("R2", "2", "0", 10), ("R3", "2", "3", 10), ("R4", "3", "0", 10)],
       [("R1", "1", "0", 100), ("R2", "1", "2", 50), ("R3", "2", "0", 50), ("R4", "1", "2", 50)]][k]
nodes = sorted({n for _, a, b, _ in net for n in (a, b)} - {"0"})
idx = {n: j for j, n in enumerate(nodes)}
G = np.zeros((len(nodes), len(nodes)))
for _, a, b, r in net:
    g = 1 / r
    for x in (a, b):
        if x != "0":
            G[idx[x], idx[x]] += g
    if a != "0" and b != "0":
        G[idx[a], idx[b]] -= g
        G[idx[b], idx[a]] -= g
I = np.zeros(len(nodes))
I[idx["1"]] = 1.0
sol = np.linalg.solve(G, I)
v = {n: sol[idx[n]] for n in nodes}
print(v)
```

```python tests
want = [{"1": 8.0, "2": 4.0}, {"1": 11.6666666667, "2": 6.6666666667, "3": 3.3333333333}, {"1": 42.8571428571, "2": 28.5714285714}][k]
assert set(v) == set(want), f"v should have the nodes {sorted(want)}."
assert all(abs(v[n] - want[n]) < 1e-6 for n in want), f"The node voltages should be {want}."
```
:::

::: check
kind: python
given: V = 5 | 9; Rs = 1 | 5

## A diode with $I_s = 10^{-12}$ A and $V_T$ = 0.02585 V is driven from `V` = {V} V through a resistor; sweep the resistor over 100 log-spaced values from 100 Ω to 100 kΩ. For each, find the diode voltage by bisection (to 1e-12 V) and set `vd` to the array of diode voltages. Then fit $V_d$ against $\ln I$ with `np.polyfit` and set `VT_fit` from the slope. (`Rs` = {Rs} is not used; it's there to vary your numbers.)

```python starter
import numpy as np
R = np.logspace(2, 5, 100)
vd = np.zeros(100)
VT_fit = 0
print(VT_fit)
```

```python solution
import numpy as np
import math
Is, VT = 1e-12, 0.02585
R = np.logspace(2, 5, 100)
vd = np.zeros(100)
for j, r in enumerate(R):
    lo, hi = 0.0, float(V)
    while hi - lo > 1e-12:
        m = (lo + hi) / 2
        if Is * (math.exp(m / VT) - 1) * r + m < V:
            lo = m
        else:
            hi = m
    vd[j] = (lo + hi) / 2
I = (V - vd) / R
VT_fit = np.polyfit(np.log(I), vd, 1)[0]
print(VT_fit)
```

```python tests
import numpy as np
assert np.all(np.diff(vd) < 0), "A bigger resistor means less current and a smaller diode voltage: vd should fall along the sweep."
assert abs(VT_fit - 0.02585) < 2e-4, "The slope of Vd against ln I should come out close to VT, 0.02585 V."
```
:::
:::
