Signal Processing Foundations — Week 7

Digital Filters
FIR & IIR

Filters are the scissors of signal processing — they cut unwanted frequencies with surgical precision. Learn to design FIR and IIR filters, read Bode plots, and choose the right tool for any application.

FIR Windowed-Sinc IIR Butterworth Pole-Zero Stability Frequency Response scipy.signal

Why Digital Filters?

Every real-world signal arrives contaminated — power-line hum, sensor noise, out-of-band interference. This section defines the general difference equation that unifies FIR and IIR filters, maps the four fundamental filter types (LP/HP/BP/BS), and explains why frequency-selective processing is indispensable before any signal reaches a model or algorithm.

After this section you will be able to
  • Write the general difference equation and identify whether a filter is FIR or IIR from its coefficients.
  • Compute the output $y[2]$ of a 3-tap FIR moving-average filter by hand given an input sequence.
  • Classify a filter as LP, HP, BP, or BS given a description of which frequencies it passes or blocks.

Imagine trying to hear a whispered conversation across a noisy café. Your brain automatically filters out background chatter and focuses on the voice in front of you. Now imagine doing the same thing for an ECG signal buried in 60 Hz power-line hum — that's exactly what a digital filter does, one sample at a time.

🎯
Why this matters: Every AI pipeline that processes audio, physiological signals, radar, or vibration data depends on upstream digital filters. Without them, noise dominates features, models learn artifacts, and system performance collapses silently. Filters are the first gate between raw sensor data and anything useful.
🔗
Think of it this way

A digital filter is like a coffee filter: you pour in a mixture (signal + noise), and it lets exactly the good stuff pass through while blocking what you don't want. The filter shape (LP/HP/BP/BS) is the mesh size — you choose how fine or coarse to make it. Just as a finer mesh catches smaller grounds, a steeper filter cuts closer to the signal of interest.

Low-Pass
Passes DC and slow variations; blocks high-frequency noise
High-Pass
Removes DC baseline wander; preserves fast transients
Band-Pass
Isolates a specific frequency band (e.g., EEG alpha waves)
Band-Stop
Rejects a narrow band (notch filter for 60 Hz hum)
20N
dB / decade
Roll-off rate of an N-th order Butterworth filter
M+1
multiplies / sample
Cost of an M-th order FIR filter (no feedback)
2N
multiplies / sample
Cost of an N-th order IIR filter (much fewer for same sharpness)
−3 dB
cutoff definition
Frequency where magnitude drops to $1/\sqrt{2}$ of passband
Problem

The General Difference Equation

A digital filter is a discrete-time system that shapes the frequency content of a signal. Given input $x[n]$, it produces output $y[n]$ by computing a weighted sum of past inputs and — optionally — past outputs.

General Difference Equation

Every digital filter — no matter how complex — fits one equation:

$$y[n] = \sum_{k=0}^{M} b_k\,x[n-k] \;-\; \sum_{k=1}^{N} a_k\,y[n-k]$$

$y[n] = \sum b_k x[n-k] - \sum a_k y[n-k]$
$y[n]$
Output
Current filtered sample
$b_k$
Feed-forward
Input weights (always present)
$a_k$
Feedback
Output weights (IIR only)
$M$
FIR order
Number of past inputs used
$N$
IIR order
Number of past outputs fed back
📝 Worked Example — 3-tap Moving Average & First-Order IIR

Big picture first. The difference equation is a recipe: to compute today's output, average recent inputs ($b_k$ terms) and optionally mix in recent outputs ($a_k$ feedback). A 3-sample average is already a working lowpass filter — and it fits this equation exactly.

Problem: FIR: $b_0=b_1=b_2=\tfrac{1}{3}$, all $a_k=0$, input $x=[1,2,4,1,0,\ldots]$. Compute $y[0]$, $y[1]$, $y[2]$. Then contrast with IIR: $b_0=0.1$, $a_1=-0.9$, input $x=[1,0,0,\ldots]$ (impulse).

1
FIR — set up.
Since all $a_k=0$, no feedback. The equation reduces to:
$y[n] = \tfrac{1}{3}x[n] + \tfrac{1}{3}x[n-1] + \tfrac{1}{3}x[n-2]$
Assume $x[n]=0$ for $n < 0$.
2
FIR — compute outputs.
$y[0] = \tfrac{1}{3}(1+0+0) = \tfrac{1}{3}$
$y[1] = \tfrac{1}{3}(2+1+0) = 1$
$y[2] = \tfrac{1}{3}(4+2+1) = \tfrac{7}{3} \approx 2.33$
y = [0.33, 1.00, 2.33, …] — the spike at x[2]=4 is smoothed down
3
IIR — unit impulse response ($x=[1,0,0,\ldots]$).
$y[n] = 0.1\,x[n] + 0.9\,y[n-1]$, starting from $y[-1]=0$:
$n=0$: $y[0]=0.1{\cdot}1+0.9{\cdot}0=0.1$
$n=1$: $y[1]=0+0.9{\cdot}0.1=0.09$
$n=2$: $y[2]=0.9{\cdot}0.09=0.081$ → decays as $0.1{\cdot}(0.9)^n$
FIR: impulse response dies after M+1=3 samples (finite)
IIR: impulse response decays as (0.9)ⁿ — infinite, never exactly zero
✔ Quick Check

For the same FIR filter ($b_0=b_1=b_2=\tfrac{1}{3}$), what is $y[3]$ if $x=[1,2,4,1,0,\ldots]$?

