---
title: Final exam
heading: "Final exam: Python for engineers"
eyebrow: A4 · Final exam
type: problems
---

::: hook
Five labs drawn from the whole course, weighted toward its second half: arrays, plots, numerical methods and data. Give yourself two and a half hours and work without the lessons open. Each lab is graded by hidden tests; if one fails, read its message, fix, and check again. "Another set" deals a different exam.
:::

::: pool
pick: 5

::: check
kind: python
given: fc = 300 | 3000; n = 2 | 4

## An `n`-th order Butterworth low-pass has $|H| = 1/\sqrt{1 + (f/f_c)^{2n}}$. For `n` = {n} and `fc` = {fc} Hz, on 500 log-spaced frequencies from $f_c/100$ to $100f_c$, set `gdb` to the gain in dB and `slope` to the roll-off in dB per decade measured between $10f_c$ and $100f_c$ (the last two decades' endpoints).

```python starter
import numpy as np
f = np.logspace(np.log10(fc / 100), np.log10(100 * fc), 500)
gdb = np.zeros(500)
slope = 0
print(slope)
```

```python solution
import numpy as np
f = np.logspace(np.log10(fc / 100), np.log10(100 * fc), 500)
gdb = -10 * np.log10(1 + (f / fc)**(2 * n))
g10 = -10 * np.log10(1 + 10**(2 * n))
g100 = -10 * np.log10(1 + 100**(2 * n))
slope = g100 - g10
print(slope)
```

```python tests
import numpy as np
f = np.logspace(np.log10(fc / 100), np.log10(100 * fc), 500)
assert np.allclose(gdb, -10 * np.log10(1 + (f / fc)**(2 * n))), "gdb is 20·log10|H| = −10·log10(1 + (f/fc)^(2n))."
assert abs(slope + 20 * n) < 0.01, f"An order-{n} filter rolls off at about −{20 * n} dB per decade."
```
:::

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

## Read the CSV in the starter (a comment line, a header, then `t` in ms and `v` in mV), convert to seconds and volts, and set `t`, `v`, then `vpp` (peak to peak, V) and `f_est`: the frequency estimated from the average spacing of rising zero crossings of `v - v.mean()`.

```python starter
import io
import numpy as np
f_true = [50, 120, 400][k]
tt = np.arange(0, 100, 0.05)
vv = 200 * np.sin(2 * np.pi * f_true * tt / 1000) + 30
text = "# scope\nt_ms,v_mV\n" + "\n".join(f"{a:.2f},{b:.3f}" for a, b in zip(tt, vv))
t = v = None
vpp = f_est = 0
print(vpp, f_est)
```

```python solution
import io
import numpy as np
f_true = [50, 120, 400][k]
tt = np.arange(0, 100, 0.05)
vv = 200 * np.sin(2 * np.pi * f_true * tt / 1000) + 30
text = "# scope\nt_ms,v_mV\n" + "\n".join(f"{a:.2f},{b:.3f}" for a, b in zip(tt, vv))
data = np.loadtxt(io.StringIO(text), delimiter=",", skiprows=2)
t, v = data[:, 0] * 1e-3, data[:, 1] * 1e-3
vpp = v.max() - v.min()
x = v - v.mean()
ups = np.nonzero((x[:-1] < 0) & (x[1:] >= 0))[0]
f_est = 1 / np.mean(np.diff(t[ups]))
print(vpp, f_est)
```

```python tests
f_true = [50, 120, 400][k]
assert v is not None and abs(v.max() - 0.23) < 2e-3, "Convert millivolts to volts, and skip both the comment and the header (skiprows=2)."
assert abs(vpp - 0.4) < 5e-3, "vpp should be about 0.4 V."
assert abs(f_est - f_true) < 0.02 * f_true, f"f_est should be close to {f_true} Hz."
```
:::

::: check
kind: python
given: tau = 1 | 4; n = 50 | 100

