---
title: Problem set 8
heading: "Problem set 8: arrays and plots"
eyebrow: A4 · Problem set 8
type: problems
---

::: hook
These labs use lessons 28 to 34: NumPy arrays, vectorized arithmetic and masks, two-dimensional arrays, and plotting. Write each without Python loops over the samples; the tests can't tell, but you'll be glad of the habit when the arrays get big.
:::

::: pool
pick: 5

::: check
kind: python
given: A = 1 | 2.5; f = 50 | 60; dc = 0 | 0.5

## For 10 cycles of $v = \text{dc} + A\sin(2\pi f t)$ sampled at 100 points per cycle (`A` = {A}, `f` = {f} Hz, `dc` = {dc} V), set `vpp` to the peak-to-peak value, `vrms` to the RMS of `v`, and `vac` to the RMS of `v` with its mean removed.

```python starter
import numpy as np
n = 1000
t = np.arange(n) / (100 * f)
v = dc + A * np.sin(2 * np.pi * f * t)
vpp = vrms = vac = 0
print(vpp, vrms, vac)
```

```python solution
import numpy as np
n = 1000
t = np.arange(n) / (100 * f)
v = dc + A * np.sin(2 * np.pi * f * t)
vpp = v.max() - v.min()
vrms = np.sqrt(np.mean(v**2))
vac = np.sqrt(np.mean((v - v.mean())**2))
print(vpp, vrms, vac)
```

```python tests
import numpy as np
assert abs(vpp - 2 * A) < 1e-3 * A, "vpp should be v.max() − v.min()."
assert abs(vrms - np.sqrt(dc**2 + A**2 / 2)) < 1e-9, "vrms should be √(mean(v²)), which includes the DC part."
assert abs(vac - A / np.sqrt(2)) < 1e-9, "vac should be the RMS after subtracting v.mean()."
```
:::

::: check
kind: python
given: k = 1..6 int; th = 2.5 | 3.0

## The starter makes noisy readings `v` sampled every millisecond. Set `n_high` to how many exceed `th` = {th} V, `first_high` to the time in ms of the first one (or `None`), and `longest` to the longest run of consecutive high samples.

```python starter
import numpy as np
rng = np.random.default_rng(k)
v = 2.5 + 0.4 * np.sin(np.arange(500) / 30) + 0.2 * rng.normal(size=500)
n_high = 0
first_high = None
longest = 0
print(n_high, first_high, longest)
```

```python solution
import numpy as np
rng = np.random.default_rng(k)
v = 2.5 + 0.4 * np.sin(np.arange(500) / 30) + 0.2 * rng.normal(size=500)
high = v > th
n_high = int(np.count_nonzero(high))
idx = np.nonzero(high)[0]
first_high = int(idx[0]) if len(idx) else None
longest = 0
run = 0
for h in high:
    run = run + 1 if h else 0
    longest = max(longest, run)
print(n_high, first_high, longest)
```

```python tests
import numpy as np
rng = np.random.default_rng(k)
vs = 2.5 + 0.4 * np.sin(np.arange(500) / 30) + 0.2 * rng.normal(size=500)
h = vs > th
assert n_high == int(np.count_nonzero(h)), "n_high should count v > th."
idx = np.nonzero(h)[0]
assert first_high == (int(idx[0]) if len(idx) else None), "first_high should be the index (in ms) of the first high sample."
best = run = 0
for x in h:
    run = run + 1 if x else 0
    best = max(best, run)
assert longest == best, f"longest should be {best}: the longest stretch of True values in a row."
```
:::

::: check
kind: python
given: Vs = 5 | 12; RL = 1000 | 10000

## For every pair of E12 resistors from 1 kΩ to 8.2 kΩ in the starter (top `R1`, bottom `R2`), compute the loaded divider output into a load `RL` = {RL} Ω as a 2D array `vout` (rows for `R2`, columns for `R1`). Set `n_ok` to how many pairs give an output within 1% of `Vs / 3`.

```python starter
import numpy as np
E12 = np.array([1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]) * 1e3
vout = None
n_ok = 0
print(n_ok)
```

```python solution
import numpy as np
E12 = np.array([1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]) * 1e3
R1 = E12[None, :]
R2 = E12[:, None]
Rp = R2 * RL / (R2 + RL)
vout = Vs * Rp / (R1 + Rp)
n_ok = int(np.count_nonzero(np.abs(vout - Vs / 3) <= 0.01 * Vs / 3))
print(n_ok)
```

```python tests
import numpy as np
E12 = np.array([1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]) * 1e3
Rp = E12[:, None] * RL / (E12[:, None] + RL)
want = Vs * Rp / (E12[None, :] + Rp)
assert vout is not None and np.shape(vout) == (12, 12) and np.allclose(vout, want), "vout should be 12 × 12: R2 in parallel with RL on the bottom, R1 on top."
assert n_ok == int(np.count_nonzero(np.abs(want - Vs / 3) <= 0.01 * Vs / 3)), "Count the pairs within 1% of Vs/3."
```
:::

::: check
kind: python
given: f0 = 1000 | 5000; Q = 0.7 | 2 | 10

