CodeRigor

LESSON

Filters you can measure

Build moving averages, windowed-sinc, one-pole and biquad filters, then measure each one: gain at a frequency, the minus 3 dB point, and linear phase.

A filter is a rule that turns one stream of samples into another, and the frequency view tells you what it does to each tone. This lesson pairs with Coding Adventure: Sound (and the Fourier Transform) and Coding Adventure: Additive Synthesis by Sebastian Lague, linked under Watch & read. Those videos are about spectra and about building sound out of sine waves, not about filtering, so the pairing is on the frequency idea: here you shape a spectrum instead of reading one. You build a moving average, a windowed-sinc filter, a one-pole smoother and a biquad low-pass in NumPy, and a function that reports the gain of any of them at any frequency.

There are two families. A finite impulse response (FIR) filter computes each output as a weighted sum of the latest inputs: y[i] = Σ h[k] · x[i − k]. The weights h are the taps, and they are also the filter's output when the input is a single 1 followed by zeros, which is why h is called the impulse response. A moving average is the FIR filter whose n taps are all 1/n. Samples before the start of the signal count as 0, so the first outputs are smaller than they should be.

A recursive (IIR) filter also feeds back its own past outputs. The biquad uses two of each: y[i] = (b₀x[i] + b₁x[i−1] + b₂x[i−2] − a₁y[i−1] − a₂y[i−2]) / a₀. Feedback lets two or three numbers give a response that an FIR filter needs dozens of taps for. The price is that the impulse response never reaches zero exactly.

The frequency view comes from one formula. A filter's complex gain at frequency f is H = (b₀ + b₁z⁻¹ + b₂z⁻²) / (a₀ + a₁z⁻¹ + a₂z⁻²) with z⁻¹ = e^(−jω) and ω = 2πf / rate. Its size |H| says how much a tone at f is scaled, and its angle says how much it is delayed. For an FIR filter the denominator is 1, and H is the DFT of the taps.

Three low-passes, measured at 8000 samples per second
Gain against frequency for a 4-tap moving average, a 31-tap windowed sinc and a second-order Butterworth biquad, the last two designed for 1000 Hz. The marked point is the Butterworth gain at its cutoff.
Three low-passes, measured at 8000 samples per second
Gain against frequency for a 4-tap moving average, a 31-tap windowed sinc and a second-order Butterworth biquad, the last two designed for 1000 Hz. The marked point is the Butterworth gain at its cutoff.

The moving average is a poor low-pass. For n = 4 at 8000 samples per second its gain is zero at 2000 Hz, where one cycle spans exactly four samples and the average of four consecutive values cancels. Above that the gain rises again.

Python
import numpy as np

n, rate = 4, 8000
for f in (0, 1000, 2000):
    w = 2 * np.pi * f / rate
    gain = abs(sum(np.exp(-1j * w * k) for k in range(n))) / n
    print(f, round(float(gain), 4))

A better FIR low-pass starts from the ideal one, whose taps are a sinc: 2f_c · sinc(2f_c t) with f_c = cutoff / rate, centred on the middle tap. That sinc is infinitely long, so you cut it to an odd number of taps and multiply by a Hamming window to soften the cut. Divide by the sum of the taps so a constant input passes with gain exactly 1. The taps are symmetric around the middle one, and that symmetry makes the phase linear: every frequency is delayed by the same (taps − 1) / 2 samples.

The one-pole filter is y[i] = (1 − a)·x[i] + a·y[i − 1] with a = e^(−2π · cutoff / rate). A step input rises as 1 − aⁿ. The biquad is designed from an analogue prototype by the bilinear transform. With k = tan(π · cutoff / rate), a₀ = 1 + k/q + k², b = [k², 2k², k²] / a₀ and a = [a₀, 2(k² − 1), 1 − k/q + k²] / a₀, which makes a[0] equal to 1. The knob q sets the shape near the cutoff: q = 1/√2 = 0.7071 is the Butterworth setting, the flattest passband, and the gain there is 1/√2, which is −3 dB.

Python
import numpy as np

