Skip to main content

FIR vs IIR Filters

What are FIR and IIR filters?​

FIR (finite impulse response) and IIR (infinite impulse response) filters are the two families of digital filter. An FIR filter computes each output from recent inputs only, so its memory of any input ends. An IIR filter also feeds back past outputs, so its memory fades but never ends. FIR filters are always stable; IIR filters need fewer calculations.

Four charts comparing a windowed-sinc FIR filter and a Butterworth IIR filter with the same cutoff: magnitude response in dB against log frequency, group delay, impulse response, and a noisy pulse after each filter

A windowed-sinc FIR filter (blue) and a Butterworth IIR filter (orange) with the same cutoff: magnitude, group delay, impulse response and the effect on a pulse. Try the interactive version.

Key takeaways
  • FIR = feed-forward only. Its impulse response is a finite list of taps, it is always stable, and a symmetric kernel gives linear phase (every frequency is delayed equally).
  • IIR = feedback. Its impulse response decays for ever. It reaches a given sharpness with far fewer multiplications, but its delay changes with frequency.
  • The windowed-sinc method designs an FIR filter in four steps: sinc, truncate, window, normalise. High-pass and band-pass filters come from the same recipe.
  • A Butterworth filter is maximally flat, −3 dB at the cutoff, and rolls off at 20 dB per decade per order. Digitally, it is built from biquads via the bilinear transform.
  • Choose FIR when phase matters or the filter must adapt; choose IIR for low cost and low latency on live data.

How FIR and IIR filters work​

A digital filter is a rule for computing each output sample y[n]y[n] from input samples x[n]x[n]. For the linear filters on this page, that rule is a difference equation: a weighted sum of recent inputs and, for IIR filters, recent outputs.

y[n]=∑k=0Mbk x[n−k]⏟FIRy[n]=∑k=0Mbk x[n−k]  −  ∑k=1Nak y[n−k]⏟IIR\underbrace{y[n] = \sum_{k=0}^{M} b_k \, x[n-k]}_{\text{FIR}} \qquad\qquad \underbrace{y[n] = \sum_{k=0}^{M} b_k \, x[n-k] \;-\; \sum_{k=1}^{N} a_k \, y[n-k]}_{\text{IIR}}

The bkb_k are the feed-forward coefficients and the aka_k the feedback coefficients. An FIR filter is the special case with no aka_k. Each z−1z^{-1} box in the diagram below holds a sample for one step: it is a one-sample delay.

Block diagrams of an FIR filter, a delay line whose taps are multiplied by b0 to b3 and added, and of a second-order IIR section, which adds the past two outputs multiplied by minus a1 and minus a2 back into the sum

The names come from what each does with a single unit pulse (an impulse) at the input:

  • FIR: the pulse walks down the delay line, picking up each weight in turn, and is gone after M+1M+1 samples. The output is the list of weights itself, so an FIR filter's impulse response is its coefficients, and applying it is a convolution of the signal with those taps.
  • IIR: the pulse comes out, is fed back in, comes out again a little smaller, and so on. The response decays like a ringing bell but, mathematically, never reaches exactly zero.

In the z-domain (the algebra of sampled signals, in which z−1z^{-1} stands for a one-sample delay), the transfer function is H(z)=B(z)/A(z)H(z) = B(z)/A(z). The roots of B(z)B(z) are the filter's zeros, values of zz where HH is zero, and the roots of A(z)A(z) its poles, values where HH becomes infinite. An FIR filter has only zeros (all its poles are at the origin), so it can't become unstable. An IIR filter is stable only if every pole lies inside the unit circle, the circle of radius 1 on which each frequency, from 0 Hz up to the sample rate, is a point; a pole on or outside it makes the output ring for ever or grow without limit.

To see what a filter does to each frequency, evaluate HH around the unit circle and plot the gain and phase: the Bode plot of the filter.

FIR vs IIR filter: which should you use?​

Use an FIR filter when waveform shape or exact timing matters, and an IIR filter when computation is tight or the data is live.

FIR filterIIR filter
StructureFeed-forward onlyFeed-forward plus feedback
Impulse responseFinite: exactly M+1M + 1 samplesInfinite: decays, never quite ends
StabilityAlways stableStable only if every pole is inside the unit circle
PhaseLinear phase with a symmetric kernel: no phase distortionNon-linear: different frequencies are delayed by different amounts
Delay (latency)M/2M/2 samples, the same at every frequency; long for sharp filtersShort at low frequencies, peaking near the cutoff
Multiplications per sampleOne per tap (about half with a symmetric kernel); tens to hundreds, more as the transition narrowsAbout five per biquad, so 10 to 20 for common orders; fewest with Chebyshev and elliptic designs
Numerical sensitivityLow; quantised taps only add small ripplesHigher; needs biquads, and care in fixed point
DesignWindowed-sinc, least squares, Parks–McClellan; any shapeFrom analogue prototypes (Butterworth, Chebyshev, elliptic, Bessel)
Adaptive filteringThe usual choice (e.g. LMS echo cancellers), since it can't go unstableRarely used
Analogue equivalentTapped delay lines and surface acoustic wave (SAW) filters, mainly at radio frequenciesRC, LC and op-amp filters, which IIR designs model directly
Best forAudio and measurement where shape and phase matter; offline analysis; adaptive filtersReal-time control, sensors, microcontrollers, audio EQ; anything on a tight budget

Anti-aliasing filters are a common case where the choice is made for you: the filter in front of an analogue-to-digital converter has to be analogue, so it is usually a Butterworth, Chebyshev, elliptic or Bessel design. Inside the digital part of an oversampling converter, the decimation filters are usually FIR. See anti-aliasing filters and oversampling.

Worked comparison​

Take a 1 kHz sample rate, a low-pass with −3 dB at 50 Hz, and at least 40 dB of rejection from 100 Hz up:

