Skip to main content

Low-Pass Filter

What is a low-pass filter?​

A low-pass filter (LPF, also written lowpass) is a filter that lets the low frequencies in a signal through and reduces the high ones. Slow changes pass almost untouched, while fast wiggles such as noise, hiss and hum are made smaller. The frequency where it starts to cut is the cutoff frequency.

A noisy signal and the same signal after a low-pass filter: the filtered line follows the slow wave and ignores the noise. Below, the filter's frequency response is flat up to the cutoff and then falls away

A noisy signal before and after a low-pass filter (top), and the filter's frequency response (bottom). Try the interactive version.

Key takeaways
  • A low-pass filter keeps slow changes and removes fast ones: it smooths noise, hum and hiss.
  • The cutoff frequency is where the output has dropped by 3 dB (half the power, about 71% of the amplitude). For an RC circuit, fc=1/(2πRC)f_c = 1/(2\pi RC).
  • Above the cutoff, the gain falls by 20 dB per decade for each order of the filter.
  • In code, the common types are the moving average, the windowed-sinc FIR and the single-pole IIR (exponential smoothing).
  • Every causal low-pass filter delays the signal. Sharper filters usually delay it more.

How a low-pass filter works​

Any signal can be thought of as a sum of sine waves at different frequencies (that's the idea behind the Fourier transform). A low-pass filter scales each of those waves by a different amount: by almost exactly 1 at low frequencies, and by less and less as the frequency rises. The chart of that scaling against frequency is the filter's frequency response.

The frequency response of first, second and fourth order low-pass filters: flat at 0 dB in the passband, 3 dB down at the cutoff, then falling at 20, 40 and 80 dB per decade through the transition band into the stopband

The terms you'll meet on every data sheet and filter design tool:

TermWhat it means
PassbandThe low frequencies the filter lets through, ideally with a gain of 1 (0 dB)
Cutoff frequency (fcf_c)The edge of the passband, usually where the gain is −3 dB: the output has half the power and about 71% of the amplitude of the input. Also called the corner or −3 dB frequency
Transition bandThe frequencies between the passband and the stopband, where the gain is falling
StopbandThe high frequencies the filter is meant to block, reduced by at least a stated amount, such as −60 dB (0.1%)
Roll-offHow fast the gain falls above the cutoff, in dB per decade (each tenfold rise in frequency) or dB per octave (each doubling)
OrderHow many energy-storing parts (capacitors, inductors) or feedback terms the filter has. Each order adds 20 dB per decade (about 6 dB per octave) of roll-off

Decibels make the numbers easier to read: −3 dB is 71% of the amplitude, −20 dB is 10%, −40 dB is 1% and −60 dB is 0.1%. Gain in dB is 20log⁡10(Aout/Ain)20 \log_{10}(A_{out}/A_{in}).

An ideal low-pass filter would pass everything below the cutoff and nothing above it, a "brick wall". No real filter can, because that would need the filter to react to input it hasn't received yet. Real filters trade off three things: how steep the transition is, how flat the passband stays, and how much they delay and distort the signal's shape.

What low-pass filters are used for​

Common uses:

  • audio: the low-pass control on a synthesiser or equaliser darkens the sound by removing treble; a subwoofer's crossover sends it only the bass, often below about 80 to 120 Hz;
  • sensor smoothing: temperature, pressure, accelerometer and load-cell readings carry electrical noise that is much faster than the quantity being measured;
  • anti-aliasing: before an analogue-to-digital converter samples a signal, a low-pass filter removes anything above half the sample rate (the Nyquist frequency), which would otherwise fold back as false low frequencies;
  • downsampling: the same rule applies in software. Filter before you keep every Mth sample (see decimation and anti-aliasing);
  • power supplies: an RC or LC filter smooths the ripple left after rectifying AC into DC;
  • trading and analytics: a moving average of a price is a low-pass filter on the price series, showing the trend under the day-to-day swings;
  • images: blurring is a two-dimensional low-pass filter, and some cameras put an optical low-pass filter in front of the sensor to prevent moiré patterns.

The RC low-pass filter circuit​

The simplest analogue low-pass filter is a resistor followed by a capacitor to ground: a first-order RC filter. A capacitor needs time to charge through the resistor. Slow changes give it that time, so the output follows the input. Fast changes don't, so the capacitor smooths them away.

An RC low-pass filter circuit: a resistor R in series from input to output, and a capacitor C from the output to 0 V, with the cutoff formula and a worked example of 1 kilohm and 220 nanofarads giving about 723 Hz

How to calculate the cutoff frequency​

The cutoff frequency of an RC low-pass filter is:

fc=12πRCf_c = \frac{1}{2\pi R C}

with RR in ohms, CC in farads and fcf_c in hertz. RCRC is the circuit's time constant, τ\tau: after a sudden step at the input, the output covers about 63% of the step in one time constant.

For example, with R=1 kΩR = 1\ \text{k}\Omega and C=220 nFC = 220\ \text{nF}:

fc=12π×1000×220×10−9=10.001382≈723 Hzf_c = \frac{1}{2\pi \times 1000 \times 220 \times 10^{-9}} = \frac{1}{0.001382} \approx 723\ \text{Hz}

The time constant is 1000×220×10−9=0.221000 \times 220 \times 10^{-9} = 0.22 ms. At a tenth of the cutoff (72 Hz) the gain is −0.04 dB, almost exactly 1. At the cutoff it is −3 dB. At ten times the cutoff (7.2 kHz) it is −20 dB, a tenth of the amplitude.

To work backwards from a cutoff you want, pick a convenient capacitor, then R=1/(2πfcC)R = 1/(2\pi f_c C). For 1 kHz with a 100 nF capacitor, R=1/(2π×1000×10−7)≈1.59 kΩR = 1/(2\pi \times 1000 \times 10^{-7}) \approx 1.59\ \text{k}\Omega. The nearest standard value of 1.5 kΩ gives about 1.06 kHz.

Some example pairs, worked out with the formula above:

RCTime constant RCCutoff fcf_cTypical use
10 kΩ1.5 µF15 ms10.6 HzSmoothing a slow sensor
10 kΩ100 nF1 ms159 HzRemoving audio-band noise from a slow control or sensor signal (mains hum at 50 or 60 Hz still gets through)
1 kΩ220 nF0.22 ms723 HzThe worked example
1.6 kΩ10 nF16 µs9.95 kHzTaming hiss on a voice or audio line
330 Ω22 nF7.3 µs21.9 kHzJust above the range of human hearing

The live demo below has a small low-pass filter calculator: type R and C, and it works out fcf_c and can apply it as the cutoff of a digital filter.

The RC filter's transfer function​

A filter's transfer function, HH, is the ratio of output to input at each frequency. For the RC low-pass filter, written with the Laplace variable ss:

H(s)=11+sRCH(s) = \frac{1}{1 + sRC}

Its size (magnitude) and phase at a frequency ff are:

∣H(f)∣=11+(f/fc)2,φ(f)=−arctan⁡(f/fc)|H(f)| = \frac{1}{\sqrt{1 + (f/f_c)^2}}, \qquad \varphi(f) = -\arctan(f/f_c)

At f=fcf = f_c, the magnitude is 1/2≈0.7071/\sqrt{2} \approx 0.707 (−3 dB) and the output lags the input by 45°. Far above the cutoff, doubling the frequency halves the output: −6 dB per octave, or −20 dB per decade. Plotted on log axes, gain and phase against frequency make a Bode plot, the usual way to show a filter's response.

First-order, second-order and Butterworth low-pass filters​

A first-order filter's gentle 20 dB per decade often isn't enough. If the noise is only five times the cutoff frequency, a first-order filter reduces it to about 20% (−14 dB). Higher orders roll off faster:

  • Second-order filters (an RLC circuit, or an active filter built around an op-amp) fall at 40 dB per decade. They have a quality factor, Q, which sets how sharp the corner is: a high Q gives a peak just before the cutoff.
  • Butterworth filters have the flattest possible passband, with no ripple, for a given order, and are −3 dB at the cutoff whatever the order. A 2nd-order Butterworth filter is a second-order filter with Q≈0.707Q \approx 0.707. For the formula and how to choose the order, see what is a Butterworth filter?
  • Chebyshev and elliptic filters accept ripple in the passband or stopband in return for a steeper transition.
  • Bessel filters roll off more gently but delay all low frequencies by nearly the same time, so a pulse or step keeps its shape.

Stacking two identical first-order RC stages (with a buffer between them) does not give a second-order filter with the same cutoff: their −3 dB point moves down to about 0.64 fcf_c, because each stage is already −3 dB at fcf_c.

Types of digital low-pass filter​

In software, a filter works on samples taken at a sample rate, fsf_s. The cutoff must be below half the sample rate. Most digital low-pass filters fall into two families:

  • FIR (finite impulse response) filters compute each output as a weighted sum of the latest inputs. The list of weights is the filter's kernel, and applying it is a convolution. FIR filters are always stable and, with a symmetric kernel, delay every frequency by the same time.
  • IIR (infinite impulse response) filters also feed back their own previous outputs. They reach a given sharpness with far fewer calculations, but delay different frequencies by different amounts.

Moving average filter​

The moving average is the simplest FIR low-pass filter: each output is the mean of the last MM inputs.

y[n]=1M∑k=0M−1x[n−k]y[n] = \frac{1}{M} \sum_{k=0}^{M-1} x[n-k]

Its −3 dB cutoff is close to 0.443 fs/M0.443 \, f_s / M, so a longer average gives a lower cutoff. It reduces random noise very well while keeping steps sharp. In the frequency domain it is a weak filter, though: its response has lobes above the cutoff, with nulls at multiples of fs/Mf_s/M, so some high frequencies leak through.

Windowed-sinc FIR filter​

The ideal brick-wall low-pass filter has an impulse response shaped like a sinc function, sin⁡(x)/x\sin(x)/x. It goes on for ever in both directions, so a windowed-sinc filter cuts it to M+1M+1 points and tapers the ends with a window (such as Blackman or Hamming). For a cutoff fcf_c given as a fraction of the sample rate:

h[i]=sin⁡(2πfc(i−M/2))i−M/2 w[i],i=0…Mh[i] = \frac{\sin\big(2\pi f_c (i - M/2)\big)}{i - M/2} \, w[i], \qquad i = 0 \dots M

then the weights are scaled to add up to 1. The transition band is roughly 4/M4/M of the sample rate wide with a Blackman window, so a longer kernel gives a sharper filter. Its stopband can be very deep: with a Blackman window, below −70 dB. It costs M+1M+1 multiplications per sample and M/2M/2 samples of delay.

Single-pole IIR filter (exponential smoothing)​

The single-pole filter is the digital twin of the RC circuit. Each output moves a fraction α\alpha of the way from the previous output towards the new input:

y[n]=y[n−1]+α(x[n]−y[n−1]),α≈1−e−2πfc/fsy[n] = y[n-1] + \alpha \big(x[n] - y[n-1]\big), \qquad \alpha \approx 1 - e^{-2\pi f_c / f_s}

It is also called exponential smoothing or an exponential moving average (EMA). Written this way, it takes one multiplication per sample and one stored value, which makes it the usual choice on microcontrollers and for live data. Like the RC circuit, it rolls off at about 20 dB per decade.

Butterworth and other digital IIR filters​

Higher-order analogue designs such as Butterworth, Chebyshev and Bessel can be turned into digital IIR filters, usually with the bilinear transform, a substitution that maps the analogue filter's frequency axis onto the digital one. They are normally built as a chain of second-order sections (biquads, small IIR filters with two feedback terms each), which keeps them numerically stable. A 4th-order digital Butterworth filter uses two biquads, about ten multiplications per sample, to get a roll-off a short FIR filter can't match. For both designs side by side, see FIR vs IIR filters.

Which low-pass filter should you use?​

Use a moving average for quick smoothing, a single-pole filter for live data on little hardware, and a windowed-sinc or Butterworth filter when the cutoff has to be sharp.

FilterTypeRoll-off and stopbandDelayBest for
RC circuitAnalogue, 1st order20 dB/decadePhase lag, 45° at fcf_cAnti-aliasing before an ADC, simple hardware smoothing
Moving averageFIRWeak: lobes let some high frequencies through(M−1)/2(M-1)/2 samplesSmoothing noisy data while keeping steps sharp; easiest to explain
Windowed-sincFIRSharp, with a stopband below −70 dBM/2M/2 samples, the same for every frequencySeparating close frequencies; offline analysis where delay doesn't matter
Single pole (EMA)IIR, 1st orderAbout 20 dB/decadeSmall at low frequenciesLive data, microcontrollers, trends with little lag
ButterworthAnalogue or IIR, any order20 dB/decade per order, flat passbandGrows with order; not the same for every frequencyA general-purpose sharp filter with little computation
BesselAnalogue or IIRGentleNearly the same for every low frequencyPulses and waveforms whose shape must be kept

Delay and phase lag​

A low-pass filter that runs in real time can only use samples it has already seen, so it always lags the input. The smoother or sharper you make it, the more past samples it relies on, and the longer the lag.

For the demo's settings (a 500 Hz sample rate, a cutoff of 10 Hz and 50 Hz mains hum), the three digital filters compare like this:

Filter at a 10 Hz cutoffDelayGain at 50 Hz (the hum)
22-point moving average21 ms−21 dB (about 9% left)
201-tap windowed-sinc200 msBelow −70 dB (gone)
Single pole, α=0.118\alpha = 0.11815 ms at low frequencies−14 dB (about 20% left)

The windowed-sinc filter removes the hum completely but is ten times slower to respond than the others. That's fine when you analyse a recording, and a problem in a control loop or an alarm. Offline, you can remove the delay altogether: shift a symmetric FIR filter's output back by M/2M/2 samples, or run any filter forwards and then backwards over the data (zero-phase filtering).

Low-pass vs high-pass filter​

A high-pass filter is the mirror image of a low-pass filter.

Low-pass filterHigh-pass filter
PassesFrequencies below the cutoffFrequencies above the cutoff
RemovesNoise, hiss, hum and fast jitterDrift, DC offset and slow wander
RC circuitResistor in series, capacitor to groundCapacitor in series, resistor to ground
Effect on a signalSmooths itKeeps the detail and centres it on zero
Typical useSensor smoothing, anti-aliasing, a subwoofer feedRemoving baseline drift, tweeter feeds, AC coupling

Put one after the other and you get a band-pass filter, which keeps only the band between the two cutoffs. To see what a filter does to each frequency in a real signal, compare its spectrum before and after with an FFT.

Common low-pass filter mistakes​

Most low-pass mistakes are about where the cutoff sits and what the filter's delay does to the data.

  • Setting the cutoff at the noise frequency. At the cutoff, 71% of the amplitude still gets through. Put the cutoff well below the noise, so the noise falls in the stopband, and check the gain there.
  • Forgetting the delay. A heavily smoothed reading is an old reading. In control loops, alarms and live dashboards, choose the lowest-lag filter that removes enough noise.
  • Using a moving average to remove a specific frequency. Its lobes leak. Unless the unwanted frequency sits exactly on one of its nulls, a windowed-sinc or Butterworth filter removes it far better.
  • Downsampling without filtering first. Keeping every Mth sample folds high frequencies down into false slow waves (aliasing). Low-pass filter below the new Nyquist frequency first.
  • Mixing up frequency units. Digital filter tools may want the cutoff in hertz, as a fraction of the sample rate, or as a fraction of half the sample rate. A cutoff out by a factor of two is a common bug.
  • Ignoring what's connected to an RC filter. A load resistance in parallel with the capacitor, or the resistance of the source driving it, shifts the cutoff. Buffer the output with an op-amp when it matters.
  • Starting from zero. A filter whose memory starts at zero makes a false ramp at the start of the data. Start it from the first sample, as the demo does.

How to build a low-pass filter in JavaScript, React or Angular​

The demo applies a moving average, a windowed-sinc or a single-pole filter to 2 seconds of a 500 Hz-sampled signal with 50 Hz hum, and recomputes the output and the frequency response each time you change the cutoff. Choose a filter type, drag the cutoff and watch the orange line and the frequency response change. Try the RC calculator and Use as cutoff. Hover to read values, scroll to zoom, drag to pan, and double-click to reset.

Here is the code for this chart. The live demo runs each filter on the chart's data with an XyCustomFilter; the React and Angular versions show the same pattern on live, streaming data, next to the built-in moving average:

// An interactive low-pass filter: filter a noisy signal and chart it with SciChart.js
const {
SciChartSurface,
NumericAxis,
LogarithmicAxis,
NumberRange,
XyDataSeries,
XyCustomFilter,
FastLineRenderableSeries,
VerticalLineAnnotation,
HorizontalLineAnnotation,
ELabelPlacement,
ENumericFormat,
LegendModifier,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
SciChartJsNavyTheme
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- 1. The test signal: a slow wave, plus mains hum and random noise ---
// A seeded random generator, so the noise is the same every time the chart loads
let seed = 2024;
const random = () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
// Gaussian (bell-curve) noise from two uniform random numbers: the Box-Muller method
const gaussian = () => Math.sqrt(-2 * Math.log(random() || 1e-12)) * Math.cos(2 * Math.PI * random());

const time = [];
const slow = []; // what we want to keep: 1.5 Hz and 4 Hz sine waves
const noisy = []; // what we measured: the slow wave + 50 Hz hum + noise
for (let n = 0; n < SAMPLE_RATE * DURATION; n++) {
const t = n / SAMPLE_RATE;
const wanted = Math.sin(2 * Math.PI * 1.5 * t) + 0.5 * Math.sin(2 * Math.PI * 4 * t);
time.push(t);
slow.push(wanted);
noisy.push(wanted + 0.3 * Math.sin(2 * Math.PI * HUM_FREQUENCY * t) + 0.3 * gaussian());
}

// --- 2. Digital low-pass filters ---
// Every filter here is a difference equation: y[n] = b[0]x[n] + b[1]x[n-1] + ... + a1 * y[n-1].
// FIR (finite impulse response) filters use only past inputs, so a1 = 0 and b is the "kernel".
// The single-pole IIR (infinite impulse response) filter also feeds back its last output.
//
// SciChart.js runs it on the chart's data with an XyCustomFilter, which calls filterFunction(index, y)
// for each point in index order: from 0 when it recalculates everything, and only for the new points
// when data is appended. So the function reads earlier inputs from the source series and keeps the
// last output for the feedback term.
function lowPassFilterFunction(sourceSeries, { b, a1 }) {
let previousOutput = 0;
return (index, y) => {
const inputs = sourceSeries.getNativeYValues(); // the source series' y values
if (index === 0) previousOutput = y; // start as if the signal had always been at its first value
let sum = a1 * previousOutput;
for (let k = 0; k < b.length; k++) {
sum += b[k] * inputs.get(Math.max(0, index - k)); // before the first sample, repeat the first sample
}
previousOutput = sum;
return sum;
};
}

// The filter's gain at frequency f, in decibels (dB): 0 dB passes unchanged, -3 dB is about 71% amplitude,
// -20 dB is 10% and -40 dB is 1%. H(f) = sum of b[k] e^(-i w k) / (1 - a1 e^(-i w)), with w = 2 pi f / sampleRate.
function gainDb({ b, a1 }, f) {
const w = (2 * Math.PI * f) / SAMPLE_RATE;
let re = 0;
let im = 0;
for (let k = 0; k < b.length; k++) {
re += b[k] * Math.cos(w * k);
im -= b[k] * Math.sin(w * k);
}
const magnitude = Math.hypot(re, im) / Math.hypot(1 - a1 * Math.cos(w), a1 * Math.sin(w));
return 20 * Math.log10(Math.max(magnitude, 1e-5)); // floor at -100 dB, where a moving average has a null
}

// Moving average: M equal weights of 1/M. Its -3 dB cutoff is close to 0.443 * sampleRate / M
function movingAverage(cutoff) {
const length = Math.max(1, Math.round((0.443 * SAMPLE_RATE) / cutoff));
return { b: new Array(length).fill(1 / length), a1: 0, label: `${length}-point moving average` };
}

// Windowed-sinc: the ideal low-pass impulse response (a sinc function), cut to a fixed length and tapered
// with a Blackman window. fc is the half-amplitude (-6 dB) frequency as a fraction of the sample rate.
function windowedSincKernel(fc, taps) {
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;
const blackman = 0.42 - 0.5 * Math.cos((2 * Math.PI * i) / M) + 0.08 * Math.cos((4 * Math.PI * i) / M);
h.push(sinc * blackman);
}
const total = h.reduce((sum, v) => sum + v, 0);
return h.map((v) => v / total); // normalise, so the gain at 0 Hz is exactly 1 (0 dB)
}
function windowedSinc(cutoff) {
// The transition band is about 4 / M of the sample rate: make it about as wide as the cutoff, up to 301 taps
const taps = Math.min(300, 2 * Math.round((2 * SAMPLE_RATE) / cutoff)) + 1;
const transition = (4 * SAMPLE_RATE) / (taps - 1);
// Find the design frequency that puts the -3 dB point exactly on the cutoff (a bisection search)
let low = cutoff / SAMPLE_RATE;
let high = Math.min(0.5, (cutoff + transition) / SAMPLE_RATE);
for (let i = 0; i < 30; i++) {
const middle = (low + high) / 2;
if (gainDb({ b: windowedSincKernel(middle, taps), a1: 0 }, cutoff) < -3.0103) low = middle;
else high = middle;
}
return { b: windowedSincKernel(high, taps), a1: 0, label: `${taps}-tap windowed-sinc` };
}

// Single-pole IIR (exponential smoothing): y[n] = y[n-1] + alpha * (x[n] - y[n-1]).
// The digital twin of an RC circuit. alpha is chosen so the gain is exactly -3 dB at the cutoff.
function singlePole(cutoff) {
const c = Math.cos((2 * Math.PI * cutoff) / SAMPLE_RATE);
const feedback = 2 - c - Math.sqrt((2 - c) * (2 - c) - 1); // a1 = 1 - alpha
const alpha = 1 - feedback;
return { b: [alpha], a1: feedback, label: `single pole, α = ${alpha.toFixed(3)}` };
}

// How long the filter delays slow signals, in samples. A symmetric FIR kernel delays every frequency
// by half its length. A single pole delays low frequencies by a1 / (1 - a1) samples.
const delaySamples = ({ b, a1 }) => (a1 ? a1 / (1 - a1) : (b.length - 1) / 2);

// Frequencies for the response chart: 400 steps, evenly spaced on a log scale, up to half the sample rate
const frequencies = Array.from({ length: 400 }, (_, i) => 0.5 * Math.pow(SAMPLE_RATE / 2 / 0.5, i / 399));

// --- 3. Chart 1: the signal in time, before and after the filter ---
const timeChart = await SciChartSurface.create(ui.timeDiv, { theme: new SciChartJsNavyTheme() });
timeChart.sciChartSurface.xAxes.add(new NumericAxis(timeChart.wasmContext, { axisTitle: "Time (s)" }));
timeChart.sciChartSurface.yAxes.add(
new NumericAxis(timeChart.wasmContext, {
axisTitle: "Amplitude",
visibleRange: new NumberRange(-3, 3)
})
);
// The measured data, and the filtered output: an XyCustomFilter that recalculates itself from the
// noisy series whenever its filter function changes or new data is appended to the noisy series
const noisySeries = new XyDataSeries(timeChart.wasmContext, {
xValues: time,
yValues: noisy,
dataSeriesName: "Noisy input"
});
const filteredSeries = new XyCustomFilter(noisySeries, { dataSeriesName: "Filtered output" });
timeChart.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(timeChart.wasmContext, {
dataSeries: noisySeries,
stroke: "#50C7E077",
strokeThickness: 1
}),
new FastLineRenderableSeries(timeChart.wasmContext, {
dataSeries: new XyDataSeries(timeChart.wasmContext, {
xValues: time,
yValues: slow,
dataSeriesName: "Slow wave (before noise)"
}),
stroke: "#FFFFFFAA",
strokeThickness: 1.5,
strokeDashArray: [6, 4]
}),
new FastLineRenderableSeries(timeChart.wasmContext, {
dataSeries: filteredSeries,
stroke: "#F48420",
strokeThickness: 3
})
);
// Hover for values, scroll to zoom, drag to pan, double-click to reset
timeChart.sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true }),
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);

