TExcelTAD
Home › Signals, Systems & Digital Filters for Engineers › FIR Design by the Window Method

FIR Design by the Window Method

The Filter Specifications lesson ended with a mask: keep 00 to 1 kHz1\ \text{kHz} within 1 dB1\ \text{dB}, remove everything above 1.5 kHz1.5\ \text{kHz} by 60 dB60\ \text{dB}, at fs=8 kHzf_s = 8\ \text{kHz}. The simplest way to meet it with a finite impulse response (FIR) filter is the window method: take the impulse response of the ideal "brick-wall" filter, which is infinitely long, cut it to NN taps, and taper the cut with a window so that the truncation does not ruin the stopband. This lesson shows why the window decides the attenuation, why the length decides the transition width, how firwin and kaiserord turn a mask into taps, and how to get high-pass and band-pass filters from the same recipe. The mathematics of FIR filters and of windows is in FIR Filters and Windows.

From the ideal filter to taps

An ideal low-pass filter with cutoff fcf_c passes ∣f∣<fc\lvert f \rvert < f_c with gain 1 and nothing else. Its impulse response (the inverse DTFT of a rectangle) is a sampled sinc, centred at n=M=(N−1)/2n = M = (N - 1)/2 so that the filter is causal:

hd[n]=2fcfs sinc⁡ ⁣(2fcfs (n−M)),h[n]=hd[n] w[n],n=0,…,N−1h_d[n] = \frac{2 f_c}{f_s}\,\operatorname{sinc}\!\left(\frac{2 f_c}{f_s}\,(n - M)\right), \qquad h[n] = h_d[n]\,w[n], \quad n = 0, \ldots, N - 1

with sinc⁡(x)=sin⁡(πx)/(πx)\operatorname{sinc}(x) = \sin(\pi x)/(\pi x). Multiplying by a window w[n]w[n] in time convolves the ideal rectangle with the window's spectrum in frequency. Two things follow:

  • the window's main-lobe width smears the brick-wall edge into a transition band whose width is about C/NC/N times fsf_s, with CC depending on the window;
  • the window's side lobes leak into the stopband and set the minimum attenuation, which depends on the window shape and not on NN.
ideal sinc, truncated 0 15 30 n x Hamming window w[n] 0 15 30 n = taps h[n] = ideal x w 0 15 30 n cutoff 1.25 kHz at fs = 8 kHz, 31 taps, delay 15 samples

Plain truncation is the rectangular ("boxcar") window: the sharpest transition but only about 21 dB21\ \text{dB} of attenuation, and a Gibbs overshoot near the edge that no length removes (Convergence and Gibbs). Smoother windows trade transition width for attenuation:

python · try it yourself
import numpy as np
from scipy import signal

# The same 31-tap low-pass (cutoff 1.25 kHz at fs = 8 kHz) truncated by different windows
fs, fc, N = 8000, 1250, 31
f = np.linspace(0, fs / 2, 8001)
print("window       gain at 1 kHz   -6 dB point   first null   peak sidelobe")
for win in ("boxcar", "hann", "hamming", "blackman", ("kaiser", 6.0)):
    h = signal.firwin(N, fc, window=win, fs=fs)
    _, H = signal.freqz(h, worN=f, fs=fs)
    g = 20 * np.log10(np.maximum(np.abs(H), 1e-12))
    i = np.argmax(f >= fc)
    while g[i + 1] < g[i]:                         # walk down the main lobe to its first null
        i += 1
    name = win if isinstance(win, str) else f"kaiser {win[1]:.0f}"
    f6 = f[np.argmax(g < -6.0206)]
    print(f"{name:10s}   {g[f == 1000][0]:7.3f} dB    {f6:6.0f} Hz    {f[i]:6.0f} Hz    {g[i:].max():6.1f} dB")
window       gain at 1 kHz   -6 dB point   first null   peak sidelobe
boxcar         0.492 dB      1244 Hz      1404 Hz     -21.8 dB
hann          -0.997 dB      1250 Hz      1696 Hz     -43.9 dB
hamming       -0.863 dB      1250 Hz      1722 Hz     -50.6 dB
blackman      -1.492 dB      1250 Hz      2181 Hz     -75.2 dB
kaiser 6      -1.034 dB      1250 Hz      1777 Hz     -61.7 dB