def design(cutoff, rate, q, prewarp=True):
    k = np.tan(np.pi * cutoff / rate) if prewarp else np.pi * cutoff / rate
    a0 = 1 + k / q + k * k
    b = np.array([k * k, 2 * k * k, k * k]) / a0
    a = np.array([a0, 2 * (k * k - 1), 1 - k / q + k * k]) / a0
    return b, a

def gain(b, a, f, rate):
    z = np.exp(-2j * np.pi * f / rate)
    return abs((b[0] + b[1] * z + b[2] * z * z) / (a[0] + a[1] * z + a[2] * z * z))

b, a = design(1000, 8000, 0.7071)
print(b.round(4).tolist(), a.round(4).tolist())
print([round(float(gain(b, a, f, 8000)), 4) for f in (0, 1000, 4000)])
for fc in (1000, 3000):
    print(fc, round(float(gain(*design(fc, 8000, 2 ** -0.5), fc, 8000)), 4),
          round(float(gain(*design(fc, 8000, 2 ** -0.5, False), fc, 8000)), 4))

The last two lines show the reason for the tangent. It is called prewarping: the digital frequency axis stops at half the sample rate, and tan stretches the axis so the cutoff you asked for lands where you asked. Skip it and the gain at 1000 Hz is 0.6685 instead of 0.7071, and at 3000 Hz it is 0.2317.

The mistakes are quiet ones. Dividing only some of the coefficients by a₀ keeps a plausible-looking filter with the wrong gain. Forgetting the prewarp leaves DC and Nyquist right, because they are fixed by the structure, and shifts only the cutoff, so a test of those two points never notices. In the recursion, overwriting the old samples before using them, or reading y from the input array instead of the output, ruins the feedback.

Two ways to get the same gain
start / 4
Measure the gain from the filter's own output, then compare it with the formula. Agreement at many frequencies is strong evidence that the recursion and the formula describe the same filter.
Two ways to get the same gain
Measure the gain from the filter's own output, then compare it with the formula. Agreement at many frequencies is strong evidence that the recursion and the formula describe the same filter.

How do you check any of this? Run a unit impulse through the recursion for a few hundred samples and take its DFT: the result must equal the formula at each bin's frequency. Check that the Butterworth gain at the cutoff is 0.7071 for several cutoffs, that the sinc taps are symmetric, and that fir equals np.convolve cut to the input length. The last snippet runs the first one.

Python
import numpy as np

rate, taps, cutoff = 8000, 31, 1000
t = np.arange(taps) - (taps - 1) / 2
fc = cutoff / rate
h = 2 * fc * np.sinc(2 * fc * t) * np.hamming(taps)
h /= h.sum()
print(len(h), bool(np.allclose(h, h[::-1])), round(float(h.sum()), 6))

def gain(f):
    w = 2 * np.pi * f / rate
    return abs(sum(c * np.exp(-1j * w * k) for k, c in enumerate(h)))

print([round(float(gain(f)), 3) for f in (0, 1000, 3000)])

# the biquad: run an impulse through the recursion and take its DFT
b = [0.097631, 0.195262, 0.097631]
a = [1.0, -0.942806, 0.333329]
x = np.zeros(256)
x[0] = 1.0
y = np.zeros(256)
for i in range(256):
    y[i] = sum(b[k] * x[i - k] for k in range(3) if i >= k) - sum(a[k] * y[i - k] for k in (1, 2) if i >= k)
print(round(float(abs(np.fft.rfft(y)[32])), 4))   # bin 32 of 256 is 1000 Hz

The windowed sinc is 0.501 at its cutoff, not 0.7071, so two filters can mean different things by the word cutoff. Its passband also ripples a little above 1, by about 0.5 percent here. These checks confirm that the filter does what the formulas say. They do not tell you that a filter sounds right, and they say nothing about the choice of cutoff, which you still have to make by listening.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Builds sounds from sine waves with envelopes and harmonics. It does not teach filtering, but it is the synthesis side of the spectrum that a low-pass reshapes, so it shows what a filter would be removing.