---
title: "Code lab: an RC filter's frequency response in NumPy"
heading: Computing and plotting a filter's response
eyebrow: C3 · Lesson 24 · Code lab
xp: 60
---

::: hook
A Bode plot is just a transfer function evaluated at many frequencies. With NumPy, which handles complex numbers natively, that's a couple of lines: build a logarithmic list of frequencies, compute $H = 1/(1 + j2\pi fRC)$ for all of them at once, and take the magnitude in dB and the angle in degrees. Then you can find the corner frequency numerically and check it against the formula.

::: play
- Below is the response you'll compute, drawn by the course's own plotter. The code labs reproduce it with NumPy and then dig numbers out of it.
- Change R and C and watch the corner move.
:::
:::

```sim plot
view: bode
x: f = 10..1M Hz log
slider: R = 100..100k = 1k Ω log
slider: C = 1n..1u = 100n F log
H: 1/(1 + j*2*pi*f*R*C)
marker: x = 1/(2*pi*R*C) | label: corner
readout: corner = 1/(2*pi*R*C) Hz
```

::: predict
## You evaluate $H = 1/(1 + j2\pi fRC)$ at 200 frequencies from 10 Hz to 1 MHz with `np.logspace(1, 6, 200)`. How are those frequencies spaced?

- [ ] Equally, 5 kHz apart
- [x] Equally on a log scale: the same ratio between neighbors
- [ ] Bunched at the high end
- [ ] Randomly

::: reveal
Equally on a log scale. `np.logspace(1, 6, 200)` gives $10^1$ to $10^6$ with the exponents equally spaced, so each frequency is the same ratio, about 1.06 times, above the last. That matches a Bode plot's log axis: every decade gets the same number of points.
:::
:::

::: nameit
## Frequency response in NumPy

```python
import numpy as np

R, C = 1e3, 100e-9
f = np.logspace(1, 6, 200)                # 10 Hz to 1 MHz
H = 1 / (1 + 1j * 2 * np.pi * f * R * C)  # complex, one value per frequency
gain_db = 20 * np.log10(np.abs(H))
phase_deg = np.degrees(np.angle(H))
```

- `1j` is Python's imaginary unit; arithmetic on arrays is elementwise, so `H` has 200 complex values.
- `np.abs` and `np.angle` give magnitude and phase (in radians; `np.degrees` converts).

**Finding the corner.** The −3 dB point is where the gain crosses $-10\log_{10}2 \approx -3.01$ dB. With a sampled curve, the closest sample is only as accurate as the spacing; interpolating between the two samples either side (in log frequency) does much better, and `np.interp` does it in one line, as long as its x values increase.

**Plotting** (shown inline when you run the lab):

```python
import matplotlib.pyplot as plt
plt.semilogx(f, gain_db)
plt.xlabel("frequency (Hz)"); plt.ylabel("gain (dB)"); plt.grid(True)
plt.show()
```
:::

::: example
## A sweep runs from 10 Hz to 100 kHz with 50 points per decade, both ends included. How many frequencies is that?

::: solution
1. **Count the intervals.** Four decades of 50 intervals each make $4 \times 50 = 200$ intervals.
2. **Add the final point.** Each interval starts at a point, so adding the final point gives $200 + 1 = 201$.

**Answer:** 201 frequencies.
:::
:::

::: example
## What do the gain and phase of an RC low-pass come out to at three times its corner?

::: solution
1. **Gain.**
   $$\begin{aligned} |H| &= \frac{1}{\sqrt{1 + 9}} \\ &= 0.316 \end{aligned}$$
   or −10.0 dB.
2. **Phase.**
   $$\begin{aligned} \phi &= -\tan^{-1}3 \\ &= -71.6° \end{aligned}$$
3. **What the code must do.** A correct code lab must reproduce both.

**Answer:** a gain of 0.316 (−10.0 dB) and a phase of −71.6°.
:::
:::

::: check
kind: python
given: R = 1000 | 2200 | 4700; C = 22e-9 | 47e-9 | 100e-9

## Compute the gain in dB of an RC low-pass (R = {R} Ω, C = {C} F) at 400 log-spaced frequencies from 10 Hz to 1 MHz, and set `f_3db` to the −3 dB frequency, found by interpolating the computed curve.