// --- 4. Chart 2: the filter's frequency response (gain in dB against frequency, on a log scale) ---
const responseChart = await SciChartSurface.create(ui.responseDiv, { theme: new SciChartJsNavyTheme() });
responseChart.sciChartSurface.xAxes.add(
new LogarithmicAxis(responseChart.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(0.5, SAMPLE_RATE / 2)
})
);
responseChart.sciChartSurface.yAxes.add(
new NumericAxis(responseChart.wasmContext, { axisTitle: "Gain (dB)", visibleRange: new NumberRange(-80, 6) })
);
const responseSeries = new XyDataSeries(responseChart.wasmContext, { dataSeriesName: "Gain" });
responseChart.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(responseChart.wasmContext, {
dataSeries: responseSeries,
stroke: "#50C7E0",
strokeThickness: 2
})
);
// Mark the cutoff, the -3 dB level and the 50 Hz hum
const cutoffLine = new VerticalLineAnnotation({
x1: 10,
stroke: "#F48420",
strokeDashArray: [6, 4],
showLabel: true,
labelPlacement: ELabelPlacement.TopRight,
axisLabelFill: "#F48420"
});
responseChart.sciChartSurface.annotations.add(
cutoffLine,
new HorizontalLineAnnotation({
y1: -3,
stroke: "#FFFFFF88",
strokeDashArray: [2, 4],
showLabel: true,
labelValue: "-3 dB",
labelPlacement: ELabelPlacement.TopLeft
}),
new VerticalLineAnnotation({
x1: HUM_FREQUENCY,
stroke: "#FFFFFF55",
strokeDashArray: [2, 4],
showLabel: true,
labelValue: "50 Hz hum",
labelPlacement: ELabelPlacement.BottomRight
})
);
responseChart.sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);