y[3] = (1/3)(x[3]+x[2]+x[1]) = (1/3)(1+4+2) = 7/3 ≈ 2.33
Filter Structure Anatomy FIR — Tapped Delay Line (no feedback) x[n] z⁻¹ z⁻¹ z⁻¹ b₀ b₁ b₂ + y[n] IIR — Feedback Loop (recursive) x[n] + ×b₀ y[n] z⁻¹ ×(−a₁) Feedback path (makes response infinite) Stable if |a₁| < 1 bₖ = feedforward (input) weights aₖ = feedback (output) weights — IIR only FIR: all aₖ = 0 → no feedback → always stable → linear phase IIR: aₖ ≠ 0 → recursive → efficient → nonlinear phase

FIR (top): feedforward only — output depends only on current and past inputs. IIR (bottom): recursive — output feeds back, creating infinite impulse response.

PropertyFIRIIR
Impulse responseFinite (M+1 samples)Infinite (decays forever)
FeedbackNone ($a_k=0$)Yes ($a_k \neq 0$)
PhaseLinear (symmetric $b_k$)Nonlinear (variable delay)
StabilityAlways stableDepends on pole locations
EfficiencyHigh order for sharp cutoffLow order → efficient
Solution
Pause & Predict

Below is a composite signal: a 50 Hz tone you want to keep, plus a 350 Hz tone you want to remove. Before adjusting the lowpass cutoff — what frequency should the cutoff be set to in order to pass only 50 Hz?

Hint: the cutoff should be somewhere between 50 Hz and 350 Hz, closer to the lower tone.

Try It: Signal Filter Demo

A composite signal (50 Hz tone + 350 Hz tone) is buried in noise. Adjust the lowpass cutoff frequency to isolate the low-frequency component. Watch the time domain and spectrum update live.

18% fs
30%
Time Domain
Frequency Spectrum
Raw signal Filtered output Cutoff fc
Implementation
Python · scipy.signal — First filter in 4 lines
from scipy.signal import butter, sosfilt import numpy as np fs = 1000 # sample rate (Hz) sos = butter(4, 200, 'low', fs=fs, output='sos') # Composite signal: 50 Hz (keep) + 450 Hz (reject) + noise t = np.arange(1024) / fs x = np.sin(2*np.pi*50*t) + np.sin(2*np.pi*450*t) + 0.3*np.random.randn(1024) y = sosfilt(sos, x) # 450 Hz attenuated >40 dB # Always use output='sos' — numerically stable for any order
Output
Filter applied: 4th-order Butterworth LP (fc=200 Hz, fs=1000 Hz) Pass-band (0-200 Hz): gain ≈ 0 dB → 50 Hz tone preserved Stop-band (450 Hz): gain ≈ -43 dB → 450 Hz tone attenuated ×141×
Key Takeaway

A digital filter is fully described by one equation: $y[n]=\sum b_k x[n-k]-\sum a_k y[n-k]$ — when all $a_k=0$ you get FIR (stable, linear phase); when $a_k\neq0$ you get IIR (efficient, nonlinear phase).

🎛️
Real-World Application

Active Noise Cancellation in Wireless Earbuds

Active Noise Cancellation (ANC) earbuds use a real-time digital filter to cancel ambient noise. A microphone captures the environment; a DSP chip runs a filter that produces an anti-noise signal $180°$ out of phase with the interference — cancelling it at the ear. The system must filter and respond within $\approx 10\ \text{ms}$ to stay phase-aligned; beyond that, the anti-noise arrives late and makes things worse. This tight latency constraint makes efficient IIR design (low order, low computational cost) essential for battery-powered devices.

CheckpointPart 1 — Why Digital Filters?

Q1 A filter has $b_0=0.5$, $b_1=0.5$, and all $a_k=0$. Is it FIR or IIR? What is its impulse response?

FIR — because all feedback coefficients $a_k=0$. The impulse response is $h=[0.5,\ 0.5]$ — exactly two non-zero samples (finite length). It is a 2-tap moving average (lowpass filter).

Q2 You need a filter that removes a constant 0 Hz DC offset from a vibration signal while keeping all frequencies above 1 Hz. Which filter type (LP/HP/BP/BS) should you use?

High-Pass (HP) — it blocks 0 Hz (DC) and passes all higher frequencies. Set the cutoff frequency near 0.5–1 Hz so the vibration content above 1 Hz passes through unaffected.

Q3 A 3rd-order FIR filter processes 1000 samples per second. How many multiply-accumulate operations per second does it require?

$M+1 = 4$ multiplications per output sample × 1000 samples/sec = 4000 multiply-accumulate operations per second. An IIR filter achieving equivalent sharpness might need only order N=2 → 2×2=4 MACs/sample, showing similar cost here but much lower order for steep rolloffs.

FIR Filters — Windowed-Sinc Design

FIR (Finite Impulse Response) filters have no feedback. Their impulse response has exactly $M+1$ non-zero samples. Symmetric coefficients guarantee linear phase — a critical property for audio, biomedical, and communication signal processing. This section covers the windowed-sinc design method and explains how the window function governs the trade-off between transition-band width and stopband attenuation.