```python starter
import numpy as np

f = np.logspace(1, 6, 400)
H = 1 / (1 + 1j * 2 * np.pi * f * R * C)
gain_db = 20 * np.log10(np.abs(H))

# The gain falls as f rises, so flip both arrays for np.interp,
# and interpolate in log10(f).
f_3db = 0   # replace
print(f_3db, 1 / (2 * np.pi * R * C))
```

```python solution
import numpy as np

f = np.logspace(1, 6, 400)
H = 1 / (1 + 1j * 2 * np.pi * f * R * C)
gain_db = 20 * np.log10(np.abs(H))

target = -10 * np.log10(2)
f_3db = 10 ** np.interp(target, gain_db[::-1], np.log10(f)[::-1])
print(f_3db, 1 / (2 * np.pi * R * C))
```

```python tests
fc = 1 / (2 * np.pi * R * C)
assert abs(f_3db - fc) < 0.002 * fc, f"The corner should be about {fc:.1f} Hz; your f_3db is {f_3db}."
```

::: right
Right. Interpolating in log frequency lands within a fraction of a percent of $1/(2\pi RC)$, even though the samples are about 3% apart.
:::
:::

::: check
kind: python
given: R = 1000 | 3300; C = 47e-9 | 100e-9; k = 10 | 100

## For the same kind of filter (R = {R} Ω, C = {C} F), set `phase_at` to the phase in degrees at {k} times the corner frequency, and `gain_at` to the gain in dB there. Compute them from $H$ directly at that one frequency.

```python starter
import numpy as np

fc = 1 / (2 * np.pi * R * C)
f1 = k * fc
H1 = 0          # replace: H at f1
phase_at = 0    # replace: degrees
gain_at = 0     # replace: dB
print(phase_at, gain_at)
```

```python solution
import numpy as np

fc = 1 / (2 * np.pi * R * C)
f1 = k * fc
H1 = 1 / (1 + 1j * 2 * np.pi * f1 * R * C)
phase_at = np.degrees(np.angle(H1))
gain_at = 20 * np.log10(abs(H1))
print(phase_at, gain_at)
```

```python tests
import math
want_p = -math.degrees(math.atan(k))
want_g = -10 * math.log10(1 + k * k)
assert abs(phase_at - want_p) < 1e-6, f"At {k} times the corner the phase is {want_p:.3f} degrees; yours is {phase_at}."
assert abs(gain_at - want_g) < 1e-6, f"At {k} times the corner the gain is {want_g:.3f} dB; yours is {gain_at}."
```

::: right
Right. Close to −90° and −20 dB per decade above the corner, as the asymptotes say.
:::
:::

::: explain
## Why is the −3 dB frequency found more accurately by interpolating between samples than by taking the nearest sample?

::: model
The computed curve only exists at the sampled frequencies, which are spaced by a few percent. The nearest sample to −3 dB can therefore be off by up to half that spacing. Between neighboring samples the gain curve is smooth and nearly straight (especially against log frequency), so drawing a line between the two samples either side of −3 dB and finding where it crosses gives the frequency to a small fraction of the spacing.
:::
:::

::: practice

::: check
given: R = 1 | 2.2; C = 10 | 47
answer: 1/(2*pi*R*1e3*C*1e-9)
unit: Hz
tolerance: 0.5%

## What corner should the lab find for R = {R} kΩ and C = {C} nF?

::: misses
- [1/(R*1e3*C*1e-9)] Include 2π.
- [any] $1/(2\pi RC)$.
:::
:::

::: check
given: a = 1 | 2; b = 4 | 6; n = 100 | 500
answer: 10^((b - a)/(n - 1))
tolerance: 0.5%

## `np.logspace({a}, {b}, {n})`: what ratio separates neighboring values?

::: misses
- [(b - a)/(n - 1)] That's the step in the exponent; the ratio is 10 to that power.
- [any] $10^{(b - a)/(n - 1)}$.
:::
:::

::: check
given: g = 0.5 | 0.1 | 0.01
answer: 20*log10(g)
unit: dB
tolerance: 0.5%

## `np.abs(H)` is {g}. What is `20*np.log10(np.abs(H))`?

::: misses
- [10*log10(g)] Amplitude ratios use 20 log₁₀.
- [any] $20\log_{10}|H|$.
:::
:::
:::
