---
title: Filter design lab
heading: Designing FIR and IIR filters in Python, and checking them against a specification
eyebrow: C9 · Lesson 43 · Filter design lab
xp: 50
---

::: hook
A filter specification is a promise: this much ripple in the passband, at least this much loss in the stopband, between these frequencies. Lessons 41 and 42 gave formulas for meeting one. In this lab you'll turn the formulas into code: generate windowed-sinc taps, size Kaiser and Butterworth designs, build a bilinear low-pass, and write the checker that tells you whether a design keeps its promise.
:::

::: play
- The curve is a Butterworth low-pass, designed by the bilinear transform at 8 kHz so it loses exactly 1 dB at 1 kHz, for order N.
- The specification asks for at least 40 dB of loss from 2 kHz up: the readout gives what this order achieves there.
- Step N up from 2. Order 5 falls just short at 2 kHz; order 6 clears it, as the order formula predicts (5.99, rounded up).
:::

```sim plot
view: graph
x: f = 0..4 kHz
y: G = -80..3 dB
slider: N = 1..10 step 1 = 4
plot: -10*log(1 + (tan(pi*f/8)/(tan(pi/8)/(10^0.1 - 1)^(1/(2*N))))^(2*N)) | samples: 600 | label: Butterworth, order N
plot: -1 - 199*step(f - 1) | dashed | label: passband limit
plot: -40 + 240*step(2 - f) | dashed | label: stopband limit
readout: loss at 2 kHz, dB = 10*log(1 + (1/(tan(pi/8)/(10^0.1 - 1)^(1/(2*N))))^(2*N)) | digits: 3
```

::: predict
## A 6th-order Butterworth design meets the specification above. An FIR filter designed with a Kaiser window for the same edges and 40 dB needs how many taps?

- [ ] 6
- [ ] 12
- [x] 19
- [ ] 200

::: reveal
19: $N = (40 - 8)/(2.285 \times 2\pi \times 0.125) + 1 = 18.8$, rounded up. The IIR filter needs about 15 coefficients for its three second-order sections, so here the two are close, and the FIR filter buys exactly linear phase. With narrower transitions the gap widens quickly in the IIR filter's favor.
:::
:::

::: nameit
## What the code does

- **Windowed sinc**: taps $h[n] = w[n]\sin(\omega_c(n - M))/(\pi(n - M))$ for n = 0 to N − 1, with M = (N − 1)/2 and the center tap $\omega_c/\pi$. The Hamming window is $w[n] = 0.54 - 0.46\cos(2\pi n/(N - 1))$.
- **Kaiser sizing**: $N = \lceil(A - 8)/(2.285\,\Delta\omega) + 1\rceil$ and β by the piecewise formula of lesson 41 (0 below 21 dB).
- **Bilinear first-order low-pass**: $\Omega_c = \tan(\pi f_c/f_s)$, $b = [k, k]$ and $a = [1, (\Omega_c - 1)/(\Omega_c + 1)]$ with $k = \Omega_c/(1 + \Omega_c)$.
- **Butterworth order**: prewarp both edges, then the order formula, rounded up.
- **Checking a specification**: evaluate the response on a dense frequency grid (a zero-padded FFT of the taps does it for an FIR filter), then find the largest passband deviation and the smallest stopband loss.
:::

::: example
## A 21-tap Hamming low-pass has $\omega_c = \pi/2$. What are its center tap and the taps next to it?

::: solution
1. **Center.** The Hamming window is 1 there:
   $$\omega_c/\pi = 0.5$$
2. **Window one away.**
   $$\begin{aligned} w &= 0.54 - 0.46\cos(2\pi \times 9/20) \\ &= 0.977 \end{aligned}$$
3. **Tap one away.** The ideal tap is $\sin(\pi/2)/\pi = 0.318$, so
   $$\begin{aligned} 0.318\,w &= 0.318 \times 0.977 \\ &= 0.311 \end{aligned}$$
4. **Even offsets.** Every even offset is zero for this cutoff, because $\sin(\pi k/2) = 0$ there.

**Answer:** the center tap is 0.5, and the taps next to it are 0.311.
:::
:::

::: example
## Lesson 41 sized a Hamming low-pass for 1 kHz and 1.5 kHz at 8 kHz, with 50 dB of stopband loss, at 53 taps. What does a checker find?

::: solution
1. **Passband.** It stays within 0.03 dB of flat up to 1 kHz.
2. **Stopband.** The worst point from 1.5 kHz up is only 49.6 dB down: it misses by 0.4 dB, because the formula's transition width is an estimate.
3. **A longer filter.** At 57 taps the worst point is 52.1 dB down and the design passes.
4. **A shorter one.** A 31-tap version loses only 20.6 dB at 1.5 kHz, still in its transition band.