After this section you will be able to
  • Compute any FIR coefficient $h[n]$ using $h[n] = 2f_c \cdot \text{sinc}(2f_c(n-M/2)) \cdot w[n]$ given $M$, $f_c$, and a named window.
  • Explain why symmetric FIR coefficients guarantee linear phase and a constant group delay of $M/2$ samples.
  • Select the appropriate window (Rectangular/Hann/Hamming/Blackman) given a stopband attenuation requirement.

Have you ever wondered why an EEG recording used to diagnose epilepsy can't just use any filter? The answer is phase. If different brain-wave frequencies arrive at the classifier with different time delays, the relative timing of ERP peaks shifts — and the diagnosis changes. FIR filters guarantee that every frequency is delayed by the exact same number of samples: no distortion, no diagnostic error.

🎯
Why this matters: FIR filters are the standard in medical devices, audio production, and seismology because their linear phase property preserves event timing. Understanding windowed-sinc design lets you spec the filter's exact cutoff, attenuation, and delay before writing a single line of code.
🔗
Think of it this way

The windowed-sinc method is like cutting a very long roll of fabric to a fixed length — the fabric is the infinite sinc function (ideal filter), the scissors are the window, and you choose how cleanly to cut based on how much fraying (sidelobe ripple) you can tolerate. A sharper cut (Rectangular window) frays more; a softer trim (Blackman window) frays less but uses more fabric (wider transition band).

Ideal Sinc
Infinite length — not realisable in practice
Window $w[n]$
Truncates sinc gracefully to M+1 samples
$h[n]$ FIR
Symmetric finite impulse response → linear phase
$|H(f)|$
Frequency response: passband, transition, stopband
Problem

The Windowed-Sinc Formula

The ideal lowpass filter has an infinite sinc impulse response. Multiplying by a window $w[n]$ truncates it to $M+1$ coefficients while controlling sidelobe behaviour.

Windowed-Sinc Coefficients

$$h[n] = 2f_c \cdot \operatorname{sinc}\!\bigl(2f_c(n-M/2)\bigr) \cdot w[n], \quad n=0,\ldots,M$$

$h[n] = 2f_c \cdot \text{sinc}(2f_c(n-M/2)) \cdot w[n]$
$h[n]$
Coefficient
n-th filter tap value
$f_c$
Cutoff
Normalized (0 to 0.5); e.g., 0.25 = fs/4
$M$
Order
Filter order; choose odd for integer group delay
$w[n]$
Window
Hamming, Hann, Blackman, etc.
📝 Worked Example — Computing h[4], h[5], h[6] for M=8, fc=0.25 (Hamming)

Where does this formula come from? The ideal LP filter passes all frequencies below $f_c$ with gain 1. Its impulse response is the inverse DTFT of a rectangular spectrum — a sinc function. Since sinc extends to infinity, we multiply by a window $w[n]$ to truncate it gracefully. The window shape determines the sidelobe level.

Problem: $M=8$, $f_c=0.25$ (quarter the sample rate). Use Hamming window: $w[n]=0.54-0.46\cos(2\pi n/M)$.

1
Compute center tap $h[4]$ (offset=0).
The sinc at argument 0: $\lim_{x\to0}\frac{\sin(\pi x)}{\pi x}=1$. Hamming center: $w[4]=0.54-0.46\cos(\pi)=0.54+0.46=1.0$
h[4] = 2 × 0.25 × 1 × 1.0 = 0.500
2
Compute $h[5]$ (offset=1).
Sinc: $\sin(2\pi{\cdot}0.25{\cdot}1)/(\pi{\cdot}1)=\sin(\pi/2)/\pi=1/\pi\approx0.3183$
Window: $w[5]=0.54-0.46\cos(2\pi{\cdot}5/8)=0.54-0.46{\cdot}(-0.707)\approx0.865$
h[5] = 0.5 × 0.3183 × 0.865 ≈ 0.2754 × ... = 2 × 0.25 × 0.3183 × 0.865 ≈ 0.1377
3
Compute $h[6]$ — a structural zero.
Offset=2. Sinc argument: $2f_c\times2=0.5{\cdot}2=1$ (integer). $\sin(\pi{\cdot}1)/(\pi{\cdot}1)=0$.
h[6] = 0 — sinc is zero at all non-zero integers; guaranteed zero regardless of window
4
Verify symmetry: $h[3]$ should equal $h[5]$.
Offset$=-1$: sinc$(-1)=\sin(-\pi)/(-\pi)=0$... wait, $2f_c{\cdot}(-1)=-0.5$. Sinc: $\sin(-\pi/2{\cdot}2)/(\pi{\cdot}(-1))=(-1)/(-\pi)=1/\pi$. Window: $w[3]=w[5]$ by symmetry of cosine.
h[3] = h[5] ✓ — symmetric coefficients confirm linear phase; group delay = M/2 = 4 samples
✔ Quick Check

For the same filter ($M=8$, $f_c=0.25$, Hamming), what is $h[8]$ (the last tap)?

h[8] = h[M-0] mirrors h[0]: offset = 8-4 = 4; sinc(4×0.5) = sinc(2) = sin(2π)/(2π) = 0. So h[8] = 0. (Tip: also equals h[0] by symmetry.)
💡
Window Trade-offs

Rectangular: sharpest transition but −21 dB sidelobes (Gibbs ringing). Hamming: −53 dB — best for most audio. Blackman: −74 dB sidelobes but widest transition band. Sharper cutoff always costs higher order (more taps).

FIR Impulse Response — Windowed Sinc (M=16, fc=0.2) n h[n] M/2=8 h[n] = h[M−n] (symmetric → linear phase) peak h[M/2] negative sidelobe sinc zero coefficient h[n]