Read the table by columns. All windows place the −6 dB-6\ \text{dB} point at the design cutoff (1250 Hz1250\ \text{Hz}): firwin's cutoff is where the gain is 0.50.5, not the −3 dB-3\ \text{dB} point of analog filters. The first null moves out as the side lobes go down: the Blackman window has the deepest stopband but the widest transition. The Kaiser window has a parameter β\beta that slides continuously along this trade-off, which is why it is the default for designing to a specification.

Window Filter's peak stopband lobe (typical) Transition width, about Use
rectangular −21 dB-21\ \text{dB} 0.9 fs/N0.9\,f_s/N almost never for filters
Hann −44 dB-44\ \text{dB} 3.1 fs/N3.1\,f_s/N modest attenuation
Hamming −53 dB-53\ \text{dB} 3.3 fs/N3.3\,f_s/N classic default
Blackman −74 dB-74\ \text{dB} 5.5 fs/N5.5\,f_s/N high attenuation, longer filter
Kaiser (β\beta) chosen from AsA_s design to a mask

(The transition widths are the usual textbook rules of thumb; the side-lobe levels measured above for N=31N = 31 differ by a few dB.)

Kaiser's design formulas

For an attenuation AsA_s in dB, Kaiser found that

β={0.1102 (As−8.7)As>500.5842 (As−21)0.4+0.07886 (As−21)21≤As≤500As<21N≈As−7.9514.36 Δf/fs+1\beta = \begin{cases} 0.1102\,(A_s - 8.7) & A_s > 50 \\ 0.5842\,(A_s - 21)^{0.4} + 0.07886\,(A_s - 21) & 21 \le A_s \le 50 \\ 0 & A_s < 21 \end{cases} \qquad N \approx \frac{A_s - 7.95}{14.36\,\Delta f / f_s} + 1

signal.kaiserord(As, width) returns both, with the width as a fraction of the Nyquist frequency fs/2f_s/2. Put the cutoff in the middle of the transition band, fc=(fp+fst)/2f_c = (f_p + f_{st})/2, because the window spreads the edge symmetrically around it.

Worked example: the vibration-channel low-pass

Given: fs=8 kHzf_s = 8\ \text{kHz}, fp=1 kHzf_p = 1\ \text{kHz}, fst=1.5 kHzf_{st} = 1.5\ \text{kHz}, As=60 dBA_s = 60\ \text{dB} (passband ripple 1 dB1\ \text{dB} allowed).

Find: β\beta, the number of taps, the gains at the band edges and the delay; then check the filter on a 300 Hz300\ \text{Hz} signal with a 2 kHz2\ \text{kHz} interferer.

Solve: β=0.1102×(60−8.7)=5.653\beta = 0.1102 \times (60 - 8.7) = 5.653. Δf/fs=0.0625\Delta f/f_s = 0.0625, so N≈52.05/0.8975+1=59.0N \approx 52.05/0.8975 + 1 = 59.0, rounded up by kaiserord to 60 taps. Cutoff fc=1.25 kHzf_c = 1.25\ \text{kHz}. Delay (N−1)/2=29.5(N - 1)/2 = 29.5 samples =3.69 ms= 3.69\ \text{ms}.

python · try it yourself
import numpy as np
from scipy import signal

fs, fp, fst, As = 8000, 1000, 1500, 60.0
numtaps, beta = signal.kaiserord(As, (fst - fp) / (fs / 2))
h = signal.firwin(numtaps, (fp + fst) / 2, window=("kaiser", beta), fs=fs)
print(f"{numtaps} taps, beta = {beta:.3f}, symmetric: {np.allclose(h, h[::-1])}, sum of taps (DC gain) = {h.sum():.5f}")
print("centre taps:", np.round(h[27:33], 5))
_, H = signal.freqz(h, worN=[0, 500, 1000, 1250, 1500, 2000, 3000], fs=fs)
for fk, Hk in zip([0, 500, 1000, 1250, 1500, 2000, 3000], H):
    print(f"  {fk:5d} Hz: {20 * np.log10(abs(Hk)):8.2f} dB")
print(f"delay = {(numtaps - 1) / 2} samples = {1e3 * (numtaps - 1) / 2 / fs:.3f} ms")

# Filter a 300 Hz signal with a 2 kHz interferer and compare after removing the delay
t = np.arange(800) / fs
x = np.sin(2 * np.pi * 300 * t) + 0.5 * np.sin(2 * np.pi * 2000 * t)
y = signal.lfilter(h, 1, x)
D = (numtaps - 1) / 2                             # 29.5 samples: compare with the input delayed by that much
ideal = np.sin(2 * np.pi * 300 * (t - D / fs))
err = y[100:] - ideal[100:]
print(f"rms error after the transient: {np.sqrt(np.mean(err**2)):.5f} (interferer was 0.35355 rms)")
60 taps, beta = 5.653, symmetric: True, sum of taps (DC gain) = 1.00000
centre taps: [0.07927 0.20973 0.29979 0.29979 0.20973 0.07927]
      0 Hz:     0.00 dB
    500 Hz:     0.00 dB
   1000 Hz:    -0.01 dB
   1250 Hz:    -6.02 dB
   1500 Hz:   -66.60 dB
   2000 Hz:   -72.66 dB
   3000 Hz:   -74.05 dB
delay = 29.5 samples = 3.688 ms
rms error after the transient: 0.00010 (interferer was 0.35355 rms)

Check: the taps are symmetric (linear phase) and sum to 1 (unit DC gain). The passband edge loses only 0.01 dB0.01\ \text{dB} and the stopband edge is 66.6 dB66.6\ \text{dB} down, inside the mask with a margin. After removing the 29.529.5-sample delay, the output differs from the clean 300 Hz300\ \text{Hz} sine by 10−410^{-4} rms: the interferer (0.3540.354 rms) is suppressed by about 71 dB71\ \text{dB}. An even number of taps gives a half-sample delay, harmless here; choose an odd NN when the output must line up with other signals on whole samples.

High-pass, band-pass and band-stop

The same recipe gives the other types. A high-pass is an all-pass delay minus a low-pass ("spectral inversion"), a band-pass is the difference of two low-passes, and a band-stop is a delay minus a band-pass. firwin does this when you pass pass_zero=False or a list of edges. A high-pass or band-stop needs an odd number of taps: an even-length symmetric FIR always has a zero at fs/2f_s/2 (type II, see Equiripple FIR).

python · try it yourself
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

fs = 16000
hp = signal.firwin(81, 1000, pass_zero=False, window="hamming", fs=fs)          # high-pass: odd length needed
bp = signal.firwin(81, [300, 3400], pass_zero=False, window="hamming", fs=fs)   # telephone band-pass
lp = signal.firwin(81, 1000, window="hamming", fs=fs)
inv = -lp
inv[40] += 1                                                                    # spectral inversion: delta - lowpass
print(f"high-pass vs delta minus low-pass: max tap difference {np.abs(hp - inv).max():.1e}")
fk = [100, 300, 1000, 2000, 3400, 6000]
for name, h in (("high-pass 1 kHz", hp), ("band-pass 300-3400", bp)):
    _, H = signal.freqz(h, worN=fk, fs=fs)
    print(f"{name:18s}", "  ".join(f"{f}: {round(20 * np.log10(abs(v)), 1) + 0.0:6.1f}" for f, v in zip(fk, H)), "dB")

f, H1 = signal.freqz(hp, worN=2048, fs=fs)
_, H2 = signal.freqz(bp, worN=2048, fs=fs)
plt.figure(figsize=(7, 3.2))
plt.plot(f, 20 * np.log10(np.abs(H1) + 1e-9), label="high-pass 1 kHz")
plt.plot(f, 20 * np.log10(np.abs(H2) + 1e-9), label="band-pass 300-3400 Hz")
plt.ylim(-90, 5); plt.xlabel("frequency (Hz)"); plt.ylabel("gain (dB)")
plt.grid(alpha=0.3); plt.legend(); plt.title("81-tap Hamming-window FIR filters, fs = 16 kHz")
plt.tight_layout(); plt.show()
high-pass vs delta minus low-pass: max tap difference 4.1e-04
high-pass 1 kHz    100:  -94.4  300:  -77.9  1000:   -6.0  2000:    0.0  3400:    0.0  6000:    0.0 dB
band-pass 300-3400 100:  -22.4  300:   -6.0  1000:    0.0  2000:    0.0  3400:   -6.0  6000: -101.8 dB

The high-pass is δ[n−40]\delta[n - 40] minus the low-pass, except for a tiny rescaling (firwin scales a high-pass to exactly unit gain at fs/2f_s/2). The band-pass edges sit at −6 dB-6\ \text{dB}, again by construction; widen the design edges if the band edges must be within 1 dB1\ \text{dB}. With 81 taps at 16 kHz16\ \text{kHz}, the transition from 300 Hz300\ \text{Hz} down to 100 Hz100\ \text{Hz} achieves only 22 dB22\ \text{dB}: low-frequency edges need many taps at a high sampling rate, a problem that decimation solves.

Guided lab: hearing the window

Hand calculation. For a 31-tap filter at 8 kHz8\ \text{kHz} with fc=1.25 kHzf_c = 1.25\ \text{kHz}, the rectangular window leaves side lobes near −22 dB-22\ \text{dB}; a 2 kHz2\ \text{kHz} tone happens to fall where the gain is −31.0 dB-31.0\ \text{dB} (about 1/361/36). The Hamming window gives −60.2 dB-60.2\ \text{dB} at the same frequency (about 1/10001/1000). Add 2000 to a freqz call to confirm both.

Simulation. Change N and the window list in the first program. Doubling NN halves the transition width (first null moves toward 1250 Hz1250\ \text{Hz}) but leaves the side-lobe levels where they are.

What you would measure. Load both filters into a USB audio interface or a microcontroller board running at 8 kSa/s8\ \text{kSa/s}, feed a 2 kHz2\ \text{kHz} sine of 0.5 V0.5\ \text{V} amplitude, and read the output on a scope. Expect about 14 mV14\ \text{mV} with the rectangular window and about 0.5 mV0.5\ \text{mV} with Hamming; the second is near or below the noise of a typical 12-bit or audio-codec output, so average the scope's FFT. Uncertainty: about ±0.2 dB\pm 0.2\ \text{dB} in the passband (generator and converter gains), a few dB at −60 dB-60\ \text{dB} because of noise.

Hazards and safe setup. Low-voltage signals only: a function generator and a USB-powered board or interface. Keep the generator below the input's full scale, set the level with the output disabled, and use headphones at low volume if you listen.

Pitfalls

  • Expecting a longer rectangular-window filter to reach more attenuation: the side lobes stay at about −21 dB-21\ \text{dB} for any NN.
  • Reading firwin's cutoff as a −3 dB-3\ \text{dB} frequency: it is the −6 dB-6\ \text{dB} (half-amplitude) point.
  • Designing a high-pass with an even number of taps (SciPy refuses; the response would be zero at fs/2f_s/2).
  • Forgetting the delay (N−1)/2(N - 1)/2 when comparing input and output, or when the filter sits in a control loop.
  • Writing the cutoff in hertz without fs=: SciPy then reads it as a fraction of Nyquist.

Practice

  1. Find β\beta and the Kaiser length for As=80 dBA_s = 80\ \text{dB} and Δf/fs=0.05\Delta f/f_s = 0.05.
  2. A Hamming-window low-pass needs a transition of 400 Hz400\ \text{Hz} at fs=16 kHzf_s = 16\ \text{kHz}. Estimate NN.
  3. Why must a linear-phase FIR high-pass have an odd number of taps?
Answer
  1. β=0.1102×71.3=7.857\beta = 0.1102 \times 71.3 = 7.857; N≈72.05/(14.36×0.05)+1=101.3N \approx 72.05/(14.36 \times 0.05) + 1 = 101.3, so 102 taps.
  2. N≈3.3×16 000/400=132N \approx 3.3 \times 16\,000/400 = 132 taps.
  3. An even-length symmetric impulse response has H(ejπ)=0H(e^{j\pi}) = 0 (the terms cancel in pairs at z=−1z = -1), so its gain at fs/2f_s/2 is forced to zero.

Test yourself

In the window method, the minimum stopband attenuation is set mainly by

  1. the number of taps
  2. the window shape
  3. the sampling rate
  4. the cutoff frequency

firwin(N, fc, fs=fs) places fcf_c at the frequency where the gain is

  1. −3-3 dB
  2. −6-6 dB
  3. −1-1 dB
  4. −60-60 dB

For As=60A_s = 60 dB, Kaiser's β\beta is about

  1. 0
  2. 3.4
  3. 5.65
  4. 8.7

A 60-tap linear-phase FIR at 8 kHz delays every frequency by

  1. 7.5 ms
  2. 3.69 ms
  3. 60 samples
  4. depends on frequency