---
title: Simple digital filters
heading: Moving averages, exponential smoothing and differences
eyebrow: C9 · Lesson 19 · Simple digital filters
xp: 40
---

::: hook
A temperature logger's readings jitter, and a few lines of code fix it: average the last twenty samples, or blend each new reading into a running estimate. A strain gauge drifts, and subtracting each sample from the last removes the drift. These filters are so simple that they're often written without anyone calling them filters, yet each has a frequency response that says exactly what it keeps and what it throws away. Knowing it turns "average a few samples" into a design: pick the length that cancels mains hum exactly, or the smoothing factor that gives the cutoff you need.
:::

::: play
- Two low-pass filters, plotted from ω = 0 to π (half the sample rate): an M-point moving average, and an exponential smoother $y[n] = (1 - \alpha)\,y[n-1] + \alpha\,x[n]$.
- The moving average has exact nulls at multiples of 2π/M, and large side lobes between them. Change M and watch the nulls move.
- The smoother has no nulls but falls smoothly and needs only one multiply and one stored number. Smaller α smooths more.
:::
:::

```sim plot
view: graph
x: w = 0..3.1416 rad
y: H = 0..1.05
slider: M = 2..32 = 8 step 1
slider: alpha = 0.02..1 = 0.25 step 0.01
plot: abs(sin(M*(w + 0.000001)/2)/(M*sin((w + 0.000001)/2))) | samples: 1500 | label: moving average
plot: alpha/sqrt(1 - 2*(1 - alpha)*cos(w) + (1 - alpha)^2) | samples: 600 | label: smoother
readout: first null of the average, rad = 2*pi/M | digits: 3
readout: smoother's gain at π = alpha/(2 - alpha) | digits: 3
```

::: predict
## Data sampled at 1 kHz carries 50 Hz hum. How many samples should a moving average span to remove the hum completely?

- [ ] 5
- [ ] 10
- [x] 20
- [ ] 50

::: reveal
20: exactly one period of 50 Hz at 1 kHz. Averaging over a whole cycle of a sinusoid gives zero, so the null at $2\pi/M$ (in hertz, $f_s/M$ = 50 Hz) lands right on the hum, and its harmonics at 100, 150 Hz… fall on the other nulls.
:::
:::

::: nameit
## Moving average

$y[n] = \frac{1}{M}\sum_{k=0}^{M-1}x[n-k]$, an FIR filter with

$$\lvert H(e^{j\omega})\rvert = \left\lvert\frac{\sin(M\omega/2)}{M\sin(\omega/2)}\right\rvert$$

Gain 1 at DC, nulls at $\omega = 2\pi k/M$, or $f = kf_s/M$ in hertz. It's the best filter for reducing random noise while keeping a step sharp, and a poor one for separating frequencies: its first side lobe is only about 13 dB down.

## Exponential smoother

$y[n] = (1 - \alpha)\,y[n-1] + \alpha\,x[n]$, with $0 < \alpha \le 1$, the discrete RC low-pass:

$$H(e^{j\omega}) = \frac{\alpha}{1 - (1 - \alpha)e^{-j\omega}}$$

DC gain 1, gain $\alpha/(2 - \alpha)$ at ω = π, and an impulse response $\alpha(1 - \alpha)^n$ that falls by 1/e in $-1/\ln(1 - \alpha)$ samples, about 1/α for small α. One multiply-add and one stored value per sample.

## First difference

$y[n] = x[n] - x[n-1]$ has $\lvert H\rvert = 2\lvert\sin(\omega/2)\rvert$: 0 at DC, 2 at ω = π. It removes offsets and slow drift, and approximates a derivative (divided by the sample period).

## Hertz and radians

A sample rate $f_s$ maps ω to $f = \omega f_s/2\pi$; ω = π is $f_s/2$, the highest frequency the samples can hold.
:::

::: example
## A 20-point moving average at 1 kHz removes 50 Hz. How much does it reduce a 10 Hz signal?

::: solution
1. **Digital frequency.**
   $$\begin{aligned} \omega &= 2\pi \cdot 10/1000 \\ &= 0.0628 \end{aligned}$$