Symmetric windowed-sinc coefficients about $n=M/2$. Every frequency is delayed identically by $M/2$ samples — this is linear phase.

Window Function Comparison

WindowSidelobeTrans. Width
Rectangular−21 dBNarrowest (sharpest)
Hann−44 dBWider
Hamming−53 dBModerate — best all-round
Blackman−74 dBWidest (gentlest)
Solution
Pause & Predict

If you switch from the Rectangular window to the Blackman window (with the same filter order M), the stopband attenuation will increase dramatically — but what do you predict will happen to the transition band width?

Hint: there is always a trade-off between how sharp the cutoff is and how low the sidelobes are.

Try It: Window Function Explorer

Window choice trades transition-band width against sidelobe attenuation. Select a window to see its effect on the FIR frequency response (M = 48 taps, fc = 20% fs).

Sidelobe: −21 dB Trans. width ≈ 4/M Stopband ≈ 21 dB
Implementation
Python · scipy.signal — FIR lowpass via firwin()
import numpy as np from scipy.signal import firwin, freqz import matplotlib.pyplot as plt fs = 1000 # sample rate (Hz) fc = 150 # lowpass cutoff (Hz) M = 64 # filter order (taps = M+1 = 65) # Design windowed-sinc FIR (firwin normalizes fc by fs/2 internally) h = firwin(M + 1, fc, window='hamming', fs=fs) # Compute frequency response w, H = freqz(h, worN=2048, fs=fs) # Plot magnitude response in dB plt.plot(w, 20*np.log10(np.abs(H)+1e-12)) plt.axvline(fc, color='r', linestyle='--', label=f'fc={fc} Hz') plt.axhline(-3, color='gray', linestyle=':', label='-3 dB') plt.ylim(-80, 5); plt.legend(); plt.grid(True)
Output
FIR LP filter designed: M=64, fc=150 Hz, window=Hamming Group delay: 32.0 samples (constant at all frequencies) Passband (0-100 Hz): ≈ 0.0 dB (gain = 1.00) At cutoff (150 Hz): ≈ -3.01 dB (gain = 0.707) Stopband (250+ Hz): ≤ -52 dB (Hamming sidelobe level)
Key Takeaway

FIR filters are designed by multiplying the infinite sinc function by a window: the window choice trades sidelobe attenuation (stopband suppression) against transition-band width — Hamming gives −53 dB attenuation and is the best all-round choice for most applications.

🎵
Real-World Application

Linear-Phase FIR Crossovers in Studio Monitors

High-end studio monitor speakers use FIR-based linear-phase digital crossover filters to split the audio signal into bass, mid, and treble bands before routing each band to the appropriate driver (woofer, midrange, tweeter). The linear phase property guarantees perfect time-alignment: summing the three bands reconstructs the original signal without phase-induced comb filtering. Analog IIR crossovers introduce frequency-dependent delays at the crossover region — a colouration that trained ears can detect and that shifts the perceived stereo image. Recording engineers routinely verify linear phase with swept-sine group delay measurements before signing off on a monitor calibration.

CheckpointPart 2 — FIR Filters

Q1 An FIR filter has order $M=10$. What is the group delay in samples, and why is it constant?

Group delay = M/2 = 5 samples. It is constant because symmetric coefficients ($h[n]=h[M-n]$) guarantee that the phase response is exactly linear: $\angle H(\omega) = -\omega M/2$. The derivative of a linear function is a constant, so group delay $=-d\angle H/d\omega = M/2$ at all frequencies.

Q2 You need a filter to remove 50 Hz ECG muscle artifacts, preserving 0.5–45 Hz with ≥ 60 dB stopband attenuation. Which window should you use?

Blackman window — it provides −74 dB sidelobe attenuation, exceeding the 60 dB requirement. The Hamming window gives only −53 dB, which falls short. The trade-off is a wider transition band, which is acceptable here since the gap between 45 Hz (passband edge) and 50 Hz (stopband start) is narrow — a higher filter order M would compensate.

Q3 For $M=8$, $f_c=0.25$ (normalized), what is the center tap value $h[4]$ (Hamming window)?

$h[4] = 2 \times 0.25 \times \text{sinc}(0) \times w[4] = 0.5 \times 1 \times 1.0 = \mathbf{0.5}$. The center tap always equals $2f_c$ because sinc(0)=1 and the Hamming window evaluates to 1 at its center ($n=M/2$).

IIR Filters & Frequency Response

IIR filters use feedback to achieve steep roll-off with far fewer coefficients than FIR. This section covers the Butterworth maximally-flat design, pole-zero placement in the $z$-plane, why second-order sections (SOS) are mandatory for numerical safety, and how to read the three-panel Bode plot (magnitude, phase, group delay) that characterizes any LTI filter.

After this section you will be able to
  • Compute the Butterworth magnitude $|H(f)|$ in dB at any frequency using $|H|^2=1/(1+(\Omega/\Omega_c)^{2N})$ and the prewarping formula.
  • Determine whether an IIR filter is stable by checking whether all poles lie strictly inside the unit circle ($|p_k|<1$).
  • Read a Bode plot and identify passband ripple, stopband attenuation, cutoff frequency, and whether phase is linear or nonlinear.