// --- 5. Re-run the filter whenever a control changes ---
const designs = { "moving-average": movingAverage, "windowed-sinc": windowedSinc, "single-pole": singlePole };
// The slider runs from 2 Hz to 120 Hz on a log scale, so the low cutoffs get as much room as the high ones
const sliderToCutoff = (value) => 2 * Math.pow(60, value / 100);
const cutoffToSlider = (cutoff) => (100 * Math.log(cutoff / 2)) / Math.log(60);

function update() {
const cutoff = sliderToCutoff(Number(ui.cutoffInput.value));
const filter = designs[ui.typeSelect.value](cutoff);

// Setting filterFunction makes the XyCustomFilter recalculate every point
filteredSeries.filterFunction = lowPassFilterFunction(noisySeries, filter);
responseSeries.clear();
responseSeries.appendRange(
frequencies,
frequencies.map((f) => gainDb(filter, f))
);
cutoffLine.x1 = cutoff;
cutoffLine.labelValue = `cutoff ${cutoff.toFixed(1)} Hz`;

// Read the real -3 dB point off the response (the moving average can only get close)
let measured = 0;
while (measured < SAMPLE_RATE / 2 && gainDb(filter, measured) > -3.0103) measured += 0.05;
const delayMs = (1000 * delaySamples(filter)) / SAMPLE_RATE;
ui.cutoffOutput.textContent = `${cutoff.toFixed(1)} Hz`;
ui.cutoffInput.setAttribute("aria-valuetext", `${cutoff.toFixed(1)} hertz`);
ui.summary.textContent = `${filter.label} · -3 dB at ${measured.toFixed(1)} Hz · delay ${delayMs.toFixed(0)} ms`;
}