DesignSizeMultiplications per sampleDelay
FIR, windowed-sinc, Hamming window39 taps39 (20 using symmetry)19 ms at every frequency
IIR, 7th-order Butterworth3 biquads + 1 first-order section1814 ms at low frequencies, rising to about 25 ms near the cutoff

For a gentle spec like this, the two are close. Tighten it to −60 dB from 60 Hz and the FIR filter needs about 305 taps with a Blackman window, a 152 ms delay; a Butterworth filter would need order 38, and that is where Chebyshev and elliptic IIR designs, with far lower orders, win. These figures come from the demo's design code.

What is a sinc function?​

The sinc function is sin⁡(x)/x\sin(x)/x, defined as 1 at x=0x = 0 (its limit). Signal processing usually uses the normalised sinc, which is zero at every non-zero whole number:

sinc⁡(x)=sin⁡(πx)πx,sinc⁡(0)=1\operatorname{sinc}(x) = \frac{\sin(\pi x)}{\pi x}, \qquad \operatorname{sinc}(0) = 1

It is the Fourier transform of a rectangle, so it describes the ideal filter. An ideal low-pass filter has a rectangular frequency response: gain 1 up to the cutoff fcf_c and 0 above it. Transform that rectangle back to the time domain and you get the filter's impulse response, a sinc:

h[k]=2fcsinc⁡(2fck)=sin⁡(2πfck)πkh[k] = 2 f_c \operatorname{sinc}(2 f_c k) = \frac{\sin(2\pi f_c k)}{\pi k}

with fcf_c given as a fraction of the sample rate (between 0 and 0.5). The same shape turns up in reverse, too: the spectrum of a short rectangular pulse is a sinc, so a rectangular window leaks into its neighbours in an FFT. A sinc filter in a delta-sigma converter is a related idea: a moving-average stage whose frequency response has the shape of a (periodic) sinc.

The ideal sinc is infinite and non-causal (half of it comes before the impulse), so it must be truncated and windowed. The low-pass filter guide shows the result as one formula; the next section takes it step by step.

How to design an FIR filter: the windowed-sinc method​

The windowed-sinc method turns the ideal sinc into a practical filter of M+1M + 1 taps (MM even, so there is a centre tap):

  1. Choose the cutoff fcf_c as a fraction of the sample rate, and the length MM. A longer kernel gives a sharper transition.
  2. Sample the sinc, centred on the middle tap. Shifting it by M/2M/2 makes the filter causal (it only uses samples it has seen):
h[i]=sin⁡(2πfc(i−M/2))i−M/2,i=0…M,h[M/2]=2πfch[i] = \frac{\sin\big(2\pi f_c (i - M/2)\big)}{i - M/2}, \qquad i = 0 \dots M, \qquad h[M/2] = 2\pi f_c
  1. Multiply by a window w[i]w[i], which tapers the ends to zero. Cutting the sinc off abruptly (a rectangular window) leaves large ripples in the frequency response; tapering trades a wider transition for a much deeper stopband.
  2. Normalise: divide every tap by their sum, so the gain at 0 Hz is exactly 1 (0 dB). This also absorbs the constant π\pi factor dropped in step 2.

The two classic windows, for i=0…Mi = 0 \dots M:

wHamming[i]=0.54−0.46cos⁡ ⁣(2πiM),wBlackman[i]=0.42−0.5cos⁡ ⁣(2πiM)+0.08cos⁡ ⁣(4πiM)w_{\text{Hamming}}[i] = 0.54 - 0.46\cos\!\left(\frac{2\pi i}{M}\right), \qquad w_{\text{Blackman}}[i] = 0.42 - 0.5\cos\!\left(\frac{2\pi i}{M}\right) + 0.08\cos\!\left(\frac{4\pi i}{M}\right)

The windowed-sinc recipe in five panels: an endless ideal sinc with 61 taps kept, a Blackman window, their product the low-pass kernel, the high-pass kernel made by spectral inversion with a tall centre spike, and the high-pass frequency response in dB, deep in the stopband and flat above the cutoff

Adapted from Burnett-Thompson (2007).

WindowStopband attenuationTransition width (roughly)Use it when
Rectangular (plain truncation)About 21 dB0.9/M0.9/M of the sample rateNot for filtering
HammingAbout 53 dB3.1/M3.1/MA good balance of sharpness and rejection
BlackmanAbout 74 dB4.6/M4.6/MDeep rejection, with a wider transition

The transition widths are a guide: they depend on how you define the band edges, so other texts give Blackman as roughly 4/M4/M, the figure the low-pass, high-pass and band-pass guides use. For the same number of taps, the window decides between a narrow transition and a deep stopband. With the windowed-sinc recipe, fcf_c is the half-amplitude point (−6 dB) of the finished filter, not the −3 dB point a Butterworth filter uses. Switch the window in the demo below and watch the stopband ripples drop from about −20 dB to below −70 dB.

High-pass, band-pass and band-stop from the same recipe​

Every other response comes from low-pass kernels of the same length:

  • High-pass by spectral inversion: negate every tap of the low-pass kernel, then add 1 to the centre tap. The result is "an impulse minus the low-pass", which passes everything the low-pass removes. The figure above shows the tall centre spike this leaves. (The high-pass filter guide compares it with simpler high-pass filters.)
  • High-pass by spectral reversal: multiply every other tap by −1. That mirrors the frequency response about a quarter of the sample rate, so a low-pass at fcf_c becomes a high-pass at 0.5−fc0.5 - f_c.
  • Band-pass: subtract a low-pass at the lower edge from a low-pass at the upper edge (same length, same window), tap by tap. Or convolve a low-pass kernel with a high-pass kernel, which gives a kernel almost twice as long.
  • Band-stop: add a low-pass at the lower edge to a high-pass at the upper edge, or spectrally invert a band-pass.

A windowed-sinc kernel is symmetric about its centre, so it has linear phase: it delays every frequency by exactly M/2M/2 samples. Run offline and centred on each sample, it doesn't delay the signal at all.