2. **Gain.**
   $$\begin{aligned} \lvert H\rvert &= \left\lvert\frac{\sin(20 \times 0.0628/2)}{20\sin(0.0314)}\right\rvert \\ &= 0.936 \end{aligned}$$
3. **Result.** So the 10 Hz signal keeps 94% of its size while the hum is gone.

**Answer:** it passes 10 Hz with a gain of 0.936, keeping 94% of its size.
:::
:::

::: example
## An exponential smoother uses α = 0.1. Describe it.

::: solution
1. **Gain at DC.** It's 1.
2. **Gain at half the sample rate.**
   $$0.1/1.9 = 0.053$$
   So it cuts the fastest jitter by about 19 times.
3. **Memory.** The impulse response falls by 1/e in
   $$-1/\ln 0.9 = 9.5\ \text{samples}$$

**Answer:** it's a low-pass with gain 1 at DC and 0.053 at half the sample rate, and a memory of about 9.5 samples.
:::
:::

::: example
## A first difference, $y[n] = x[n] - x[n - 1]$, runs at 1 kHz. What is its gain at 10 Hz and at 250 Hz?

::: solution
1. **Gain of a first difference.**
   $$\lvert H\rvert = 2\lvert\sin(\omega/2)\rvert$$
2. **At 10 Hz.** Here ω = 0.0628 and the gain is 0.0628: low frequencies almost vanish.
3. **At 250 Hz.** Here ω = π/2, so the gain is
   $$2\sin(\pi/4) = 1.414$$
4. **What it is.** It's a crude high-pass, and at low frequencies a differentiator: the gain grows in proportion to frequency.

**Answer:** a gain of 0.0628 at 10 Hz and 1.414 at 250 Hz.
:::
:::

::: check
given: fs = 1000 | 8000 | 48000; M = 10 | 20 | 160
answer: fs/M
unit: Hz
tolerance: 0.5%

## An {M}-point moving average runs on data sampled at {fs} Hz. At what frequency is its first null?

::: right
Right. $f_s/M$ = {answer} Hz.
:::

::: misses
- [fs/(2*M)] The null is at ω = 2π/M, which is $f_s/M$ in hertz.
- [any] Not yet. $f = \omega f_s/2\pi$ with ω = 2π/M.
:::
:::

::: check
given: M = 4 | 8 | 16; w = 0.2 | 0.5
answer: abs(sin(M*w/2)/(M*sin(w/2)))
tolerance: 0.5%

## What is the gain of an {M}-point moving average at ω = {w} rad?

::: right
Right. $\lvert\sin(M\omega/2)/(M\sin(\omega/2))\rvert$ = {answer}.
:::

::: misses
- [any] Not yet. Use the moving average's magnitude formula.
:::
:::

::: check
kind: parts
given: alpha = 0.05 | 0.2 | 0.5

## An exponential smoother has α = {alpha}.

::: part
answer: alpha/(2 - alpha)
tolerance: 0.5%

### What is its gain at ω = π?

::: misses
- [alpha] At ω = π the denominator is $1 + (1 - \alpha) = 2 - \alpha$.
- [any] Not yet. $\alpha/(2 - \alpha)$.
:::
:::

::: part
answer: -1/ln(1 - alpha)
tolerance: 0.5%

### In how many samples does its impulse response fall by 1/e?

::: misses
- [1/alpha] That's the small-α approximation; use the exact $-1/\ln(1 - \alpha)$.
- [any] Not yet. Solve $(1 - \alpha)^n = e^{-1}$.
:::
:::
:::

::: check
given: w = 0.1 | 1 | 2.5 | 3.1416
answer: 2*abs(sin(w/2))
tolerance: 0.5%

## What is the gain of the first difference $x[n] - x[n-1]$ at ω = {w} rad?

::: right
Right. $2\lvert\sin(\omega/2)\rvert$ = {answer}.
:::

::: misses
- [2*abs(sin(w))] The half-sample center puts ω/2 in the sine.
- [any] Not yet. $\lvert 1 - e^{-j\omega}\rvert$.
:::
:::

::: check
given: f = 60 | 1000 | 5000; fs = 8000 | 44100
answer: 2*pi*f/fs
unit: rad
tolerance: 0.5%