Imagine you need to separate a 100 Hz heartbeat from 60 Hz power-line interference using a chip running on a hearing-aid battery. Every multiply-accumulate operation costs energy. A 4th-order IIR Butterworth achieving −40 dB at twice the cutoff needs only 8 operations per sample. An FIR doing the same job needs 80+ taps — 10 times more. That energy difference can mean hours of battery life.

🎯
Why this matters: IIR filters dominate real-time embedded systems — hearing aids, cellular modems, sonar processors — because efficiency is non-negotiable. Understanding Butterworth design, pole-zero placement, and the SOS stability convention is essential for any DSP hardware or FPGA deployment.
🔗
Think of it this way

Poles and zeros in the $z$-plane are like magnets arranged around a circular track (the unit circle). A pole close to the track creates a strong resonance — it amplifies nearby frequencies. A zero on the track kills a specific frequency completely. As long as all poles stay inside the circle, the filter is stable; push a pole outside and the output grows without bound.

N=1 (6 dB/oct)
Gentle slope — suitable for simple pre-filtering
N=4 (24 dB/oct)
Standard Butterworth — flat passband, good transition
N=8 (48 dB/oct)
Near brick-wall — used in anti-aliasing and channel filters
Z-Plane Poles
All poles inside unit circle → stable filter
20N
dB/decade
Butterworth N-th order roll-off rate
−3.01
dB at fc
Magnitude exactly $1/\sqrt{2}$ at the cutoff for all Butterworth orders
<1
|pole| condition
All poles must be strictly inside the unit circle for stability
Problem

Butterworth Lowpass Design

The Butterworth filter has a maximally flat magnitude response — no ripple in the passband or stopband. It is the standard starting point for IIR design.

Butterworth Magnitude-Squared Response

The magnitude-squared response of an N-th order Butterworth filter is:

$$|H(j\Omega)|^2 = \frac{1}{1 + \left(\dfrac{\Omega}{\Omega_c}\right)^{2N}}$$

$|H|^2 = 1\,/\,(1 + (\Omega/\Omega_c)^{2N})$
$N$
Order
Higher N → steeper roll-off (20N dB/decade)
$\Omega_c$
Cutoff
Analog frequency at −3 dB point (prewarped)
$\Omega$
Frequency
Input analog frequency to evaluate

Digital design uses the bilinear transform with prewarping: $\Omega_c = \tan(\pi f_c/f_s)$ to map analog to digital exactly at $f_c$.

📝 Worked Example — Butterworth Magnitude at 150 Hz and 300 Hz

Why prewarp? The bilinear transform compresses the frequency axis nonlinearly. Prewarping guarantees the digital filter's −3 dB point lands exactly at the desired $f_c$.

Problem: 4th-order Butterworth LP, $f_c=150$ Hz, $f_s=1000$ Hz. Evaluate $|H(f)|$ in dB at (a) $f=150$ Hz and (b) $f=300$ Hz.

1
Prewarp both frequencies.
$\Omega_c = \tan(\pi{\cdot}150/1000) = \tan(0.15\pi) \approx 0.5095$
$\Omega_{300} = \tan(\pi{\cdot}300/1000) = \tan(0.3\pi) \approx 1.3764$
2
Evaluate at $f_c=150$ Hz.
Ratio $\Omega_{150}/\Omega_c = 1$ by definition → $|H|^2=1/(1+1^8)=0.5$
|H| = 1/√2 → 20 log₁₀(0.707) = −3.01 dB ✓
3
Evaluate at $f=300$ Hz (one octave above cutoff).
Ratio: $1.3764/0.5095\approx2.70$. Raise to $2N=8$: $2.70^8\approx1108$.
$|H|^2=1/(1+1108)\approx9\times10^{-4}$ → $|H|\approx0.030$
20 log₁₀(0.030) ≈ −30.5 dB — at one octave above cutoff, <0.1% of power passes
4
Derive the roll-off rule.
When frequency doubles (1 octave), $(\Omega/\Omega_c)^{2N}$ grows by $2^{2N}=2^8=256$.
Attenuation: $10\log_{10}(256)\approx24$ dB per octave. In general: $20N$ dB/decade.
N=4 Butterworth: roll-off ≈ 80 dB/decade ≈ 24 dB/octave
✔ Quick Check

For the same N=4 Butterworth LP ($f_c=150$ Hz, $f_s=1000$ Hz), at $f=150$ Hz the gain is −3 dB. What is the gain in dB at $f=0$ Hz (DC)?

At f=0 Hz, Ω=0: |H|² = 1/(1+0) = 1 → |H| = 1 → 0 dB. DC passes through with full gain — this is the defining property of a lowpass filter.
⚠️
Common Mistake — Direct Form (b, a) Instability

Never use scipy.signal.lfilter(b, a, x) for IIR filters of order > 5. Direct-form coefficients become numerically unstable due to floating-point cancellation. Always specify output='sos' and use sosfilt(). Second-order sections (SOS) cascade biquad sections — the industry-standard approach.

Z-Plane Pole-Zero Diagram — 4th-order Butterworth LP Re Im 1 -1 j -j × × × × p₁ p₂ p₁* p₂* 4 zeros at z=−1 r=1 (unit circle) STABLE |p| < 1 × = Poles (inside unit circle → stable) ○ = Zeros (at z = −1)

All four poles inside the unit circle → the filter is stable. Zeros at $z=-1$ create infinite attenuation at $f=f_s/2$ (Nyquist). The further a pole is from the unit circle, the faster the impulse response decays.