Other FIR design methods exist, such as least-squares and the Parks–McClellan (equiripple) algorithm, which get a given spec with fewer taps. The windowed-sinc method is the one to learn first: it fits in a dozen lines of code, and it's easy to see why it works.

What is a Butterworth filter?​

A Butterworth filter is a filter designed to have the flattest possible passband, with no ripple at all, for its order. Stephen Butterworth described it in 1930. Its magnitude response, for order nn and cutoff fcf_c, is:

∣H(f)∣2=11+(f/fc)2n|H(f)|^2 = \frac{1}{1 + (f/f_c)^{2n}}
  • At f=fcf = f_c the gain is 1/21/\sqrt{2}, −3 dB, whatever the order.
  • Far above the cutoff, the gain falls by 20n dB per decade (about 6n dB per octave). A 2nd-order filter falls at 40 dB per decade, a 4th-order at 80.
  • Below the cutoff, the first 2n−12n - 1 derivatives of ∣H∣2|H|^2 are zero at 0 Hz. That is what "maximally flat" means.
  • Its poles sit evenly spaced on a half circle in the left half of the s-plane (the complex-frequency plane used for analogue filters), at the angles π(2k+n−1)/(2n)\pi(2k + n - 1)/(2n) for k=1…nk = 1 \dots n.

Each pair of those poles is a second-order section with a quality factor QQ. A 2nd-order Butterworth filter is one section with Q=1/2≈0.7071Q = 1/\sqrt{2} \approx 0.7071; a 4th-order filter is two sections, with Q≈0.5412Q \approx 0.5412 and Q≈1.3066Q \approx 1.3066. An odd order adds one first-order section.

How to choose a Butterworth filter's order​

To pass up to fcf_c (at −3 dB) and reduce frequencies from fstopf_{stop} upwards by at least AA dB, the minimum order is:

n≥log⁡10(10A/10−1)2log⁡10(fstop/fc)n \ge \frac{\log_{10}\left(10^{A/10} - 1\right)}{2 \log_{10}\left(f_{stop}/f_c\right)}

rounded up. For example, for −40 dB at twice the cutoff, n≥log⁡10(9999)/(2log⁡102)=4.0/0.602=6.6n \ge \log_{10}(9999) / (2 \log_{10} 2) = 4.0/0.602 = 6.6, so a 7th-order filter. For a digital filter, use the prewarped ratio tan⁡(πfstop/fs)/tan⁡(πfc/fs)\tan(\pi f_{stop}/f_s) / \tan(\pi f_c/f_s) instead of fstop/fcf_{stop}/f_c (explained below). At a 1 kHz sample rate with fc=50f_c = 50 Hz and fstop=100f_{stop} = 100 Hz, that gives 6.4, so order 7 again.

Chebyshev, elliptic and Bessel filters are the alternatives, with different trade-offs:

  • Chebyshev type I allows ripple in the passband (type II in the stopband) for a steeper transition at the same order.
  • Elliptic (Cauer) filters ripple in both bands and give the steepest transition for a given order.
  • Bessel filters roll off gently but delay low frequencies almost equally, so pulses keep their shape.

How to design a digital IIR filter: the bilinear transform and biquads​

The usual route to a digital IIR filter is to design the analogue filter first, then convert it. The bilinear transform replaces each ss in the analogue transfer function with:

s=2fs 1−z−11+z−1s = 2 f_s \, \frac{1 - z^{-1}}{1 + z^{-1}}

It maps the whole analogue frequency axis onto the digital one from 0 to fs/2f_s/2, so a stable analogue filter always gives a stable digital filter, and nothing aliases. Frequencies are squeezed in the process, more so near fs/2f_s/2: an analogue frequency Ω\Omega lands at a digital frequency ff where Ω=2fstan⁡(πf/fs)\Omega = 2 f_s \tan(\pi f / f_s). Prewarping corrects for that at the frequency that matters: design the analogue filter with its cutoff at 2fstan⁡(πfc/fs)2 f_s \tan(\pi f_c / f_s), and the digital filter's −3 dB point lands exactly on fcf_c.

For one second-order section with quality factor QQ, writing K=tan⁡(πfc/fs)K = \tan(\pi f_c / f_s), the low-pass coefficients come out as:

b0=b2=K2D,b1=2b0,a1=2(K2−1)D,a2=1−K/Q+K2D,D=1+K/Q+K2b_0 = b_2 = \frac{K^2}{D}, \quad b_1 = 2b_0, \quad a_1 = \frac{2(K^2 - 1)}{D}, \quad a_2 = \frac{1 - K/Q + K^2}{D}, \quad D = 1 + K/Q + K^2

and for a high-pass, b0=b2=1/Db_0 = b_2 = 1/D and b1=−2/Db_1 = -2/D with the same a1a_1 and a2a_2. For example, a 2nd-order Butterworth low-pass at 100 Hz, sampled at 1 kHz, has K=tan⁡(0.1π)=0.3249K = \tan(0.1\pi) = 0.3249 and gives

b=[0.067455, 0.134911, 0.067455],a=[1, −1.142981, 0.412802]b = [0.067455,\ 0.134911,\ 0.067455], \qquad a = [1,\ -1.142981,\ 0.412802]

the same coefficients as the Audio EQ Cookbook formulas for Q=0.7071Q = 0.7071.

Building higher-order IIR filters from biquads​

Each pole pair becomes one second-order section (a biquad), and the sections run one after another, the output of one feeding the next. Expanding them into a single high-order difference equation is mathematically the same, but it isn't numerically: the roots of a long polynomial are extremely sensitive to rounding in its coefficients, and a high-order filter in that "direct form" can end up with a pole outside the unit circle. Cascaded second-order sections keep each pole pair's coefficients separate and well behaved.

Phase, group delay and linear phase​