**Answer:** the 53-tap design misses the stopband spec by 0.4 dB (49.6 dB down); at 57 taps it passes, 52.1 dB down.
:::
:::

::: check
given: N = 4 | 5 | 6 | 7
answer: 10*log(1 + (1/(tan(pi/8)/(10^0.1 - 1)^(1/(2*N))))^(2*N))
unit: dB
tolerance: 0.5%

## A bilinear Butterworth at 8 kHz loses 1 dB at 1 kHz. What does order {N} lose at 2 kHz?

::: right
Right: {answer} dB.
:::

::: misses
- [any] Not yet. $10\log_{10}(1 + (\Omega_s/\Omega_c)^{2N})$ with $\Omega_s = \tan(\pi/4)$ and $\Omega_c = \tan(\pi/8)/(10^{0.1} - 1)^{1/2N}$.
:::
:::

::: check
kind: python

## Write `hamming_lowpass(wc, N)`: the N taps (N odd) of a Hamming-windowed ideal low-pass with cutoff `wc` radians per sample, as a list.

```python starter
import math

def hamming_lowpass(wc, N):
    return [wc / math.pi] * N
```

```python solution
import math

def hamming_lowpass(wc, N):
    M = (N - 1) // 2
    taps = []
    for n in range(N):
        k = n - M
        ideal = wc / math.pi if k == 0 else math.sin(wc * k) / (math.pi * k)
        taps.append(ideal * (0.54 - 0.46 * math.cos(2 * math.pi * n / (N - 1))))
    return taps
```

```python tests
import math
h = hamming_lowpass(math.pi / 2, 21)
assert len(h) == 21 and abs(h[10] - 0.5) < 1e-12, f"The center tap should be 0.5, got {h[10]}."
assert abs(h[11] - 0.3109) < 1e-3 and abs(h[9] - h[11]) < 1e-12, f"The taps beside it should be 0.311 and equal; got {h[9]}, {h[11]}."
assert abs(h[12]) < 1e-12, "Even offsets are zero for a cutoff of π/2."
assert abs(h[0]) < 1e-3, "The Hamming window brings the ends down to 8% of the ideal."
assert abs(sum(hamming_lowpass(0.3, 101)) - 1) < 0.01, "The DC gain, the sum of the taps, should be close to 1."
```

::: right
Right. Symmetric taps, so exactly linear phase.
:::
:::

::: check
kind: python

## Write `kaiser_design(A, dw)`: for stopband attenuation A dB and transition dw rad/sample, return `(N, beta)` with N rounded up to an integer and β by Kaiser's formula (0 for A < 21).

```python starter
def kaiser_design(A, dw):
    return (0, 0.0)
```

```python solution
import math

def kaiser_design(A, dw):
    N = math.ceil((A - 8) / (2.285 * dw) + 1)
    if A > 50:
        beta = 0.1102 * (A - 8.7)
    elif A >= 21:
        beta = 0.5842 * (A - 21) ** 0.4 + 0.07886 * (A - 21)
    else:
        beta = 0.0
    return (N, beta)
```

```python tests
import math
N, b = kaiser_design(50, 2 * math.pi * 0.0625)
assert N == 48 and abs(b - 4.5335) < 1e-3, f"50 dB over 0.0625 cycles: (48, 4.53), got {(N, b)}."
N, b = kaiser_design(80, 2 * math.pi * 0.05)
assert N == 102 and abs(b - 7.857) < 1e-3, f"80 dB over 0.05 cycles: (102, 7.857), got {(N, b)}."
N, b = kaiser_design(15, 0.5)
assert b == 0 and N == 8, f"Below 21 dB, β = 0 (a rectangular window); got {(N, b)}."
```

::: right
Right. Two formulas replace a table of windows.
:::
:::

::: check
kind: python

## Write `bilinear_lowpass(fc, fs)`: the first-order bilinear low-pass with its −3 dB point at fc, as `(b, a)` with b = [b0, b1] and a = [1, a1].

```python starter
def bilinear_lowpass(fc, fs):
    return ([1, 0], [1, 0])
```

```python solution
import math

def bilinear_lowpass(fc, fs):
    W = math.tan(math.pi * fc / fs)
    k = W / (1 + W)
    return ([k, k], [1, (W - 1) / (W + 1)])
```