Frequency Response $H(e^{j\omega})$

$$H(e^{j\omega}) = \sum_{n} h[n]\,e^{-j\omega n} = |H(e^{j\omega})|\,e^{\,j\angle H(e^{j\omega})}$$

Evaluate the $z$-transform on the unit circle ($z=e^{j\omega}$). Three key derived quantities:

  • Magnitude $|H(e^{j\omega})|$ — amplification or attenuation at each frequency
  • Phase $\angle H(e^{j\omega})$ — phase shift at each frequency
  • Group delay $\tau(\omega)=-d\angle H/d\omega$ — time delay in samples at each frequency
📝 Worked Example — Group Delay of a 3-tap Moving Average

Problem: 3-tap MA: $h=[\tfrac{1}{3},\tfrac{1}{3},\tfrac{1}{3}]$. Derive $H(e^{j\omega})$ and compute group delay.

1
Write the DTFT sum.
$H(e^{j\omega})=\tfrac{1}{3}(1+e^{-j\omega}+e^{-j2\omega})=\tfrac{1}{3}e^{-j\omega}(e^{j\omega}+1+e^{-j\omega})$
H(e^jω) = (1/3)·e^{−jω}·(1 + 2cosω)
2
Extract phase.
Phase of $(1+2\cos\omega)$ is 0 (real positive for small $\omega$), so the total phase comes only from $e^{-j\omega}$: $\angle H=-\omega$.
Group delay = −d(−ω)/dω = 1 sample = M/2 = 1 — constant ✓
✔ Quick Check

At $\omega=2\pi/3$ ($f=f_s/3$), what is $|H(e^{j\omega})|$ for the 3-tap MA?

|H| = (1/3)|1 + 2cos(2π/3)| = (1/3)|1 + 2(−0.5)| = (1/3)|0| = 0. Perfect null at f=fs/3 — the three samples sum to zero at that frequency.
Solution
Pause & Predict

Below you can sweep the Butterworth filter order N from 1 to 10. Before you try it — at N=1 the roll-off is 20 dB/decade. What roll-off (in dB/decade) do you predict for N=4?

Hint: the roll-off rate formula is 20N dB/decade — you can compute this directly.

Try It: Butterworth Order Sweep

Each additional order adds ~20 dB/decade to the roll-off rate. Sweep N = 1 to 10 and watch the filter sharpen toward a brick-wall response. The live-calc panel tracks the roll-off and attenuation values.

4
Live Calculation — Butterworth Roll-off
Roll-off = 20 × N dB/decade = 20 × 4 = 80 dB/decade
At f = 2×fc:Atten ≈ 20 log₁₀(2^N) = 20×N×log₁₀(2)−24 dB
At f = 4×fc:Atten ≈ 20 log₁₀(4^N) = 40×N×log₁₀(2)−48 dB
Implementation
Python · scipy.signal — Butterworth, Chebyshev, and Elliptic comparison
from scipy.signal import butter, cheby1, ellip, sosfreqz import numpy as np; import matplotlib.pyplot as plt fs = 1000; fc = 150; N = 4 # Butterworth — maximally flat passband (no ripple) sos_b = butter(N, fc, btype='low', fs=fs, output='sos') # Chebyshev I — passband ripple ≤1 dB, sharper roll-off than Butterworth sos_c = cheby1(N, rp=1, Wn=fc, btype='low', fs=fs, output='sos') # Elliptic — ripple in both bands, sharpest roll-off for given order sos_e = ellip(N, rp=1, rs=60, Wn=fc, btype='low', fs=fs, output='sos') # All use output='sos' — cascade of biquads, numerically stable for sos, label in [(sos_b,'Butterworth'),(sos_c,'Chebyshev'),(sos_e,'Elliptic')]: w, H = sosfreqz(sos, worN=2048, fs=fs) plt.plot(w, 20*np.log10(np.abs(H)+1e-12), label=label) plt.ylim(-80, 5); plt.legend(); plt.grid(True)
Output
N=4 lowpass (fc=150 Hz, fs=1000 Hz) — all output='sos' Butterworth: 0 dB passband ripple, -3 dB at fc, 80 dB/decade Chebyshev: ≤1 dB passband ripple, sharper at fc, slightly more distortion Elliptic: ≤1 dB passband ripple, ≥60 dB stopband, sharpest transition
Key Takeaway

IIR Butterworth filters deliver $20N$ dB/decade roll-off with a maximally flat passband; always use output='sos' and sosfilt() to avoid numerical instability — direct $(b,a)$ form breaks for N>5 due to floating-point pole sensitivity near the unit circle.

❤️
Real-World Application

ECG Baseline Wander Removal in Wearable Monitors

Wearable ECG patches (Holter monitors, Apple Watch ECG) suffer from baseline wander — a slow drift below 0.5 Hz caused by patient movement and electrode impedance changes. A high-pass Butterworth IIR filter with $f_c=0.5$ Hz removes this drift while preserving the P-wave, QRS complex, and T-wave (0.5–40 Hz). The group delay of the IIR filter must be accounted for when measuring PR and QT intervals for arrhythmia detection — clinical software applies phase compensation to align the filtered signal with the original recording timeline.

CheckpointPart 3 — IIR & Frequency Response

Q1 A 2nd-order IIR filter has poles at $z=0.85\pm0.3j$. Is this filter stable?