Every causal filter delays the signal. The useful measure is the group delay: how long the filter holds up the energy at each frequency, τ(f)=−12πdφdf\tau(f) = -\frac{1}{2\pi}\frac{d\varphi}{df}, where φ\varphi is the phase.

  • A symmetric FIR filter has a constant group delay of M/2M/2 samples. Every frequency arrives together, so a pulse comes out the same shape, just later. That is linear phase.
  • An IIR filter's group delay varies with frequency. For a Butterworth low-pass it is smallest at low frequencies and peaks near the cutoff, and the peak grows with the order. At a 1 kHz sample rate and a 50 Hz cutoff, the delay at 1 Hz is about 3.2 ms (1st order), 4.5 ms (2nd), 8.3 ms (4th) and 16.2 ms (8th); the 4th-order filter's peaks at about 12.6 ms near the cutoff, and the 8th-order's at about 30 ms.

Unequal delay is phase distortion. You can see it in the step response: the frequencies near the cutoff arrive late and pile up, so a Butterworth low-pass overshoots a step by about 4% at 2nd order, 11% at 4th and 16.5% at 8th. A windowed-sinc filter rings too, but symmetrically, before and after the edge. On a filtered pulse, the FIR output is the same shape on both edges, and the IIR output is lopsided.

Zero-phase filtering offline​

When the whole recording is available, you can remove the delay altogether:

  • Forward-backward filtering (filtfilt in MATLAB and SciPy): run an IIR filter forwards, then run it again backwards over the result. The phase shifts cancel exactly. The magnitude is applied twice, so the attenuation doubles in dB and the −3 dB point becomes −6 dB.
  • Shift a symmetric FIR output back by M/2M/2 samples, or compute each output from the samples centred on it.

Neither works in real time, because both need samples from the future.

Common FIR and IIR filter mistakes​

The usual mistakes are numerical (IIR stability, too few FIR taps) or about how the cutoff is defined.

  • Building a high-order IIR filter as one difference equation. Coefficient rounding moves the poles, and a high-order direct-form filter, especially one with a low cutoff, can become unstable in single precision or fixed point. Use a cascade of biquads.
  • Forgetting phase distortion. An IIR filter changes the shape of pulses, steps and heartbeats. If shape or timing matters (ECG, seismic picking, measuring edges), use a linear-phase FIR filter or zero-phase filtering.
  • Using filtfilt and expecting the designed cutoff. Forward-backward filtering doubles the attenuation, so the −3 dB point moves. Design for −1.5 dB at the cutoff, or correct for it.
  • Too few taps. A short windowed-sinc kernel can't make a sharp transition: the transition width is several times fs/Mf_s/M. Check the response; don't trust the cutoff you typed.
  • Comparing cutoffs defined differently. A windowed-sinc fcf_c is the −6 dB point, a Butterworth fcf_c the −3 dB point, and some tools take the cutoff as a fraction of half the sample rate. Measure the −3 dB point of the finished filter.
  • No window, or the wrong one. Plain truncation leaves ripples only about 21 dB down, whatever the length. Use Hamming or Blackman.
  • Forgetting the start-up transient. Both kinds start from zero memory, so the first MM outputs of an FIR filter, and the first few time constants of an IIR filter, are not yet valid. Trim them, or start the filter from the first sample's value.
  • Asking for a cutoff the sample rate can't support. Cutoffs must be below fs/2f_s/2, and a bilinear-transform design warps badly near it. Leave a margin, or raise the sample rate.

How to apply FIR and IIR filters in JavaScript, React or Angular​

The demo designs a windowed-sinc FIR filter and a Butterworth IIR filter to the same cutoff at 1,000 samples per second, and recomputes their frequency responses, group delays, impulse responses and filtered signals on every change. Choose a response type, then change the cutoff, the FIR length and window, and the Butterworth order: the readout above the charts gives each filter's cost, delay and measured −3 dB point. Hover over any of the four charts for values; scroll to zoom, drag to pan, and double-click to reset.

Here is the code for this example. The JavaScript tab has the full windowed-sinc and Butterworth design code; the React and Angular tabs apply a windowed-sinc FIR low-pass and a 2nd-order Butterworth IIR low-pass to live, streaming data:

// FIR vs IIR: a windowed-sinc FIR filter and a Butterworth IIR filter with the same cutoff, side by side
const {
SciChartSurface,
NumericAxis,
LogarithmicAxis,
NumberRange,
XyDataSeries,
XyCustomFilter,
FastLineRenderableSeries,
VerticalLineAnnotation,
HorizontalLineAnnotation,
ELabelPlacement,
ENumericFormat,
EAutoRange,
LegendModifier,
ELegendPlacement,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
SciChartJsNavyTheme
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- 1. FIR design: the windowed-sinc recipe ---
// The ideal low-pass filter's impulse response is a sinc function. Cut it to M + 1 taps, centre it on
// i = M/2, taper it with a window and scale it so the taps add up to 1 (a gain of exactly 1 at 0 Hz).
// fc is a fraction of the sample rate, and it is the half-amplitude (-6 dB) point of the result.
function windowValue(name, i, M) {
if (name === "hamming") return 0.54 - 0.46 * Math.cos((2 * Math.PI * i) / M);
if (name === "blackman") {
return 0.42 - 0.5 * Math.cos((2 * Math.PI * i) / M) + 0.08 * Math.cos((4 * Math.PI * i) / M);
}
return 1; // rectangular: plain truncation
}
function windowedSincLowPass(fc, taps, windowName) {
const M = taps - 1;
const h = [];
for (let i = 0; i <= M; i++) {
const k = i - M / 2;
const sinc = k === 0 ? 2 * Math.PI * fc : Math.sin(2 * Math.PI * fc * k) / k; // the centre tap is the limit, 2 pi fc
h.push(sinc * windowValue(windowName, i, M));
}
const total = h.reduce((sum, v) => sum + v, 0);
return h.map((v) => v / total);
}
// High-pass by spectral inversion: an impulse minus the low-pass (negate every tap, add 1 to the centre)
function spectralInversion(h) {
const inverted = h.map((v) => -v);
inverted[(h.length - 1) / 2] += 1;
return inverted;
}
function designFir(type, fc, taps, windowName) {
if (type === "low-pass") return windowedSincLowPass(fc, taps, windowName);
if (type === "high-pass") return spectralInversion(windowedSincLowPass(fc, taps, windowName));
// Band-pass from fc to 2 fc: a low-pass at 2 fc minus a low-pass at fc
const upper = windowedSincLowPass(2 * fc, taps, windowName);
const lower = windowedSincLowPass(fc, taps, windowName);
return upper.map((v, i) => v - lower[i]);
}

// --- 2. IIR design: a Butterworth filter as a chain of second-order sections (biquads) ---
// The analogue Butterworth poles sit evenly round a half circle. Each pair becomes one biquad with quality
// factor Q, and an odd order adds a first-order section. The bilinear transform maps each section to a
// digital one; K = tan(pi fc / fs) "prewarps" the cutoff so the digital filter is -3 dB exactly at fc.
// Each section is { b: [b0, b1, b2], a: [1, a1, a2] }, for y[n] = b0 x[n] + b1 x[n-1] + b2 x[n-2] - a1 y[n-1] - a2 y[n-2].
function butterworthSections(kind, fc, order) {
const K = Math.tan(Math.PI * fc);
const sections = [];
for (let k = 1; k <= Math.floor(order / 2); k++) {
const theta = (Math.PI * (2 * k + order - 1)) / (2 * order); // angle of the k-th analogue pole
const Q = -1 / (2 * Math.cos(theta));
const norm = 1 / (1 + K / Q + K * K);
const a = [1, 2 * (K * K - 1) * norm, (1 - K / Q + K * K) * norm];
const b = kind === "low-pass" ? [K * K * norm, 2 * K * K * norm, K * K * norm] : [norm, -2 * norm, norm];
sections.push({ b, a });
}
if (order % 2 === 1) {
const norm = 1 / (1 + K);
const a = [1, (K - 1) * norm, 0];
const b = kind === "low-pass" ? [K * norm, K * norm, 0] : [norm, -norm, 0];
sections.push({ b, a });
}
return sections;
}
function designIir(type, fc, order) {
if (type === "band-pass") {
// A Butterworth high-pass at fc followed by a Butterworth low-pass at 2 fc
return [...butterworthSections("high-pass", fc, order), ...butterworthSections("low-pass", 2 * fc, order)];
}
return butterworthSections(type, fc, order);
}

// --- 3. Frequency response and group delay of any filter given as sections ---
// An FIR filter is a single section with b = the taps and a = [1]. At w = 2 pi f / fs, a polynomial
// p gives P = sum of p[k] e^(-i w k). The group delay (how long each frequency is held up, in samples)
// is the real part of sum(k p[k] e^(-i w k)) / P, for b minus for a, summed over the sections.
function polynomialAt(p, w) {
let re = 0;
let im = 0;
let dRe = 0;
let dIm = 0;
for (let k = 0; k < p.length; k++) {
const c = Math.cos(w * k);
const s = -Math.sin(w * k);
re += p[k] * c;
im += p[k] * s;
dRe += k * p[k] * c;
dIm += k * p[k] * s;
}
const magnitudeSquared = re * re + im * im;
return { magnitude: Math.sqrt(magnitudeSquared), delay: (dRe * re + dIm * im) / (magnitudeSquared || 1e-300) };
}
function responseAt(sections, f) {
const w = (2 * Math.PI * f) / SAMPLE_RATE;
let gain = 1;
let delay = 0;
for (const { b, a } of sections) {
const top = polynomialAt(b, w);
const bottom = polynomialAt(a, w);
gain *= top.magnitude / bottom.magnitude;
delay += top.delay - bottom.delay;
}
return { gainDb: 20 * Math.log10(Math.max(gain, 1e-6)), delaySamples: delay }; // floor at -120 dB
}

// --- 4. Running the filters on data ---
// SciChart.js runs each filter with an XyCustomFilter, which calls filterFunction(index, y) for each point
// in index order: from 0 when it recalculates everything (on creation, or when filterFunction is set).
// The FIR filter reads earlier inputs from the source series; the IIR filter keeps each section's last two
// inputs and outputs as its state, and clears it at index 0. (If you update a single point of the source,
// set filterFunction again so the whole output is recalculated.)
function firFilterFunction(sourceSeries, taps) {
return (index) => {
const x = sourceSeries.getNativeYValues();
let sum = 0;
for (let k = 0; k < taps.length && k <= index; k++) sum += taps[k] * x.get(index - k);
return sum;
};
}
function iirFilterFunction(sections) {
let state = [];
return (index, y) => {
if (index === 0 || !state.length) state = sections.map(() => ({ x1: 0, x2: 0, y1: 0, y2: 0 }));
let value = y;
sections.forEach(({ b, a }, s) => {
const z = state[s];
const out = b[0] * value + b[1] * z.x1 + b[2] * z.x2 - a[1] * z.y1 - a[2] * z.y2;
z.x2 = z.x1;
z.x1 = value;
z.y2 = z.y1;
z.y1 = out;
value = out;
});
return value;
};
}
// The IIR filter's impulse response: feed it a single 1 followed by zeros
function iirImpulseResponse(sections, length) {
const step = iirFilterFunction(sections);
return Array.from({ length }, (_, n) => step(n, n === 0 ? 1 : 0));
}

// --- 5. The test signal: a rectangular pulse with a little noise (a seeded random generator) ---
let seed = 1977;
const random = () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
const gaussian = () => Math.sqrt(-2 * Math.log(random() || 1e-12)) * Math.cos(2 * Math.PI * random());
const time = [];
const pulse = [];
for (let n = 0; n < SAMPLE_RATE; n++) {
const t = n / SAMPLE_RATE;
time.push(1000 * t); // milliseconds
pulse.push((t >= 0.3 && t < 0.6 ? 1 : 0) + 0.05 * gaussian());
}

// --- 6. The four charts ---
const theme = new SciChartJsNavyTheme();
const FIR_COLOUR = "#50C7E0";
const IIR_COLOUR = "#F48420";
const addModifiers = (surface, legend = undefined) => {
surface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
if (legend) surface.chartModifiers.add(new LegendModifier({ showCheckboxes: true, placement: legend }));
};
const logFrequencyAxis = (wasmContext) =>
new LogarithmicAxis(wasmContext, {
axisTitle: "Frequency (Hz)",
logBase: 10,
labelFormat: ENumericFormat.SignificantFigures,
labelPrecision: 2,
autoTicks: false, // a labelled gridline at 1, 10 and 100 Hz, and minor gridlines between
majorDelta: 1,
minorDelta: 1,
visibleRange: new NumberRange(1, SAMPLE_RATE / 2)
});
const line = (wasmContext, dataSeries, stroke, thickness = 2) =>
new FastLineRenderableSeries(wasmContext, { dataSeries, stroke, strokeThickness: thickness });

// Chart 1: magnitude response in dB on a log frequency axis
const magnitude = await SciChartSurface.create(ui.magnitudeDiv, { theme, title: "Magnitude", titleStyle: { fontSize: 16 } });
magnitude.sciChartSurface.xAxes.add(logFrequencyAxis(magnitude.wasmContext));
magnitude.sciChartSurface.yAxes.add(
new NumericAxis(magnitude.wasmContext, { axisTitle: "Gain (dB)", visibleRange: new NumberRange(-100, 6) })
);
const firGain = new XyDataSeries(magnitude.wasmContext, { dataSeriesName: "FIR (windowed-sinc)" });
const iirGain = new XyDataSeries(magnitude.wasmContext, { dataSeriesName: "IIR (Butterworth)" });
magnitude.sciChartSurface.renderableSeries.add(
line(magnitude.wasmContext, firGain, FIR_COLOUR),
line(magnitude.wasmContext, iirGain, IIR_COLOUR)
);
const cutoffLines = [0, 1].map(
() =>
new VerticalLineAnnotation({
x1: 50,
stroke: "#FFFFFF88",
strokeDashArray: [6, 4],
showLabel: true,
labelPlacement: ELabelPlacement.TopRight
})
);
magnitude.sciChartSurface.annotations.add(
...cutoffLines,
new HorizontalLineAnnotation({
y1: -3,
stroke: "#FFFFFF66",
strokeDashArray: [2, 4],
showLabel: true,
labelValue: "-3 dB",
labelPlacement: ELabelPlacement.BottomLeft
})
);
addModifiers(magnitude.sciChartSurface, ELegendPlacement.BottomLeft);

// Chart 2: group delay in milliseconds: flat for the FIR filter, frequency-dependent for the IIR filter
const delay = await SciChartSurface.create(ui.delayDiv, { theme, title: "Group delay", titleStyle: { fontSize: 16 } });
delay.sciChartSurface.xAxes.add(logFrequencyAxis(delay.wasmContext));
delay.sciChartSurface.yAxes.add(
new NumericAxis(delay.wasmContext, {
axisTitle: "Delay (ms)",
autoRange: EAutoRange.Always,
growBy: new NumberRange(0.05, 0.1)
})
);
const firDelay = new XyDataSeries(delay.wasmContext, { dataSeriesName: "FIR delay" });
const iirDelay = new XyDataSeries(delay.wasmContext, { dataSeriesName: "IIR delay" });
delay.sciChartSurface.renderableSeries.add(
line(delay.wasmContext, firDelay, FIR_COLOUR),
line(delay.wasmContext, iirDelay, IIR_COLOUR)
);
addModifiers(delay.sciChartSurface);

// Chart 3: impulse responses: the FIR filter's taps end; the IIR filter's response decays for ever
const IMPULSE_LENGTH = 400; // samples
const impulse = await SciChartSurface.create(ui.impulseDiv, { theme, title: "Impulse response", titleStyle: { fontSize: 16 } });
impulse.sciChartSurface.xAxes.add(
new NumericAxis(impulse.wasmContext, {
axisTitle: "Time (ms)",
labelPrecision: 0,
visibleRange: new NumberRange(0, IMPULSE_LENGTH)
})
);
impulse.sciChartSurface.yAxes.add(
new NumericAxis(impulse.wasmContext, {
axisTitle: "Amplitude",
labelPrecision: 2,
autoRange: EAutoRange.Always,
growBy: new NumberRange(0.1, 0.1)
})
);
const firImpulse = new XyDataSeries(impulse.wasmContext, { dataSeriesName: "FIR taps" });
const iirImpulse = new XyDataSeries(impulse.wasmContext, { dataSeriesName: "IIR impulse response" });
impulse.sciChartSurface.renderableSeries.add(
line(impulse.wasmContext, iirImpulse, IIR_COLOUR),
line(impulse.wasmContext, firImpulse, FIR_COLOUR)
);
const firEndLine = new VerticalLineAnnotation({
x1: 100,
stroke: FIR_COLOUR,
strokeDashArray: [4, 4],
showLabel: true,
labelValue: "FIR ends",
labelPlacement: ELabelPlacement.TopLeft,
axisLabelFill: FIR_COLOUR
});
impulse.sciChartSurface.annotations.add(firEndLine);
addModifiers(impulse.sciChartSurface);

// Chart 4: a noisy pulse through both filters. The XyCustomFilters recalculate when filterFunction is set
const signal = await SciChartSurface.create(ui.signalDiv, { theme, title: "Filtered pulse", titleStyle: { fontSize: 16 } });
signal.sciChartSurface.xAxes.add(new NumericAxis(signal.wasmContext, { axisTitle: "Time (ms)", labelPrecision: 0 }));
signal.sciChartSurface.yAxes.add(
new NumericAxis(signal.wasmContext, { axisTitle: "Amplitude", visibleRange: new NumberRange(-1.2, 1.5) })
);
const input = new XyDataSeries(signal.wasmContext, { xValues: time, yValues: pulse, dataSeriesName: "Input" });
const firOutput = new XyCustomFilter(input, { dataSeriesName: "FIR output" });
const iirOutput = new XyCustomFilter(input, { dataSeriesName: "IIR output" });
signal.sciChartSurface.renderableSeries.add(
line(signal.wasmContext, input, "#FFFFFF66", 1),
line(signal.wasmContext, firOutput, FIR_COLOUR),
line(signal.wasmContext, iirOutput, IIR_COLOUR)
);
addModifiers(signal.sciChartSurface, ELegendPlacement.TopRight);

// --- 7. Re-design and re-run both filters whenever a control changes ---
// Frequencies for the response charts: 500 steps, evenly spaced on a log scale from 1 Hz to fs / 2
const frequencies = Array.from({ length: 500 }, (_, i) => Math.pow(SAMPLE_RATE / 2, i / 499));
// The cutoff slider runs from 10 Hz to 200 Hz on a log scale
const sliderToCutoff = (value) => 10 * Math.pow(20, value / 100);

// Where the gain crosses -3 dB: step through in 0.5 Hz steps, then interpolate between the two steps
function minus3dBPoints(sections) {
const points = [];
let previous = responseAt(sections, 0.5).gainDb + 3.0103;
for (let f = 1; f < SAMPLE_RATE / 2; f += 0.5) {
const current = responseAt(sections, f).gainDb + 3.0103;
if (current > 0 !== previous > 0) points.push((f - 0.5 + (0.5 * previous) / (previous - current)).toFixed(1));
previous = current;
}
if (points.length) return "-3 dB at " + points.join(" and ") + " Hz";
const peak = Math.max(...frequencies.map((f) => responseAt(sections, f).gainDb));
return `gain peaks at ${peak.toFixed(1)} dB (too few taps for this band)`;
}
// Multiplications per output sample: one per tap for FIR; 5 per biquad and 3 per first-order section for IIR
const iirMultiplies = (sections) => sections.reduce((sum, s) => sum + (s.a[2] === 0 ? 3 : 5), 0);

function update() {
const type = ui.responseSelect.value;
const cutoff = sliderToCutoff(Number(ui.cutoffInput.value));
const taps = Number(ui.tapsInput.value);
const order = Number(ui.orderInput.value);
const fc = cutoff / SAMPLE_RATE;
const fir = designFir(type, fc, taps, ui.windowSelect.value);
const firSections = [{ b: fir, a: [1] }];
const iirSections = designIir(type, fc, order);

// Charts 1 and 2: magnitude and group delay
const firResponse = frequencies.map((f) => responseAt(firSections, f));
const iirResponse = frequencies.map((f) => responseAt(iirSections, f));
firGain.clear();
firGain.appendRange(frequencies, firResponse.map((r) => r.gainDb));
iirGain.clear();
iirGain.appendRange(frequencies, iirResponse.map((r) => r.gainDb));
const toMs = (samples) => (1000 * samples) / SAMPLE_RATE;
firDelay.clear();
// A symmetric kernel delays every frequency by exactly (taps - 1) / 2 samples
firDelay.appendRange(frequencies, frequencies.map(() => toMs((taps - 1) / 2)));
iirDelay.clear();
iirDelay.appendRange(frequencies, iirResponse.map((r) => toMs(r.delaySamples)));
cutoffLines[0].x1 = cutoff;
cutoffLines[0].labelValue = `fc ${cutoff.toFixed(0)} Hz`;
cutoffLines[1].x1 = 2 * cutoff;
cutoffLines[1].labelValue = `2 fc`;
cutoffLines[1].isHidden = type !== "band-pass";

// Chart 3: impulse responses
const sampleTimes = Array.from({ length: IMPULSE_LENGTH }, (_, n) => toMs(n));
firImpulse.clear();
firImpulse.appendRange(sampleTimes.slice(0, taps), fir);
iirImpulse.clear();
iirImpulse.appendRange(sampleTimes, iirImpulseResponse(iirSections, IMPULSE_LENGTH));
firEndLine.x1 = toMs(taps - 1);

// Chart 4: setting filterFunction makes each XyCustomFilter recalculate every point
firOutput.filterFunction = firFilterFunction(input, fir);
iirOutput.filterFunction = iirFilterFunction(iirSections);

// The readout: cost, delay and the measured -3 dB points
const passband = iirResponse.filter((r) => r.gainDb > -3.0103).map((r) => toMs(r.delaySamples));
const iirDelayText = passband.length
? `${Math.min(...passband).toFixed(1)} to ${Math.max(...passband).toFixed(1)} ms in the passband`
: "-";
ui.cutoffOutput.textContent = `${cutoff.toFixed(0)} Hz`;
ui.cutoffInput.setAttribute("aria-valuetext", `${cutoff.toFixed(0)} hertz`);
ui.tapsOutput.textContent = String(taps);
ui.orderOutput.textContent = String(order);
ui.firStatus.textContent =
`FIR: ${taps} taps, ${taps} multiplies per sample, ` +
`delay ${toMs((taps - 1) / 2).toFixed(1)} ms at every frequency, ${minus3dBPoints(firSections)}`;
ui.iirStatus.textContent =
`IIR: order ${order}${type === "band-pass" ? " high-pass + order " + order + " low-pass" : ""}, ` +
`${iirSections.length} section${iirSections.length > 1 ? "s" : ""}, ${iirMultiplies(iirSections)} multiplies per sample, ` +
`delay ${iirDelayText}, ${minus3dBPoints(iirSections)}`;
}

for (const control of [ui.responseSelect, ui.windowSelect]) control.addEventListener("change", update);
for (const control of [ui.cutoffInput, ui.tapsInput, ui.orderInput]) control.addEventListener("input", update);
update();

Key points:

  • One design, many responses: windowedSincLowPass builds the kernel; spectral inversion makes the high-pass, and the difference of two low-pass kernels the band-pass. butterworthSections returns one biquad per pole pair (plus a first-order section for an odd order), with the prewarped bilinear-transform coefficients.
  • Your own filter on chart data: an XyCustomFilter wraps a source XyDataSeries and calls your filterFunction(index, y) for each point in index order, from index 0 when it recalculates everything (on creation, or when filterFunction is set) and only for new points when data is appended. That suits both kinds: the FIR filter reads past inputs from the source series, and the IIR filter carries each biquad's state from one call to the next. If you update a single point of the source, filterFunction is called for that index alone, so set filterFunction again to recalculate the whole output.
  • The response charts are plain JavaScript: responseAt evaluates each section's polynomials at e−jωke^{-j\omega k} to get the gain in dB and the group delay, drawn on a LogarithmicAxis like a Bode plot. The impulse responses are the FIR taps and the IIR filter's output for a single 1.
  • Live updates: each control calls update(), which redesigns both filters, refills the XyDataSeries with clear() and appendRange(), and sets new filter functions, so all four charts redraw at once.

See it in the demo app: JavaScript trendline and moving average filters · React trendline and moving average filters · Angular trendline and moving average filters, whose moving average is the simplest FIR filter. For frequency responses on log axes, see the JavaScript chart with a logarithmic axis.

Go deeper: SciChart.js custom filter documentation, the data filters API overview, the logarithmic axis, and the related guides in this section: low-pass filter, high-pass filter, convolution and the Bode plot.

Frequently asked questions​

What is the difference between FIR and IIR filters?​

An FIR (finite impulse response) filter computes each output from recent inputs only, so its response to a single pulse ends after a fixed number of samples. An IIR (infinite impulse response) filter also feeds back its own past outputs, so that response dies away but never ends. FIR filters are always stable and can delay every frequency equally (linear phase); IIR filters reach the same sharpness with far fewer calculations, but delay frequencies unequally and can become unstable if designed carelessly.

What is an FIR filter?​

An FIR filter is a digital filter whose output is a weighted sum of the current input and a fixed number of past inputs: y[n] = b0 x[n] + b1 x[n-1] + ... + bM x[n-M]. The list of weights, called taps or coefficients, is also its impulse response. Applying it is a convolution. A common way to design one is the windowed-sinc method.

What is an IIR filter?​

An IIR filter is a digital filter that uses feedback: each output depends on recent inputs and on its own previous outputs. Because of that feedback its impulse response goes on for ever, decaying over time. Butterworth, Chebyshev, elliptic and Bessel filters are usually built as IIR filters, as a chain of second-order sections called biquads.

What is a Butterworth filter?​

A Butterworth filter is a filter designed to have the flattest possible passband: no ripple at all, with the gain falling smoothly to -3 dB at the cutoff frequency. Its magnitude is 1 / sqrt(1 + (f/fc)^(2n)) for order n, so it rolls off at 20n dB per decade above the cutoff. It was described by Stephen Butterworth in 1930 and is the usual default for analogue and digital IIR filters.

What is the sinc function?​

The sinc function is sin(x)/x, with the value 1 at x = 0. In signal processing the normalised form sin(πx)/(πx) is common; it is zero at every non-zero whole number. It matters because it is the Fourier transform of a rectangle: the impulse response of an ideal low-pass filter is a sinc, which is why windowed-sinc FIR filters start from it.

How do I apply an FIR or IIR filter in JavaScript?​

Design the coefficients first: windowed-sinc taps for an FIR filter, or Butterworth biquad coefficients from the bilinear transform for an IIR filter. Then run the difference equation over your samples: a weighted sum of past inputs for FIR, plus feedback from past outputs for IIR. In SciChart.js, wrap the filter in an XyCustomFilter on your XyDataSeries; it recalculates when the filter changes and as new samples are appended.

Sources​

  • Smith, S. W. (1997), The Scientist and Engineer's Guide to Digital Signal Processing, California Technical Publishing. Chapters 14 (introduction to digital filters, spectral inversion and reversal), 16 (windowed-sinc filters), 19 (recursive filters) and 20 (Chebyshev filters).
  • Oppenheim, A. V. and Schafer, R. W. (2010), Discrete-Time Signal Processing, 3rd edition, Pearson. FIR design by windowing (window attenuation and transition widths), the bilinear transform, and the effects of coefficient quantisation on direct-form and cascade structures.
  • Butterworth, S. (1930), "On the Theory of Filter Amplifiers", Experimental Wireless and the Wireless Engineer, 7, pp. 536–541. The original maximally flat filter.
  • Lyons, R. G. (2011), Understanding Digital Signal Processing, 3rd edition, Prentice Hall. FIR and IIR filters compared, biquads, and group delay.
  • Smith, J. O. (2007), Introduction to Digital Filters with Audio Applications, Center for Computer Research in Music and Acoustics (CCRMA), Stanford University. Difference equations, poles and zeros, the bilinear transform and forward-backward (zero-phase) filtering.
  • Burnett-Thompson, A. (2007), A 3D Local Positioning System to track A Neutrally Buoyant Flow Follower, PhD thesis, University of Manchester, UK, chapter 3. The associated published paper is Burnett-Thompson, A. and York, T. (2007), A 3D Acoustic Local Positioning System to Track a Neutrally Buoyant Flow Follower, IEEE Instrumentation and Measurement Technology Conference (IMTC 2007). The structure of the windowed-sinc design section, and the idea of showing a high-pass kernel next to its frequency response.