// The RC calculator: the cutoff of an analogue RC low-pass filter, f = 1 / (2 pi R C)
function rcCutoff() {
const ohms = Number(ui.rInput.value) * 1e3;
const farads = Number(ui.cInput.value) * 1e-6;
return 1 / (2 * Math.PI * ohms * farads);
}
function updateRc() {
const f = rcCutoff();
ui.rcOutput.textContent = isFinite(f) && f > 0 ? `${f.toPrecision(4)} Hz` : "-";
}

ui.typeSelect.addEventListener("change", update);
ui.cutoffInput.addEventListener("input", update);
ui.rInput.addEventListener("input", updateRc);
ui.cInput.addEventListener("input", updateRc);
ui.rcButton.addEventListener("click", () => {
const f = rcCutoff();
if (!isFinite(f) || f <= 0) return;
// The slider covers 2 to 120 Hz, so cutoffs outside that range are clamped
ui.cutoffInput.value = Math.min(100, Math.max(0, cutoffToSlider(f))).toFixed(1);
update();
});
update();
updateRc();

Key points:

  • Each filter is a difference equation, y[n]=∑kbk x[n−k]+a1 y[n−1]y[n] = \sum_k b_k \, x[n-k] + a_1 \, y[n-1]: a moving average and a windowed-sinc are just different weights bb, and the single-pole filter adds the feedback term a1a_1.
  • Your own filter on live data: an XyCustomFilter wraps a source XyDataSeries and calls your filterFunction(index, y) for each point, in index order. It starts from index 0 when it recalculates everything (when the series is created or filterFunction is set), and runs only the new points when data is appended. So the function can read earlier samples from the source series and keep the last output for the single-pole filter's feedback. In the demo, each control change sets a new filterFunction, and the chart redraws.
  • The zero-code option: for a plain moving average, the built-in XyMovingAverageFilter takes your XyDataSeries and a length. It is a trailing average (the first length − 1 points are left empty), it needs x values in ascending order, and it also updates itself as data is appended.
  • The frequency response is calculated in plain JavaScript from the filter's weights. It uses a LogarithmicAxis for frequency and a gain axis in dB, the layout of a Bode plot; a VerticalLineAnnotation marks the cutoff and a HorizontalLineAnnotation marks −3 dB.

