Filters made of arithmetic
In Frequency response and filters you built filters from resistors, capacitors and inductors. Their behaviour depends on component values that drift with temperature and age and come with tolerances of a few per cent. Once a signal has been sampled, as in Sampling and the FFT, a filter can instead be a short program: multiply recent samples by fixed numbers and add them up. Such a digital filter behaves identically on every unit ever built, never drifts, can be changed by a software update, and can do things no practical analogue circuit can, such as a perfectly linear phase or a stopband 100 dB deep.
Digital filters are everywhere. A smartwatch smooths its accelerometer readings before counting steps; an electrocardiograph removes mains hum and baseline wander from a heartbeat; a hearing aid splits sound into frequency bands and amplifies each to suit its wearer; a radio receiver selects one channel from a crowded band; the decimation stage of every oversampling converter is a sharp digital low-pass filter. This lesson gives you the theory to analyse such filters (difference equations, the z-transform, poles and zeros) and the practice to design them, run them and measure what they do.
Difference equations: FIR and IIR
A digital filter computes each output sample from current and past inputs and, possibly, past outputs.
Definition— Linear constant-coefficient difference equation
A causal digital filter of this kind computes with fixed coefficients and (and ). If all with are zero, the filter is FIR (finite impulse response): its impulse response is just and then zeros. If it feeds back past outputs, the filter is IIR (infinite impulse response): an impulse can echo for ever.
An FIR filter is a convolution with its coefficients, so everything in Signals, systems and convolution applies directly, including stability: a finite list of coefficients always has a finite absolute sum. An IIR filter can produce a long impulse response from a handful of coefficients, which makes it cheap, but its feedback can also make it unstable. The program runs the difference equation directly on an impulse for three small filters, finds their poles and zeros (explained in the next section), and evaluates the frequency response of the stable ones.
import numpy as np
def lfilter(b, a, x):
"""Run the difference equation a[0] y[n] = sum b[k] x[n-k] - sum_{k>=1} a[k] y[n-k]."""
y = np.zeros(len(x))
for n in range(len(x)):
acc = sum(b[k] * x[n - k] for k in range(len(b)) if n - k >= 0)
acc -= sum(a[k] * y[n - k] for k in range(1, len(a)) if n - k >= 0)
y[n] = acc / a[0]
return y
def freq_response(b, a, f, fs):
"""H(e^{jw}) = B(e^{jw}) / A(e^{jw}) with z^{-1} = e^{-jw}, w = 2 pi f / fs."""
zinv = np.exp(-2j * np.pi * np.asarray(f) / fs)
return np.polyval(b[::-1], zinv) / np.polyval(a[::-1], zinv)
def show(roots):
"""Roots as tidy strings, sorted, with -0 printed as 0."""
out = []
for r in sorted(roots, key=lambda z: (round(z.real, 6), round(z.imag, 6))):
re, im = round(r.real, 3) + 0.0, round(r.imag, 3) + 0.0
out.append(f"{re:g}{im:+g}j" if im else f"{re:g}")
return "[" + ", ".join(out) + "]"
fs = 1000
impulse = np.zeros(12)
impulse[0] = 1
filters = {
"4-point moving average (FIR)": ([0.25, 0.25, 0.25, 0.25], [1.0]),
"exponential smoother (IIR)": ([0.2], [1.0, -0.8]),
"unstable: y = x + 1.1 y[n-1]": ([1.0], [1.0, -1.1]),
}
for name, (b, a) in filters.items():
h = lfilter(b, a, impulse)
poles = np.roots(a) if len(a) > 1 else np.array([])
zeros = np.roots(b) if len(b) > 1 else np.array([])
print(name)
print(" impulse response:", np.round(h[:8], 3))
print(" poles:", show(poles), " zeros:", show(zeros))
if np.all(np.abs(poles) < 1):
H = freq_response(np.array(b), np.array(a), [0, 50, 125, 250, 500], fs)
print(" |H| at 0, 50, 125, 250, 500 Hz:", np.round(np.abs(H), 3))
else:
print(" a pole is outside the unit circle: the impulse response grows without bound")The moving average's impulse response stops after four samples. The exponential smoother , a favourite for cleaning up sensor readings because it needs one multiplication and one stored value, has an impulse response that decays for ever. Changing the feedback coefficient to 1.1 gives an impulse response that grows without limit. Both smoothers pass DC with gain 1 and attenuate higher frequencies, but differently: the moving average has exact zeros of gain at 250 Hz and 500 Hz, while the smoother just rolls off.
The z-transform, poles and zeros
The tool that turns difference equations into algebra is the z-transform, the discrete-time relative of the Laplace transform of the next lesson.
Definition— z-transform
The z-transform of a sequence is the function of a complex variable defined for the where the sum converges, its region of convergence (ROC). For a sequence that is zero for (a causal sequence) the ROC is the outside of a circle, .
The key property is what a delay does. If , then . A delay of one sample is multiplication by . Taking the z-transform of the whole difference equation therefore gives and so the filter's transfer function is also the z-transform of the impulse response , and the convolution theorem holds in this form too: convolution of sequences is multiplication of their z-transforms.
Frequency response. Setting with turns the z-transform into the discrete-time Fourier transform, so the frequency response is evaluated on the unit circle: . The point () is DC; going anticlockwise round the circle raises the frequency, reaching at , the Nyquist frequency. (Going on round the lower half gives the negative frequencies.)
Poles and zeros. Multiply the numerator and denominator by a power of so they become polynomials in . Their roots are the zeros (where ) and the poles (where is infinite) of the filter. Factored, This gives a picture of the frequency response. At a frequency , each factor is the distance from the point on the unit circle to a zero, and each the distance to a pole. So is small where the circle passes close to a zero (and exactly zero if the zero is on the circle) and large where it passes close to a pole.
The moving average illustrates this. Its zeros are at and , all on the unit circle, at 500 Hz and 250 Hz, which is why the program found its gain exactly zero at those frequencies. A filter designer turns this round: to remove 50 Hz mains hum from an electrocardiogram sampled at 500 Hz, put a pair of zeros on the unit circle at angle , and a pair of poles just inside them at the same angle (radius 0.98, say), so that the gain recovers within a few hertz on either side. That is a notch filter, and an exercise below asks you to analyse one.
Theorem— Stability of a causal digital filter
A causal filter with a rational transfer function (with common factors cancelled) is BIBO stable if and only if all its poles lie strictly inside the unit circle, .
Proof
If the poles are distinct, a partial-fraction expansion writes as a polynomial in plus terms , and the causal sequence with transform is for (sum the geometric series). So for large enough, , with every because no factor cancels. If every , then , so the filter is stable by the absolute-summability criterion of the first lesson. If some , the term does not decay, and does not tend to zero (terms from poles of the same largest modulus cannot cancel for all ), so the sum diverges. Repeated poles add factors , which change nothing: is still summable when .
∎
The exponential smoother's pole at 0.8 is inside: stable. The filter with feedback 1.1 has its pole at 1.1, outside: unstable, exactly as its growing impulse response showed. An FIR filter has all its poles at , so it is always stable.
Designing an FIR low-pass filter by windowing
The ideal low-pass filter passes everything below a cut-off with gain 1 and nothing above. Its frequency response is a rectangle, so its impulse response, by the transform pairs of Fourier analysis, is a sinc: It is infinitely long and non-causal. The window method makes it practical in three steps: keep only taps centred on ; delay them by samples so the filter is causal; and multiply by a window that tapers the ends. Without the taper, the abrupt truncation produces exactly the Gibbs ripple of the Fourier series, now in the frequency response. The program designs a 51-tap low-pass with Hz at kHz using three windows.
import numpy as np
def lowpass_fir(num_taps, fc, fs, window):
"""Windowed-sinc low-pass: the ideal impulse response (2 fc / fs) sinc(2 fc n / fs), truncated and tapered."""
n = np.arange(num_taps) - (num_taps - 1) / 2 # symmetric about the middle tap
h = 2 * fc / fs * np.sinc(2 * fc * n / fs)
h *= window(num_taps)
return h / np.sum(h) # exact gain 1 at DC
def response_db(h, f, fs):
H = np.array([np.sum(h * np.exp(-2j * np.pi * fk * np.arange(len(h)) / fs)) for fk in f])
return 20 * np.log10(np.abs(H) + 1e-15)
fs, fc, taps = 1000, 100, 51
f = np.arange(0, 500.5, 0.5)
print(f"{taps}-tap low-pass, cut-off {fc} Hz, fs = {fs} Hz")
print("window gain at 100 Hz -1 dB at first null at worst stopband gain")
for name, w in [("rectangular", np.ones), ("Hamming", np.hamming), ("Blackman", np.blackman)]:
h = lowpass_fir(taps, fc, fs, w)
db = response_db(h, f, fs)
f_1db = f[np.argmax(db < -1)] # first frequency below -1 dB
i = np.argmax(f > fc)
while db[i + 1] < db[i]: # walk down to the first null
i += 1
print(f"{name:12} {db[f == fc][0]:7.2f} dB {f_1db:5.1f} Hz {f[i]:5.1f} Hz {db[i:].max():6.1f} dB")
h = lowpass_fir(taps, fc, fs, np.hamming)
print("\nHamming design: symmetric taps?", np.allclose(h, h[::-1]),
f"-> linear phase, delay {(taps - 1) // 2} samples = {(taps - 1) / 2 / fs * 1e3:.0f} ms")
print("middle taps:", np.round(h[22:29], 4))
db = response_db(h, f, fs)
print("\n f (Hz) gain")
for fk in (0, 50, 80, 100, 120, 140, 200, 300, 400):
level = round(db[f == fk][0], 1) + 0.0
bar = "#" * max(0, int(round((level + 80) / 2)))
print(f"{fk:7} {level:7.1f} dB {bar}")The table shows the trade-off that governs all window designs. The rectangular window (plain truncation) gives the sharpest transition, from dB at 90.5 Hz to the first null at 112.5 Hz, but its stopband is only 22 dB down, the Gibbs overshoot in disguise. The Hamming window holds the stopband below dB with a transition about twice as wide, and the Blackman window reaches dB with a wider transition still. To get a narrower transition with the same window, use more taps: the transition width is roughly , with about 1 for the rectangular, 3.3 for the Hamming and 5.5 for the Blackman window.
Linear phase. The taps are symmetric, , so the filter's frequency response is a real function times : every frequency is delayed by exactly samples, here 25 samples or 25 ms. A constant delay preserves the shape of a waveform, which matters for pulses in data communication, for heartbeat waveforms, and for audio crossovers. This is something an analogue filter cannot do exactly.
The window method is simple and robust, but not optimal. In practice engineers more often use the Parks–McClellan algorithm (in SciPy, scipy.signal.remez), which finds the filter with the smallest maximum error for a given length, with equal-sized ripples across each band, or least-squares designs. All produce the same kind of object: a symmetric list of taps.
IIR filters, biquads and the bilinear transform
An FIR filter needs many taps for a sharp transition. An IIR filter gets its sharpness from poles placed close to the unit circle, and needs far fewer coefficients; the price is phase that is not linear and the possibility of instability. The usual way to design one is to borrow a classic analogue design (Butterworth, Chebyshev, elliptic), whose properties are well understood, and convert it to discrete time.
Definition— Bilinear transform
The bilinear transform converts an analogue transfer function into a digital one by the substitution It maps the left half of the s-plane onto the inside of the unit circle, so a stable analogue filter always becomes a stable digital one, and it maps the imaginary axis onto the unit circle, with
The whole infinite analogue frequency axis is squeezed into the digital range from 0 to , so frequencies are warped: the mapping is nearly linear at low frequencies and compressed near . To make a critical frequency land where you want it, you pre-warp: design the analogue filter with its cut-off at instead of .
The workhorse of IIR filtering is the biquad, a second-order section with two poles and two zeros:
The program designs a second-order Butterworth low-pass (cut-off 100 Hz at kHz) as one biquad, by pre-warping and applying the bilinear transform to . Then it asks what happens to a sixth-order filter when its coefficients are rounded to a fixed number of fractional bits, as they must be on a fixed-point processor.
import numpy as np
fs = 1000.0
def butterworth_biquad(fc, fs):
"""Second-order Butterworth low-pass by the bilinear transform s = 2 fs (z - 1)/(z + 1).
Returns b = [b0, b1, b2], a = [1, a1, a2]."""
wa = 2 * fs * np.tan(np.pi * fc / fs) # pre-warp so the -3 dB point lands at fc
K = wa / (2 * fs) # tan(pi fc / fs)
q = np.sqrt(2) # H(s) = wa^2 / (s^2 + sqrt(2) wa s + wa^2)
d = 1 + q * K + K * K
b = np.array([K * K, 2 * K * K, K * K]) / d
a = np.array([1, 2 * (K * K - 1) / d, (1 - q * K + K * K) / d])
return b, a
def gain_db(b, a, f):
zinv = np.exp(-2j * np.pi * f / fs)
return 20 * np.log10(abs(np.polyval(b[::-1], zinv) / np.polyval(a[::-1], zinv)))
b, a = butterworth_biquad(100, fs)
print("biquad b =", np.round(b, 6), " a =", np.round(a, 6))
print("poles:", np.round(np.abs(np.roots(a)), 4), "in magnitude (inside the unit circle: stable)")
for f in (0, 50, 100, 200, 400):
print(f" {f:3} Hz: {round(gain_db(b, a, f), 2) + 0.0:7.2f} dB")
# Coefficient quantisation: a 6th-order Butterworth low-pass at 20 Hz, as one big polynomial
# (direct form) or as three biquads, with coefficients rounded to F fractional bits.
order, fc = 6, 20.0
wa = 2 * fs * np.tan(np.pi * fc / fs)
s_poles = wa * np.exp(1j * np.pi * (0.5 + (2 * np.arange(order) + 1) / (2 * order)))
z_poles = (1 + s_poles / (2 * fs)) / (1 - s_poles / (2 * fs)) # bilinear map of each pole
a_direct = np.real(np.poly(z_poles))
print(f"\n6th-order denominator (direct form): {np.round(a_direct, 3)}")
print(f"true largest pole radius: {np.abs(z_poles).max():.4f}")
print(" F bits direct form: largest |pole| three biquads: largest |pole|")
for F in (8, 12, 14, 20, 24):
quant = lambda c: np.round(c * 2 ** F) / 2 ** F
r_direct = np.abs(np.roots(quant(a_direct))).max()
r_biquad = max(np.abs(np.roots(quant(np.array([1, -2 * p.real, abs(p) ** 2])))).max()
for p in z_poles if p.imag > 0)
print(f"{F:6} {r_direct:20.4f} {r_biquad:20.4f}")The biquad is exactly what was ordered: 0 dB at DC, dB at the 100 Hz cut-off thanks to pre-warping, and steeper attenuation than an analogue Butterworth near 500 Hz, because the bilinear transform puts both zeros at . Five coefficients give a respectable low-pass, though with a far gentler roll-off than the 51-tap FIR design: dB at 200 Hz, where the FIR filter reaches dB.
The second table is the reason IIR filters are almost never implemented as one high-order difference equation. The sixth-order filter's poles cluster near with radius up to 0.968, and the coefficients of its denominator polynomial are large numbers (up to 15.6) that nearly cancel. Round them to 12 or 14 fractional bits and the poles move outside the unit circle: the filter is unstable. Even 20 bits leave the largest pole visibly displaced. The same filter built as three biquads keeps its poles in place at every precision tested. Roots of high-degree polynomials are extremely sensitive to their coefficients; roots of quadratics are not. So practical IIR filters are cascades of biquads, called second-order sections, which is why SciPy offers sosfilt and microcontroller libraries offer biquad-cascade functions.
Fixed-point effects, in overview
Many filters run on processors without floating-point hardware, or in FPGAs and custom chips where every bit costs area and power. Numbers are then fixed-point: integers with an implied binary point, such as the Q15 format, which stores values from to just under in 16 bits. Four effects need attention.
- Coefficient quantisation. As the program showed, rounding coefficients moves poles and zeros, changing the response and possibly destroying stability. Biquad cascades, and structures designed for low sensitivity, keep this under control.
- Round-off noise. Every multiplication produces a longer result that must be rounded back to the word length, adding a tiny error, a noise source at every multiplier. In an IIR filter the noise passes through the feedback and can be amplified, especially when poles sit close to the unit circle. Wider accumulators help: DSP processors typically accumulate in 32 to 40 bits even when data are 16 bits.
- Overflow. A sum can exceed the largest representable number. In two's-complement arithmetic it then wraps round to a large negative value, a violent error; saturating arithmetic clips instead, which is much gentler. Designers scale signals between sections so overflow is rare.
- Limit cycles. With rounding inside a feedback loop, an IIR filter whose input has fallen to zero can keep producing a small oscillation for ever, instead of decaying to zero. It is usually tiny but can be audible in quiet passages of audio.
An FIR filter has no feedback, so it cannot have limit cycles, and its round-off noise is not amplified by recursion. This robustness, together with linear phase, is why FIR filters dominate in FPGAs, communications and multirate systems, while IIR biquads dominate where cheapness and low latency matter: audio equalisers, sensor smoothing, control loops.
Filtering a noisy signal
Here is a complete small task. A slow sensor signal, made of 2 Hz and 5 Hz components, is sampled at 1 kHz. It arrives buried in broadband noise and 50 Hz mains pickup. We compare a 201-tap FIR low-pass (Hamming window) with a fourth-order Butterworth IIR built from two biquads, both with a 20 Hz cut-off, and measure the signal-to-noise ratio against the known clean signal.
import numpy as np
fs = 1000.0
t = np.arange(0, 3.0, 1 / fs)
clean = np.sin(2 * np.pi * 2 * t) + 0.5 * np.sin(2 * np.pi * 5 * t) # the wanted slow signal
rng = np.random.default_rng(42)
noise = 0.5 * rng.standard_normal(len(t)) # broadband sensor noise
hum = 0.8 * np.sin(2 * np.pi * 50 * t) # mains pickup at 50 Hz
x = clean + noise + hum
def snr_db(estimate, delay=0, skip=500):
"""SNR of an estimate of `clean`, after undoing a delay and ignoring the start-up transient."""
e = estimate[skip + delay:]
c = clean[skip:len(clean) - delay]
return 10 * np.log10(np.mean(c ** 2) / np.mean((e - c) ** 2))
# 1. FIR: 201-tap Hamming-windowed sinc, cut-off 20 Hz. Linear phase, delay (201 - 1) / 2 = 100 samples.
taps = 201
n = np.arange(taps) - (taps - 1) / 2
h = 2 * 20 / fs * np.sinc(2 * 20 * n / fs) * np.hamming(taps)
h /= h.sum()
y_fir = np.convolve(x, h)[:len(x)]
# 2. IIR: two Butterworth biquads in cascade (4th order), cut-off 20 Hz, by the bilinear transform.
def biquad_sections(order, fc):
wa = 2 * fs * np.tan(np.pi * fc / fs)
sections = []
for k in range(order // 2):
p = wa * np.exp(1j * np.pi * (0.5 + (2 * k + 1) / (2 * order))) # analogue pole
zp = (1 + p / (2 * fs)) / (1 - p / (2 * fs)) # digital pole
a = np.array([1.0, -2 * zp.real, abs(zp) ** 2])
b = np.array([1.0, 2.0, 1.0]) * a.sum() / 4 # zeros at z = -1, gain 1 at DC
sections.append((b, a))
return sections
def run_biquad(b, a, x):
y = np.zeros(len(x))
x1 = x2 = y1 = y2 = 0.0
for i, xi in enumerate(x):
yi = b[0] * xi + b[1] * x1 + b[2] * x2 - a[1] * y1 - a[2] * y2
x2, x1, y2, y1 = x1, xi, y1, yi
y[i] = yi
return y
y_iir = x
for b, a in biquad_sections(4, 20.0):
y_iir = run_biquad(b, a, y_iir)
best = min(range(60), key=lambda d: -snr_db(y_iir, d))
print(f"input SNR: {snr_db(x):6.1f} dB")
print(f"FIR (201 taps), its 100-sample delay removed: {snr_db(y_fir, 100):6.1f} dB")
print(f"IIR (4th order), no delay removed: {snr_db(y_iir, 0):6.1f} dB")
print(f"IIR, best whole-sample delay ({best}) removed: {snr_db(y_iir, best):6.1f} dB")
print(f"multiplications per sample: FIR {taps}, IIR {2 * 5}")
print("\n t (s) clean noisy FIR out (100 samples later)")
for i in range(1000, 1400, 40):
bar = " " * int(round(20 + 12 * y_fir[i + 100])) + "*"
c, xn, yf = (round(v, 3) + 0.0 for v in (clean[i], x[i], y_fir[i + 100]))
print(f"{t[i]:5.2f} {c:+.3f} {xn:+.3f} {yf:+.3f} {bar}")The input SNR is about 0 dB: noise and hum together are as strong as the signal. Both filters lift it to about 17 dB, a fifty-fold reduction in error power, and the hum disappears entirely; what remains is the noise that lies inside the 0–20 Hz passband, which no low-pass filter can remove. The comparison of costs is the interesting part:
- The FIR filter needs 201 multiplications per sample and delays everything by 100 ms, but every frequency by the same amount, so the output is an undistorted, delayed copy.
- The IIR filter needs 10 multiplications per sample and delays the signal by only about 20 ms. But compared without correcting for its delay, it scores only 8.3 dB, and even at its best single delay it scores slightly less than the FIR, because its delay differs between the 2 Hz and 5 Hz components (its phase is not linear), which slightly distorts the waveform.
For offline processing, where the whole record is available, there is a third option: run an IIR filter forwards and then backwards over the data (scipy.signal.filtfilt), which cancels the phase shift exactly. It cannot be done in real time, because the backward pass needs the future.
Digital filters in industry
- Audio. Equalisers, crossovers and room correction in phones, cars and studios are mostly biquad cascades, often with coefficients from closed-form formulas such as the Audio EQ Cookbook; hearing aids run banks of filters within a few milliseconds of latency.
- Communications. Software-defined radios, from hobbyists' receivers running GNU Radio to base stations, select channels and change sample rates with multirate FIR filters: polyphase structures that compute only the samples that will be kept, and very cheap cascaded integrator–comb (CIC) filters for large rate changes.
- Data conversion. Every sigma-delta converter contains a digital decimation filter that removes the shaped quantisation noise and the out-of-band signals; Sensors and data conversion returns to this.
- Control and power. Motor drives and power converters filter their current and voltage measurements with short IIR filters inside control loops that run tens of thousands of times a second, where every sample of delay erodes the stability margin (see Feedback control).
- Biomedical. Electrocardiograph and EEG front ends use notch filters for 50 or 60 Hz hum and band-pass filters chosen so as not to distort clinically important waveform features, which is one reason linear-phase FIR filters are common there.
On hardware, FPGAs contain hundreds or thousands of dedicated multiply-accumulate blocks that implement FIR filters at hundreds of millions of samples per second, and microcontrollers use libraries such as Arm's CMSIS-DSP. For design, scipy.signal (firwin, remez, butter, ellip, sosfilt) is the standard open-source toolkit, and the coefficients it produces are what gets loaded into the hardware.
Common misconceptions
Misconception
"IIR filters are always better because they need fewer coefficients." They are cheaper and have lower latency, but their phase is not linear, they can become unstable after quantisation, and they suffer limit cycles and amplified round-off noise. FIR filters cost more arithmetic and buy robustness and linear phase. The right choice depends on the application.
Misconception
"A good filter removes the noise." It removes the noise outside the passband. Noise at the same frequencies as the signal passes straight through, as the 17 dB ceiling in the example shows. To do better you need more information: averaging repeated measurements, a model of the signal (as in a Kalman filter), or a better sensor.
Misconception
"If it is stable in floating point, it is stable in the product." A sixth-order direct-form filter stable in double precision became unstable with 14-bit coefficients. Fixed-point implementations must be checked with the actual word lengths, usually by simulating them bit for bit.
Misconception
"More taps (or higher order) is always better." More taps sharpen the transition, but cost computation and, for an FIR filter, latency: a 2001-tap linear-phase filter at 1 kHz delays its output by a whole second, useless in a control loop. Choose the least demanding specification that does the job.
Misconception
"The bilinear transform copies the analogue frequency response exactly." It copies it with the frequency axis warped by . Only the frequencies you pre-warp land exactly where intended, and the warping is severe near .
Exercises
1. Digital filters
Warm-upHumanA linear-phase FIR filter has 101 symmetric taps and runs at 8 kHz. By how many samples does it delay every frequency component?
2. Digital filters
CoreHumanThe 4-point moving average runs at kHz. Besides 500 Hz, at what frequency between 0 and 500 Hz is its gain exactly zero? Answer in hertz.
3. Digital filters
CoreHumanEach option gives the poles of a causal digital filter. Which filters are BIBO stable? Select all that apply.
4. Digital filters
StretchHumanAn analogue low-pass filter with its −3 dB point at 100 Hz is converted to a digital filter at kHz with the bilinear transform , without pre-warping. At what frequency does the digital filter's −3 dB point fall? Give the nearest whole hertz.
5. Digital filters
CoreHumanWhich application most clearly calls for a linear-phase FIR filter rather than an IIR biquad cascade?
6. Digital filters
CoreComputationalWrite lfilter(b, a, x), which runs the difference equation on the input array x, treating and as zero before . (This is what scipy.signal.lfilter does.) The tests use an FIR moving average, an exponential smoother, a filter with and a biquad.
7. Digital filters
CoreComputationalComplete design_lowpass(num_taps, fc, fs) so that it returns a linear-phase low-pass FIR filter designed by the window method: the ideal (sinc) response, truncated to num_taps taps centred on the middle tap, multiplied by a Hamming window (np.hamming), and scaled to have gain exactly 1 at DC. The tests measure the passband ripple and require at least 50 dB of stopband attenuation.
8. Digital filters
StretchComputationalDesign a notch filter to remove mains hum: write design_notch(f0, fs, r) returning (b, a) for , with : zeros on the unit circle at angle and poles just inside them at radius . Choose so the gain at DC is exactly 1. The tests check zero gain at , unit gain at DC, stability, and that the notch is narrow.
Further reading and resources
- Introduction to Digital Filters with Audio Applications · Julius O. Smith IIIA free online book on difference equations, the z-transform, and filter structures, with many worked examples.
- scipy.signal · SciPyThe Python library engineers use for filter design (firwin, remez, butter, cheby1, ellip) and filtering (lfilter, sosfilt, filtfilt).
- Audio EQ Cookbook · Robert Bristow-Johnson (W3C Working Group Note)Widely used closed-form formulas for the biquad coefficients of equaliser filters, derived with the bilinear transform.
- CMSIS-DSP · ArmAn open-source library of filters (including fixed-point biquad cascades) and FFTs for Arm microcontrollers.
- Chebyshev approximation for nonrecursive digital filters with linear phase · Thomas W. Parks and James H. McClellan · 1972The paper behind the Parks–McClellan (Remez) algorithm for optimal equiripple FIR filters.