## A second-order low-pass has $H = 1/\big(1 - (f/f_0)^2 + j(f/f_0)/Q\big)$. Make a two-subplot Bode plot (gain in dB on top, phase in degrees below, log frequency axes) from $f_0/100$ to $100f_0$, with `f0` = {f0} Hz and `Q` = {Q}. Set `peak_db` to the largest gain in dB on your frequency grid.

```python starter
import numpy as np
import matplotlib.pyplot as plt
f = np.logspace(np.log10(f0 / 100), np.log10(100 * f0), 2000)
peak_db = 0
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
f = np.logspace(np.log10(f0 / 100), np.log10(100 * f0), 2000)
H = 1 / (1 - (f / f0)**2 + 1j * (f / f0) / Q)
fig, (a1, a2) = plt.subplots(2, 1, sharex=True)
a1.semilogx(f, 20 * np.log10(np.abs(H)))
a1.set_ylabel("|H| (dB)")
a2.semilogx(f, np.degrees(np.angle(H)))
a2.set_ylabel("phase (°)")
a2.set_xlabel("f (Hz)")
peak_db = np.max(20 * np.log10(np.abs(H)))
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
f = np.logspace(np.log10(f0 / 100), np.log10(100 * f0), 2000)
H = 1 / (1 - (f / f0)**2 + 1j * (f / f0) / Q)
assert len(plt.gcf().axes) == 2, "Make two subplots."
assert all(a.get_xscale() == "log" for a in plt.gcf().axes), "Both frequency axes should be log."
assert abs(peak_db - np.max(20 * np.log10(np.abs(H)))) < 1e-9, "peak_db should be the largest gain in dB on the grid."
```
:::

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

## `X` holds 24 hourly readings for each of 7 days (shape 7 × 24, made in the starter). Set `daily_mean` (one per day), `hourly_mean` (one per hour, averaged over the days), and `worst_day`, `worst_hour` where the single largest reading is.

```python starter
import numpy as np
rng = np.random.default_rng(k)
hours = np.arange(24)
X = 50 + 10 * np.sin((hours - 8) * np.pi / 12)[None, :] + rng.normal(0, 2, (7, 24))
daily_mean = hourly_mean = None
worst_day = worst_hour = 0
print(worst_day, worst_hour)
```

```python solution
import numpy as np
rng = np.random.default_rng(k)
hours = np.arange(24)
X = 50 + 10 * np.sin((hours - 8) * np.pi / 12)[None, :] + rng.normal(0, 2, (7, 24))
daily_mean = X.mean(axis=1)
hourly_mean = X.mean(axis=0)
worst_day, worst_hour = np.unravel_index(np.argmax(X), X.shape)
print(worst_day, worst_hour)
```

```python tests
import numpy as np
rng = np.random.default_rng(k)
hours = np.arange(24)
Xs = 50 + 10 * np.sin((hours - 8) * np.pi / 12)[None, :] + rng.normal(0, 2, (7, 24))
assert np.allclose(daily_mean, Xs.mean(axis=1)), "daily_mean should be one value per day: average across axis 1."
assert np.allclose(hourly_mean, Xs.mean(axis=0)), "hourly_mean should be one value per hour: average down axis 0."
assert (int(worst_day), int(worst_hour)) == tuple(int(i) for i in np.unravel_index(np.argmax(Xs), Xs.shape)), "Use np.unravel_index(np.argmax(X), X.shape)."
```
:::

::: check
kind: python
given: f = 50 | 60; A = 170 | 325

## Full-wave rectify a mains sine of amplitude `A` = {A} V at `f` = {f} Hz (take $|v|$), sampled at 200 points per cycle over 5 cycles. Set `vdc` to the average of the rectified wave and `ratio` to `vdc / A`.

```python starter
import numpy as np
t = np.arange(1000) / (200 * f)
v = A * np.sin(2 * np.pi * f * t)
vdc = v.mean()
ratio = vdc / A
print(vdc, ratio)
```

```python solution
import numpy as np
t = np.arange(1000) / (200 * f)
v = A * np.sin(2 * np.pi * f * t)
vdc = np.abs(v).mean()
ratio = vdc / A
print(vdc, ratio)
```

```python tests
import numpy as np
assert abs(ratio - 2 / np.pi) < 1e-3, "A full-wave rectified sine averages to (2/π) of its peak. Take np.abs(v) before averaging."
```
:::

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

## Make a `n` × `n` grid of points with `x` and `y` from −1 to 1 using `np.meshgrid`, and set `inside` to the fraction of grid points with $x^2 + y^2 \le 1$.

```python starter
import numpy as np
inside = 0
print(inside)
```

```python solution
import numpy as np
x = np.linspace(-1, 1, n)
X, Y = np.meshgrid(x, x)
inside = np.mean(X**2 + Y**2 <= 1)
print(inside)
```

```python tests
import numpy as np
x = np.linspace(-1, 1, n)
X, Y = np.meshgrid(x, x)
assert abs(inside - np.mean(X**2 + Y**2 <= 1)) < 1e-12, "Use np.meshgrid(x, x) with x = np.linspace(-1, 1, n), then the mean of the mask."
```
:::
:::