## Integrate $dv/dt = (5 - v)/\tau - 0.1v^2$ from $v = 0$ to $t = 5\tau$ with RK4 in `n` = {n} steps and with `2 * n` steps (`tau` = {tau}). Set `v1`, `v2` to the two final values and `est` to the estimated error of `v2`, $|v_1 - v_2|/15$.

```python starter
v1 = v2 = est = 0
print(v1, v2, est)
```

```python solution
def run(steps):
    h, v = 5 * tau / steps, 0.0
    f = lambda v: (5 - v) / tau - 0.1 * v * v
    for _ in range(steps):
        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

v1, v2 = run(n), run(2 * n)
est = abs(v1 - v2) / 15
print(v1, v2, est)
```

```python tests
def run(steps):
    h, v = 5 * tau / steps, 0.0
    f = lambda v: (5 - v) / tau - 0.1 * v * v
    for _ in range(steps):
        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
assert abs(v1 - run(n)) < 1e-12 and abs(v2 - run(2 * n)) < 1e-12, "Run RK4 with n steps and with 2n steps over 0 to 5τ."
assert abs(est - abs(v1 - v2) / 15) < 1e-15, "est is |v1 − v2| / 15."
```
:::

::: check
kind: python
given: tR = 1 | 5; tC = 2 | 10

## A divider of 10 kΩ over 10 kΩ feeds an RC low-pass of 10 kΩ and 100 nF; the output is at the capacitor. Model every resistor as uniform ±`tR`% and the capacitor as uniform ±`tC`%. With `default_rng(3)`, draw 100,000 boards (top, bottom, filter R, then C). The DC gain is the divider ratio, and the corner is $1/(2\pi R_{th}C + 2\pi R_fC)$ where $R_{th}$ is the divider's Thevenin resistance. Set `gain`, `fc` (arrays) and `yld`: the fraction with gain within ±2% of 0.5 and corner within ±5% of nominal.

```python starter
import numpy as np
gain = fc = None
yld = 0
print(yld)
```

```python solution
import numpy as np
rng = np.random.default_rng(3)
N = 100000
Rt = 10e3 * rng.uniform(1 - tR / 100, 1 + tR / 100, N)
Rb = 10e3 * rng.uniform(1 - tR / 100, 1 + tR / 100, N)
Rf = 10e3 * rng.uniform(1 - tR / 100, 1 + tR / 100, N)
C = 100e-9 * rng.uniform(1 - tC / 100, 1 + tC / 100, N)
gain = Rb / (Rt + Rb)
Rth = Rt * Rb / (Rt + Rb)
fc = 1 / (2 * np.pi * (Rth + Rf) * C)
f0 = 1 / (2 * np.pi * 15e3 * 100e-9)
yld = np.mean((np.abs(gain / 0.5 - 1) <= 0.02) & (np.abs(fc / f0 - 1) <= 0.05))
print(yld)
```

```python tests
import numpy as np
rng = np.random.default_rng(3)
N = 100000
Rt = 10e3 * rng.uniform(1 - tR / 100, 1 + tR / 100, N)
Rb = 10e3 * rng.uniform(1 - tR / 100, 1 + tR / 100, N)
Rf = 10e3 * rng.uniform(1 - tR / 100, 1 + tR / 100, N)
C = 100e-9 * rng.uniform(1 - tC / 100, 1 + tC / 100, N)
g = Rb / (Rt + Rb)
f = 1 / (2 * np.pi * (Rt * Rb / (Rt + Rb) + Rf) * C)
assert gain is not None and np.allclose(gain, g) and np.allclose(fc, f), "Draw top, bottom, filter R and C in that order; the corner uses (R_top ∥ R_bottom + R_f)·C."
f0 = 1 / (2 * np.pi * 15e3 * 100e-9)
assert abs(yld - np.mean((np.abs(g / 0.5 - 1) <= 0.02) & (np.abs(f / f0 - 1) <= 0.05))) < 1e-15, "yld needs both conditions."
```
:::