Stable. $|p|=\sqrt{0.85^2+0.3^2}=\sqrt{0.7225+0.09}=\sqrt{0.8125}\approx0.901 < 1$. Both poles lie inside the unit circle → the impulse response decays → stable. If $|p|\geq1$, the filter would be unstable.

Q2 Why should you always use output='sos' instead of output='ba' when designing IIR filters in SciPy?

Direct $(b,a)$ polynomial coefficients become numerically unstable for orders above ~5 because tiny floating-point errors in the coefficients shift poles outside the unit circle. SOS (second-order sections) factorizes the transfer function into cascaded biquad sections, each with only 5–6 coefficients, keeping all numerical computations well-conditioned regardless of filter order.

Q3 A 6th-order Butterworth LP filter has $f_c=200$ Hz. Estimate the attenuation in dB at $f=600$ Hz (one decade above $f_c$).

Roll-off = 20N dB/decade = 20×6 = 120 dB/decade. Since 600 Hz is 0.477 decades above 200 Hz (log₁₀(600/200) = log₁₀(3) ≈ 0.477), attenuation ≈ 120 × 0.477 ≈ 57 dB. (Exact value: 20·log₁₀(1+(600/200)^12) ≈ 57.3 dB.)

Bode Plot Explorer

Explore how filter type (LP/HP/BP/BS), filter family (Butterworth vs FIR), and order $N$ interact to shape the frequency response. The Bode plot shows magnitude (dB) and phase simultaneously so you can see both the amplitude roll-off and the phase distortion that comes with higher-order IIR designs.

Filter Family
Filter Type
4
25% fs
Magnitude Response (dB)
Phase Response (°)
IIR Butterworth FIR Windowed-Sinc Cutoff fc
Roll-off
80 dB/dec
At 2×fc
−24 dB
Phase Type
Nonlinear
Group Delay
Variable

Week 7 — Key Ideas to Retain

If you forget everything else, remember these four ideas. Each one is directly testable on the midterm.

⚖️

FIR vs IIR — the core trade-off

FIR: no feedback, always stable, linear phase, high order. IIR: feedback, efficient (low order), nonlinear phase, must check stability. Choose FIR when phase matters (EEG, audio); choose IIR when efficiency matters (real-time embedded).

📐

Windowed-Sinc Design

$h[n]=2f_c\cdot\text{sinc}(2f_c(n-M/2))\cdot w[n]$. Hamming window gives −53 dB sidelobe attenuation and is the best all-round choice. Center tap always equals $2f_c$. Symmetric coefficients → linear phase → group delay = $M/2$ samples.

🎯

Butterworth Roll-off

$|H|^2=1/(1+(\Omega/\Omega_c)^{2N})$. Roll-off = 20N dB/decade. At $f_c$: exactly −3 dB. To prewarp: $\Omega_c=\tan(\pi f_c/f_s)$. Always use output='sos' + sosfilt() for numerical safety.

🔄

Stability & SOS

An IIR filter is stable iff all poles satisfy $|p_k|<1$ (strictly inside the unit circle). Direct $(b,a)$ form breaks for N>5. SOS (second-order sections) decomposes the filter into biquad stages — numerically stable at any order.

Coming up — Week 9: Time-Frequency Analysis (STFT)

The Fourier Transform gives global frequency content. But when does a 440 Hz note appear in a recording? The Short-Time Fourier Transform (STFT) answers by applying a sliding window: you trade time resolution for frequency resolution. Week 9 explores the STFT, the spectrogram, and the Heisenberg uncertainty principle that governs that trade-off. (Week 8 = Midterm Exam.)

Go Deeper

Curated resources for students who want to build deeper intuition. Each resource is worth the time — no filler.

Practice Problems

8 questions (3 Theory · 3 Code · 2 Synthesis) covering all three topics. Numerical values on exams may differ but the method will always mirror these problems exactly.

1 Theory — Why Filters Easy

FIR or IIR? Identify from Coefficients

A filter is defined by: $b_0=0.25,\, b_1=0.5,\, b_2=0.25$, and all $a_k=0$. (a) Is this FIR or IIR? (b) Write out the difference equation. (c) Compute $y[0]$ and $y[1]$ for input $x=[4,2,0,0,\ldots]$ (zero initial conditions). (d) What type of filter (LP/HP/BP/BS) is this likely to be, and why?

Since all $a_k=0$ there is no feedback — this is FIR. The center coefficient is largest, which is typical of a lowpass filter (DC passes, high frequencies are averaged out). Compute by substituting into the difference equation.
2 Code — Why Filters Easy

Design and Apply a Butterworth Lowpass Filter

Using scipy.signal.butter and sosfilt: (a) Design a 4th-order Butterworth LP filter with $f_c=200$ Hz and $f_s=1000$ Hz using output='sos'. (b) Generate a test signal: 50 Hz + 350 Hz sine, 1 second at $f_s=1000$ Hz. (c) Filter the signal and plot both the original and filtered signal overlaid. (d) Verify in the plot that the 350 Hz component is attenuated.

butter(N, Wn, btype, fs, output), sosfilt(sos, x)

Use: sos = butter(4, 200, 'low', fs=1000, output='sos'). To generate the signal: t = np.linspace(0, 1, 1000, endpoint=False), then add two sines. Filter with sosfilt(sos, x).
3 Theory — FIR Design Medium

Windowed-Sinc Coefficient Calculation