See it in the demo app: JavaScript trendline and moving average filters · React trendline and moving average filters · Angular trendline and moving average filters, which uses the built-in moving average filter, the simplest low-pass. For a live signal and its spectrum, see the JavaScript audio analyzer · React audio analyzer · Angular audio analyzer.

Go deeper: SciChart.js moving average filter documentation, creating a custom filter, the data filters API overview, and the next guides in this section: high-pass filter, convolution and the FFT.

Frequently asked questions​

What does a low-pass filter do?​

A low-pass filter lets slow changes in a signal through and reduces fast ones. Frequencies below its cutoff pass almost unchanged, and frequencies above it are made smaller, more so the higher they are. The result is a smoother signal: hiss, hum, jitter and sensor noise are reduced, while the underlying trend is kept.

How do you calculate the cutoff frequency of a low-pass filter?​

For a resistor-capacitor (RC) low-pass filter, the cutoff frequency is fc = 1 / (2πRC), with R in ohms, C in farads and fc in hertz. For example, 1 kΩ and 220 nF give 1 / (2π × 1000 × 0.00000022), which is about 723 Hz. At that frequency the output is 3 dB down, about 71% of the input amplitude.

What is the difference between a low-pass and a high-pass filter?​

A low-pass filter keeps frequencies below its cutoff and reduces those above it, so it smooths a signal. A high-pass filter does the opposite: it keeps frequencies above its cutoff and removes slow changes such as drift or a DC offset. Using one after the other gives a band-pass filter.