::: check
kind: python
given: f1 = 180 | 440; f2 = 1250 | 2000; s = 2 | 5

## The starter makes a record of two tones in noise, sampled at 8 kHz for 8000 samples. Using a Hann window (`np.hanning`) before `np.fft.rfft`, set `peaks` to the sorted frequencies of the two largest local maxima of the spectrum's magnitude (ignoring DC).

```python starter
import numpy as np
rng = np.random.default_rng(s)
fs, N = 8000, 8000
t = np.arange(N) / fs
x = np.sin(2 * np.pi * f1 * t) + 0.5 * np.sin(2 * np.pi * f2 * t) + 0.5 * rng.normal(size=N)
peaks = []
print(peaks)
```

```python solution
import numpy as np
rng = np.random.default_rng(s)
fs, N = 8000, 8000
t = np.arange(N) / fs
x = np.sin(2 * np.pi * f1 * t) + 0.5 * np.sin(2 * np.pi * f2 * t) + 0.5 * rng.normal(size=N)
A = np.abs(np.fft.rfft(x * np.hanning(N)))
f = np.fft.rfftfreq(N, 1 / fs)
is_max = (A[1:-1] > A[:-2]) & (A[1:-1] > A[2:])
idx = np.nonzero(is_max)[0] + 1
top2 = idx[np.argsort(A[idx])[-2:]]
peaks = sorted(f[top2])
print(peaks)
```

```python tests
assert len(peaks) == 2 and abs(peaks[0] - f1) <= 1 and abs(peaks[1] - f2) <= 1, f"The two tones are at {f1} and {f2} Hz."
```
:::

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

## Write a class `Part` with `name`, `value` and `tol` (a fraction) and a method `bounds()`. From the starter's list of tuples, make a list of `Part` objects and set `widest` to the name of the part with the largest absolute tolerance band (`value * tol`), and `total` to a dictionary from the first letter of each name to the sum of the nominal values with that letter.

```python starter
rows = [[("R1", 4700, 0.05), ("R2", 1000, 0.01), ("C1", 1e-7, 0.1), ("R3", 22000, 0.01)],
        [("R1", 100, 0.05), ("C1", 1e-6, 0.2), ("C2", 2.2e-6, 0.1)],
        [("L1", 0.01, 0.2), ("R1", 330, 0.05), ("L2", 0.022, 0.1)]][k]
widest = None
total = {}
print(widest, total)
```

```python solution
class Part:
    def __init__(self, name, value, tol):
        self.name = name
        self.value = value
        self.tol = tol

    def bounds(self):
        return self.value * (1 - self.tol), self.value * (1 + self.tol)

rows = [[("R1", 4700, 0.05), ("R2", 1000, 0.01), ("C1", 1e-7, 0.1), ("R3", 22000, 0.01)],
        [("R1", 100, 0.05), ("C1", 1e-6, 0.2), ("C2", 2.2e-6, 0.1)],
        [("L1", 0.01, 0.2), ("R1", 330, 0.05), ("L2", 0.022, 0.1)]][k]
parts = [Part(*r) for r in rows]
widest = max(parts, key=lambda p: p.value * p.tol).name
total = {}
for p in parts:
    total[p.name[0]] = total.get(p.name[0], 0) + p.value
print(widest, total)
```

```python tests
want_w = ["R1", "R1", "R1"][k]
assert widest == want_w, f"widest should be {want_w}: compare value × tol."
want_t = [{"R": 27700, "C": 1e-7}, {"R": 100, "C": 3.2e-6}, {"L": 0.032, "R": 330}][k]
assert set(total) == set(want_t) and all(abs(total[c] - want_t[c]) < 1e-12 * max(1, want_t[c]) for c in want_t), f"total should be {want_t}."
p = Part("X", 100, 0.1)
assert abs(p.bounds()[0] - 90) < 1e-9 and abs(p.bounds()[1] - 110) < 1e-9, "bounds() should return (value·(1 − tol), value·(1 + tol))."
```
:::