Design an FIR lowpass filter with $M=6$ and normalized cutoff $f_c=0.2$. Use a Rectangular window ($w[n]=1$ for all $n$). (a) Write the general formula for $h[n]$. (b) Compute $h[3]$ (center tap). (c) Compute $h[4]$. (d) Verify that $h[3]=h[M-3]$ (symmetry check). (e) What is the group delay in samples?

Recall: $\text{sinc}(x)=\sin(\pi x)/(\pi x)$ and $\text{sinc}(0)=1$.

Center tap at $n=M/2=3$: $h[3]=2f_c \cdot 1 \cdot 1 = 0.4$. For $h[4]$: offset $= 4-3=1$; sinc$(2f_c \cdot 1) = $ sinc$(0.4) = \sin(0.4\pi)/(0.4\pi)$. Group delay $= M/2 = 3$ samples.
4 Code — FIR Design Medium

FIR Filter Design with firwin() + Frequency Response

Using scipy.signal.firwin and freqz: (a) Design three FIR LP filters ($f_c=150$ Hz, $f_s=1000$ Hz, $M=64$) using Rectangular, Hamming, and Blackman windows. (b) Compute and plot all three magnitude responses in dB on the same axes (−80 to 5 dB range). (c) Add a vertical dashed line at $f_c$. (d) Annotate the sidelobe level for each curve. Which window gives the best stopband attenuation?

Use firwin(65, 150, window='hamming', fs=1000). For frequency response: w, H = freqz(h, worN=2048, fs=1000). Convert to dB: 20*np.log10(np.abs(H)+1e-12). Blackman gives ≈ −74 dB sidelobe attenuation.
5 Theory — IIR & Frequency Response Medium

Butterworth Magnitude Calculation

A 6th-order Butterworth LP filter has $f_c=100$ Hz, $f_s=1000$ Hz. (a) Compute the prewarped cutoff $\Omega_c=\tan(\pi f_c/f_s)$. (b) Evaluate $|H(f)|^2$ at $f=200$ Hz using the prewarped ratio $\Omega_{200}/\Omega_c$. (c) Convert to dB. (d) What is the theoretical roll-off rate in dB/decade? (e) Is this filter stable? What condition must all poles satisfy?

$\Omega_c = \tan(0.1\pi) \approx 0.3249$. $\Omega_{200} = \tan(0.2\pi) \approx 0.7265$. Ratio $\approx 2.237$. Raise to $2N=12$: $2.237^{12}\approx1380$. $|H|^2=1/1381$. Roll-off = 20×6 = 120 dB/decade. Stability: all poles must satisfy $|p_k|<1$.
6 Code — IIR & Response Medium

Compare Butterworth, Chebyshev, and Elliptic Filters

Using scipy.signal: (a) Design three N=4 LP filters ($f_c=150$ Hz, $f_s=1000$ Hz): Butterworth, Chebyshev I (1 dB passband ripple), and Elliptic (1 dB/60 dB). All using output='sos'. (b) Plot all three magnitude responses in dB on the same axes. (c) Add markers at $f_c$ (−3 dB) and $2f_c$ (expected attenuation). (d) Which filter has the sharpest roll-off at $f=2f_c$?

Use butter(4, 150, 'low', fs=1000, output='sos'), cheby1(4, 1, 150, 'low', fs=1000, output='sos'), ellip(4, 1, 60, 150, 'low', fs=1000, output='sos'). Elliptic will have the sharpest transition at the cost of ripple in both passbands.
7 Synthesis Hard

ECG Bandpass Filter Design

A wearable ECG patch samples at $f_s=500$ Hz. The QRS complex occupies 5–40 Hz; baseline wander is below 0.5 Hz; muscle noise is above 100 Hz. (a) Specify the bandpass cutoff frequencies $f_{c1}$ and $f_{c2}$ to isolate the QRS complex. (b) Design a 4th-order Butterworth bandpass filter using butter(N, [fc1,fc2], 'bandpass', fs=500, output='sos'). (c) Plot the magnitude response. (d) What is the filter's roll-off below $f_{c1}$ in dB/decade? Why is linear phase (FIR) important for ECG interval measurements?

Set $f_{c1}=0.5$ Hz and $f_{c2}=45$ Hz to pass 0.5–45 Hz. Note: a bandpass filter of order N has a Butterworth roll-off of 20N dB/decade on each side. Linear phase matters for ECG because the PR interval and QT interval are measured from peak timing — nonlinear phase would shift different frequency components of the peaks by different amounts, distorting measurements.
8 Synthesis Hard

60 Hz Notch Filter Design & Group Delay

Power-line interference at 60 Hz contaminates a physiological recording at $f_s=1000$ Hz. (a) Design a notch (band-stop) filter using iirnotch(60, 30, fs=1000) — the second argument is the quality factor Q. (b) Apply the filter to a composite signal: 10 Hz + 60 Hz + 200 Hz sines. (c) Plot the frequency spectrum before and after filtering. (d) Verify the 60 Hz component is attenuated and the 10 Hz and 200 Hz components are preserved. (e) Explain in one sentence why a high Q value creates a narrower notch.

Use from scipy.signal import iirnotch. The notch width is $f_0/Q$: for Q=30, width = 60/30 = 2 Hz. Higher Q → narrower band rejected → more selectivity. Apply with sosfilt(np.array([b,a]).reshape(1,-1), x) or simply lfilter(b, a, x) since iirnotch is only 2nd order. Plot spectrum with np.fft.rfft.