Is a moving average a low-pass filter?​

Yes. A moving average replaces each sample with the mean of the last M samples, which is a simple FIR low-pass filter. It is the optimal filter for reducing random white noise while keeping the sharpest step response, but it is a poor frequency separator: its response has ripples above the cutoff that let some high frequencies through.

What is a Butterworth low-pass filter?​

A Butterworth low-pass filter has the flattest possible passband, with no ripple and a gain of −3 dB at the cutoff whatever its order. Above the cutoff its gain falls by 20 dB per decade for each order, so a 4th-order Butterworth falls at 80 dB per decade.

How do I make a low-pass filter in JavaScript?​

For a simple low-pass filter, apply exponential smoothing to each sample: y = y + alpha × (x - y), with alpha between 0 and 1. For a sharper filter, convolve the samples with a windowed-sinc kernel. In SciChart.js, put the raw samples in an XyDataSeries and wrap your filter in an XyCustomFilter, which recalculates as new data arrives; for a plain moving average, the built-in XyMovingAverageFilter does it with no code.

Sources​

  • Smith, S. W. (1997), The Scientist and Engineer's Guide to Digital Signal Processing, California Technical Publishing. Chapters 14 (introduction to digital filters), 15 (moving average filters), 16 (windowed-sinc filters) and 19 (recursive filters, including the single-pole filter).
  • Oppenheim, A. V. and Schafer, R. W. (2010), Discrete-Time Signal Processing, 3rd edition, Pearson. FIR and IIR filter design, and the bilinear transform.
  • Butterworth, S. (1930), "On the Theory of Filter Amplifiers", Experimental Wireless and the Wireless Engineer, 7, pp. 536–541. The original maximally flat filter.
  • Smith, J. O. (2007), Introduction to Digital Filters with Audio Applications, Center for Computer Research in Music and Acoustics (CCRMA), Stanford University. Difference equations, transfer functions and frequency response.
  • Oppenheim, A. V. (2011), Signals and Systems, RES.6-007, MIT OpenCourseWare. Lectures on filtering, the frequency response and Butterworth filters.