```python tests
import cmath, math
b, a = bilinear_lowpass(1000, 8000)
assert abs(b[0] - 0.29289) < 1e-5 and abs(a[1] + 0.41421) < 1e-5, f"1 kHz at 8 kHz: b0 = 0.2929, a1 = -0.4142; got {b}, {a}."
for fc, fs in [(1000, 8000), (3000, 8000), (50, 1000)]:
    b, a = bilinear_lowpass(fc, fs)
    z = cmath.exp(2j * math.pi * fc / fs)
    H = (b[0] + b[1] / z) / (a[0] + a[1] / z)
    assert abs(abs(H) - 1 / math.sqrt(2)) < 1e-9, f"The gain at {fc} Hz should be exactly 0.7071, got {abs(H):.5f}."
    assert abs((b[0] + b[1]) / (a[0] + a[1]) - 1) < 1e-9, "The DC gain should be 1."
```

::: right
Right. Prewarping puts the −3 dB point exactly where it was asked for.
:::
:::

::: check
kind: python

## Write `butter_order(fp, fst, Ap, As, fs)`: the Butterworth order for at most Ap dB loss up to fp and at least As dB from fst, designed by the bilinear transform at fs (prewarp both edges).

```python starter
def butter_order(fp, fst, Ap, As, fs):
    return 1
```

```python solution
import math

def butter_order(fp, fst, Ap, As, fs):
    Wp, Ws = math.tan(math.pi * fp / fs), math.tan(math.pi * fst / fs)
    n = math.log10((10 ** (As / 10) - 1) / (10 ** (Ap / 10) - 1)) / (2 * math.log10(Ws / Wp))
    return math.ceil(n - 1e-9)
```

```python tests
assert butter_order(1000, 2000, 1, 40, 8000) == 6, f"The lesson's example needs order 6, got {butter_order(1000, 2000, 1, 40, 8000)}."
assert butter_order(1000, 2000, 3, 20, 48000) == 4, f"Gentler, at 48 kHz: order 4, got {butter_order(1000, 2000, 3, 20, 48000)}."
assert butter_order(3000, 3500, 0.5, 60, 8000) == 11, f"A narrow transition near Nyquist: order 11, got {butter_order(3000, 3500, 0.5, 60, 8000)}."
```

::: right
Right. Without prewarping, the last case would come out as order 52 instead of 11, because near Nyquist the edges' ratio is far larger once warped.
:::
:::

::: check
kind: python

## Write `meets_spec(h, fs, fp, fst, ripple_db, atten_db)`: True if the FIR filter h stays within ±ripple_db of 0 dB up to fp and at least atten_db down from fst to fs/2. Evaluate it with a 16384-point zero-padded `rfft`.

```python starter
def meets_spec(h, fs, fp, fst, ripple_db, atten_db):
    return True
```

```python solution
import numpy as np

def meets_spec(h, fs, fp, fst, ripple_db, atten_db):
    H = np.abs(np.fft.rfft(np.asarray(h, dtype=float), 16384))
    f = np.arange(len(H)) * fs / 16384
    db = 20 * np.log10(np.maximum(H, 1e-300))
    passband = db[f <= fp]
    stopband = db[f >= fst]
    return bool(np.max(np.abs(passband)) <= ripple_db and np.max(stopband) <= -atten_db)
```

```python tests
import math
def ham(wc, N):
    M = (N - 1) // 2
    return [(wc / math.pi if n == M else math.sin(wc * (n - M)) / (math.pi * (n - M))) * (0.54 - 0.46 * math.cos(2 * math.pi * n / (N - 1))) for n in range(N)]
wc = 2 * math.pi * 1250 / 8000
assert meets_spec(ham(wc, 57), 8000, 1000, 1500, 0.1, 50), "57 taps reach 52 dB from 1.5 kHz and pass."
assert not meets_spec(ham(wc, 53), 8000, 1000, 1500, 0.1, 50), "53 taps reach only 49.6 dB at 1.5 kHz and should fail."
assert not meets_spec(ham(wc, 31), 8000, 1000, 1500, 0.1, 50), "The 31-tap version is far too short."
assert not meets_spec(ham(wc, 61), 8000, 1000, 1500, 0.1, 60), "Hamming can't reach 60 dB at any length."
```

::: right
Right. Every design flow ends with a check like this, because formulas only estimate.
:::
:::

::: explain
## Why check a filter against its specification on a dense frequency grid, rather than trusting the design formulas?

::: model
The design formulas are estimates. Window lengths come from approximate transition widths, Kaiser's formulas are curve fits, and rounding, quantized coefficients or an unlucky cutoff can leave a design a decibel or two short at one frequency. A filter's worst ripple or weakest stopband point can fall between any coarse set of test frequencies, so the response has to be evaluated finely enough to catch every peak, which a heavily zero-padded FFT does cheaply. Checking the actual taps against the actual limits turns "should work" into "does work", and it catches mistakes such as a wrong cutoff or a forgotten prewarp that formulas would never reveal.
:::
:::