## At a sample rate of {fs} Hz, what ω corresponds to {f} Hz?

::: right
Right. $2\pi f/f_s$ = {answer} rad per sample.
:::

::: misses
- [f/fs] Multiply by 2π.
- [any] Not yet. $\omega = 2\pi f/f_s$.
:::
:::

::: check
given: fs = 600 | 1200 | 9600; fh = 50 | 60
answer: fs/fh
tolerance: 0

## Data sampled at {fs} Hz carries {fh} Hz hum. How many points should a moving average span to null it exactly?

::: right
Right. One period of the hum: {answer} samples.
:::

::: misses
- [fs/(2*fh)] Half a period cancels nothing; the average needs a whole cycle.
- [any] Not yet. $f_s/f_h$.
:::
:::

::: check
kind: choice

## A pressure sensor's samples have a slowly drifting offset on top of the fast pulses you care about. Which simple filter removes the offset?

- [ ] A moving average
- [ ] An exponential smoother
- [x] The first difference
- [ ] None: offsets can't be filtered

::: misses
- [1] A moving average keeps DC and removes the fast pulses: the opposite of what's wanted.
- [2] It's a low-pass too; it keeps the offset.
- [4] The first difference has zero gain at DC, so a constant offset disappears.
:::
:::

::: check
kind: parts
given: M = 5 | 10 | 20; fs = 1000 | 8000; f = 10 | 30

## An {M}-point moving average runs at {fs} Hz.

::: part
answer: abs(sin(M*pi*f/fs)/(M*sin(pi*f/fs)))
tolerance: 0.5%

### What is its gain at {f} Hz?

::: misses
- [any] $\lvert\sin(M\omega/2)/(M\sin(\omega/2))\rvert$ with $\omega = 2\pi f/f_s$.
:::
:::

::: part
answer: fs/M
unit: Hz
tolerance: 0.5%

### At what lowest frequency is its gain zero?

::: misses
- [any] $f_s/M$: a whole cycle fits in the window.
:::
:::
:::

::: check
kind: parts
given: a = 0.05 | 0.1 | 0.3

## An exponential smoother $y[n] = (1 - \alpha)y[n-1] + \alpha x[n]$ uses α = {a}.

::: part
answer: a/(2 - a)
tolerance: 0.5%

### What is its gain at ω = π?

::: misses
- [any] $\alpha/(1 + (1 - \alpha))$.
:::
:::

::: part
answer: -1/ln(1 - a)
tolerance: 0.5%

### In how many samples does its impulse response fall by 1/e?

::: misses
- [1/a] That's the approximation for small α.
- [any] Solve $(1 - \alpha)^n = 1/e$.
:::
:::
:::

::: explain
## Why does a moving average over exactly one period of a sinusoid remove it completely?

::: model
The average of a sinusoid over a whole number of cycles is zero, because its positive and negative halves cancel exactly. A moving average over M samples averages whatever M consecutive samples are in its window, and if M samples span exactly one cycle, the window always holds a complete cycle no matter where it starts, so the sinusoid contributes nothing to any output. In the frequency response that's the null at $f_s/M$, and the same argument puts nulls at every harmonic, which complete two, three or more whole cycles in the window.
:::
:::

::: practice

::: check
given: fs = 2000 | 10000; M = 25 | 40
answer: fs/M
unit: Hz
tolerance: 0.5%

## First null of an {M}-point average at {fs} Hz?

::: misses
- [any] $f_s/M$.
:::
:::

::: check
given: alpha = 0.05 | 0.1 | 0.2 | 0.25 | 0.3 | 0.5
answer: alpha/(2 - alpha)
tolerance: 0.5%

## Gain at ω = π of a smoother with α = {alpha}?

::: misses
- [any] $\alpha/(2 - \alpha)$.
:::
:::

::: check
given: w = 0.25 | 0.5 | 1 | 1.5 | 2 | 2.5 | 3
answer: 2*abs(sin(w/2))
tolerance: 0.5%

## First-difference gain at ω = {w}?

::: misses
- [any] $2\lvert\sin(\omega/2)\rvert$.
:::
:::
:::