::: check
kind: python
given: V = 3.3 | 5; th = 0.5 | 0.9

## A capacitor charges as $v(t) = V(1 - e^{-t/\tau})$ with $\tau$ = 2 ms and `V` = {V} V. Find the time when it reaches `th` = {th} of `V` three ways: `t_exact` from the formula, `t_bisect` by bisection on [0, 20 ms] to 1e-12 s, and `t_samples` as the first sample time at or above the threshold on a 0.01 ms grid. All in seconds.

```python starter
import numpy as np
t_exact = t_bisect = t_samples = 0
print(t_exact, t_bisect, t_samples)
```

```python solution
import numpy as np
tau = 2e-3
t_exact = -tau * np.log(1 - th)
lo, hi = 0.0, 20e-3
while hi - lo > 1e-12:
    m = (lo + hi) / 2
    if V * (1 - np.exp(-m / tau)) < th * V:
        lo = m
    else:
        hi = m
t_bisect = (lo + hi) / 2
t = np.arange(0, 20e-3, 1e-5)
t_samples = t[np.argmax(V * (1 - np.exp(-t / tau)) >= th * V)]
print(t_exact, t_bisect, t_samples)
```

```python tests
import numpy as np
te = -2e-3 * np.log(1 - th)
assert abs(t_exact - te) < 1e-15, "t_exact = −τ·ln(1 − th)."
assert abs(t_bisect - te) < 1e-11, "t_bisect should agree with the formula to about 1e-12 s."
assert 0 <= t_samples - te < 1.0001e-5, "t_samples is the first grid point at or after the crossing."
```
:::

::: check
kind: python
given: n = 10 | 20 | 30 | 40 | 50 | 60

## Compare three integrals of $e^{-x}\sin(5x)$ from 0 to 3 on `n` = {n} slices: `left` (rectangles using the left end of each slice), `trap` (trapezoid) and `simp` (Simpson). Set `exact` from the formula $\frac{5 - e^{-3}(\sin 15 + 5\cos 15)}{26}$, and `best` to the name, `"left"`, `"trap"` or `"simp"`, of the most accurate.

```python starter
import numpy as np
left = trap = simp = exact = 0
best = None
print(best)
```

```python solution
import numpy as np
x = np.linspace(0, 3, n + 1)
y = np.exp(-x) * np.sin(5 * x)
h = x[1] - x[0]
left = h * y[:-1].sum()
trap = h * (y.sum() - (y[0] + y[-1]) / 2)
simp = h / 3 * (y[0] + 4 * y[1:-1:2].sum() + 2 * y[2:-1:2].sum() + y[-1])
exact = (5 - np.exp(-3) * (np.sin(15) + 5 * np.cos(15))) / 26
errs = {"left": abs(left - exact), "trap": abs(trap - exact), "simp": abs(simp - exact)}
best = min(errs, key=errs.get)
print(best)
```

```python tests
import numpy as np
x = np.linspace(0, 3, n + 1)
y = np.exp(-x) * np.sin(5 * x)
h = x[1] - x[0]
assert abs(left - h * y[:-1].sum()) < 1e-12, "left uses y at the start of each slice."
assert abs(trap - h * (y.sum() - (y[0] + y[-1]) / 2)) < 1e-12, "trap counts the two ends half."
assert abs(simp - h / 3 * (y[0] + 4 * y[1:-1:2].sum() + 2 * y[2:-1:2].sum() + y[-1])) < 1e-12, "simp uses weights 1, 4, 2, 4, ..., 4, 1 times h/3."
assert best == "simp", "Simpson's rule, fourth order, should be the most accurate."
```
:::
:::
