---
title: Filtering signals in code
heading: Moving averages, smoothing and medians, with what each one costs
eyebrow: A4 · Lesson 51 · Filtering signals in code
xp: 40
---

::: hook
A temperature sensor's readings wander by a few hundredths of a degree, a strain gauge picks up 60 Hz hum from the mains, and every so often an ADC reading comes back wildly wrong from a glitch. You can't fix those in hardware after the fact, but a few lines of code can: average neighboring samples, smooth with a running estimate, or take the middle of a few readings. Each choice removes something, keeps something, and delays everything a little. Lesson 50's spectrum is how you see which.
:::

::: predict
## A signal sampled at 600 Hz carries 60 Hz hum. You replace each sample by the average of the last 10. What happens to the hum?

- [x] It disappears completely
- [ ] It's cut to a tenth of its size
- [ ] It's cut in half
- [ ] Nothing: averaging only removes random noise

::: reveal
It vanishes. Ten samples at 600 Hz span exactly 1/60 s, one full cycle of the hum, and a sine averaged over a whole cycle is zero, wherever the window starts. A moving average of $N$ samples has a **null** at $f_s/N$ and at every multiple of it, so choosing $N$ to make the window one hum cycle long removes the hum and its harmonics exactly.
:::
:::

::: nameit
## The moving average

$$y[n] = \frac{1}{N}\sum_{k=0}^{N-1} x[n - k]$$

```python
y = np.convolve(x, np.ones(N) / N, mode="valid")    # N - 1 fewer samples
```

Its gain at frequency $f$ is

$$|H(f)| = \left|\frac{\sin(\pi f N/f_s)}{N\sin(\pi f/f_s)}\right|$$

which is 1 at DC, falls with frequency, and is exactly zero at $f = kf_s/N$. A symmetric window like this delays the signal by $(N - 1)/2$ samples. `mode="valid"` keeps only the outputs whose window lies entirely inside the data; `"same"` keeps the length but makes up the ends from partial windows.

## Exponential smoothing

$$y[n] = y[n-1] + \alpha\,(x[n] - y[n-1])$$

Each new sample pulls the estimate a fraction $\alpha$ of the way toward itself. It needs one stored number instead of $N$, which is why firmware uses it. It's the digital RC low-pass: a step reaches 63% after a time constant

$$\tau = \frac{-\Delta t}{\ln(1 - \alpha)} \approx \frac{\Delta t}{\alpha}$$

with corner frequency $1/(2\pi\tau)$. Unlike the moving average it has no nulls, and its memory never quite ends: old samples fade but never drop out.

## The median filter

Replace each sample by the median of its neighbors. A single wild sample is never the median of three, so it disappears, while steps and edges pass through sharp. Averaging would smear the glitch across its neighbors instead. The median is a **nonlinear** filter: it has no frequency response, and no spectrum explains it.

## Choosing

| Problem | Filter |
|---|---|
| Hum or ripple at a known frequency | Moving average one cycle long |
| Broadband noise, little memory available | Exponential smoothing |
| Occasional wild readings | Median of 3 or 5 |
| A precise frequency response | A designed FIR or IIR filter (S7) |
:::

::: example
## A 5 Hz signal with 60 Hz hum, $x = \sin(2\pi \cdot 5t) + 0.5\sin(2\pi \cdot 60t)$, is sampled at 600 Hz and passed through a 10-point moving average. What comes out?

::: solution
1. **Filter the signal and evaluate the response.** `H` is the moving average's gain at a frequency.

```python
fs, N = 600, 10
t = np.arange(600) / fs
x = np.sin(2 * np.pi * 5 * t) + 0.5 * np.sin(2 * np.pi * 60 * t)
y = np.convolve(x, np.ones(N) / N, mode="valid")
H = lambda f: abs(np.sin(np.pi * f * N / fs) / (N * np.sin(np.pi * f / fs)))
print(H(5), H(60))    # 0.98873, 0.0
```

2. **The hum.** It's gone, since 60 Hz is $f_s/N$, a null.
3. **The 5 Hz signal.** It comes through with gain 0.989, delayed by
   $$\begin{aligned} \frac{N - 1}{2} &= 4.5\ \text{samples} \\ &= 7.5\ \text{ms} \end{aligned}$$
4. **The output.** It matches $0.989\sin(2\pi \cdot 5(t - 7.5\text{ ms}))$ to rounding error: a moving average changes a sine's size and delay, never its shape or frequency.

**Answer:** the 5 Hz sine alone, scaled by 0.989 and delayed 7.5 ms; the 60 Hz hum is gone.
:::
:::

::: example
## Firmware smooths a sensor sampled every 1 ms with $\alpha$ = 0.1. What's its time constant and corner frequency?

::: solution
1. **The time constant.**
   $$\begin{aligned} \tau &= \frac{-1\ \text{ms}}{\ln 0.9} \\ &= 9.49\ \text{ms} \end{aligned}$$
   a little less than the $\Delta t/\alpha$ = 10 ms estimate.
2. **The corner frequency.**
   $$\begin{aligned} f_c &= \frac{1}{2\pi \times 9.49\ \text{ms}} \\ &= 16.8\ \text{Hz} \end{aligned}$$
3. **The step response.** A step input reaches 63% after about 9.5 samples and 99% after about 44.
4. **The cost.** It costs one multiply and one add per sample and one stored number.

**Answer:** a time constant of 9.49 ms and a corner frequency of 16.8 Hz.
:::
:::

::: example
## Readings of 1.0, 1.1, 0.9, 9.0, 1.0, 1.05, 0.95 V include one glitch. Compare a 3-point moving average with a 3-point median.

::: solution
1. **Filter the readings both ways.** A 3-point moving average with `np.convolve`, and a 3-point median over each window.

```python
v = [1.0, 1.1, 0.9, 9.0, 1.0, 1.05, 0.95]
ma = np.convolve(v, np.ones(3) / 3, mode="valid")   # 1.0, 3.67, 3.63, 3.68, 1.0
md = [float(np.median(v[i:i + 3])) for i in range(len(v) - 2)]   # 1.0, 1.1, 1.0, 1.05, 1.0
```

2. **The average.** It spreads the 9 V glitch over three outputs, each about 3.6 V, worse than leaving it alone.
3. **The median.** It never lets it through: in every window holding the 9.0 the middle value is a normal reading.

**Answer:** the moving average smears the glitch into three readings near 3.6 V, while the median removes it.
:::
:::

::: check
kind: python
given: N = 4 | 8 | 16; k = 1..5 int

## Write `moving_average(x, N)` without `np.convolve`, using a cumulative sum: with `c = np.cumsum(np.insert(x, 0, 0))`, the sum of `x[i:i + N]` is `c[i + N] - c[i]`. Return the `len(x) - N + 1` window averages. Set `y = moving_average(x, N)` for the starter's samples and `N` = {N}.

```python starter
import numpy as np
x = np.random.default_rng(k).normal(0, 1, 200)

def moving_average(x, N):
    return x[N - 1:] / N

y = moving_average(x, N)
print(y[:5])
```

```python solution
import numpy as np
x = np.random.default_rng(k).normal(0, 1, 200)

def moving_average(x, N):
    c = np.cumsum(np.insert(x, 0, 0))
    return (c[N:] - c[:-N]) / N

y = moving_average(x, N)
print(y[:5])
```

```python tests
import numpy as np
xx = np.random.default_rng(k).normal(0, 1, 200)
ref = np.convolve(xx, np.ones(N) / N, mode="valid")
assert np.shape(y) == ref.shape and np.allclose(y, ref, atol=1e-12), "The averages should match np.convolve(x, np.ones(N)/N, 'valid'): (c[N:] - c[:-N]) / N."
```

::: right
Right. The cumulative sum turns each window's sum into one subtraction, so the cost doesn't grow with $N$. That's how fast moving averages are built in practice.
:::
:::

::: check
kind: python
given: N = 5 | 10 | 20; f = 3 | 17 | 35

## Sample a 1 V sine at `f` = {f} Hz for 2 s at `fs` = 1000 Hz, pass it through an `N`-point moving average (`N` = {N}, mode `"valid"`), and set `measured` to the output's amplitude, half its peak-to-peak over the last second. Set `formula` to $|H(f)|$ from the lesson.

```python starter
import numpy as np
fs = 1000
t = np.arange(2 * fs) / fs
x = np.sin(2 * np.pi * f * t)
measured = 1
formula = 1
print(measured, formula)
```

```python solution
import numpy as np
fs = 1000
t = np.arange(2 * fs) / fs
x = np.sin(2 * np.pi * f * t)
y = np.convolve(x, np.ones(N) / N, mode="valid")
last = y[-fs:]
measured = (last.max() - last.min()) / 2
formula = abs(np.sin(np.pi * f * N / fs) / (N * np.sin(np.pi * f / fs)))
print(measured, formula)
```

```python tests
import numpy as np
F = abs(np.sin(np.pi * f * N / 1000) / (N * np.sin(np.pi * f / 1000)))
assert abs(formula - F) < 1e-12, "formula is |sin(π f N/fs) / (N sin(π f/fs))|."
assert abs(measured - F) < 2e-3, f"The measured gain should be close to {F:.4f}."
```

::: right
Right. The measured amplitude agrees with the formula to within the sampling of the peak. Filtering a known sine and measuring what comes out is the bench method for any filter whose formula you don't have.
:::
:::

::: check
kind: python
given: a = 0.02 | 0.05 | 0.1 | 0.25

## Write `smooth(x, alpha)` returning the exponentially smoothed sequence, starting from `y = x[0]`. Feed it a unit step (100 zeros then 400 ones) sampled every 1 ms with `alpha` = {a}. Set `n63` to the number of samples after the step until the output first reaches 0.632, and `tau_ms` to the formula $-\Delta t/\ln(1 - \alpha)$ in ms.

```python starter
import math
def smooth(x, alpha):
    return list(x)

x = [0.0] * 100 + [1.0] * 400
y = smooth(x, a)
n63 = 0
tau_ms = 1 / a
print(n63, tau_ms)
```

```python solution
import math
def smooth(x, alpha):
    y, out = x[0], []
    for v in x:
        y = y + alpha * (v - y)
        out.append(y)
    return out

x = [0.0] * 100 + [1.0] * 400
y = smooth(x, a)
n63 = next(i for i in range(100, 500) if y[i] >= 0.632) - 99
tau_ms = -1 / math.log(1 - a)
print(n63, tau_ms)
```

```python tests
import math
yy, out = 0.0, []
for v in [0.0] * 100 + [1.0] * 400:
    yy += a * (v - yy); out.append(yy)
assert all(abs(p - q) < 1e-12 for p, q in zip(y, out)), "Each output is y + alpha*(x - y), starting from x[0]."
want = next(i for i in range(100, 500) if out[i] >= 0.632) - 99
assert n63 == want, f"The output first reaches 0.632 on step {want} after the input steps."
assert abs(tau_ms - (-1 / math.log(1 - a))) < 1e-12 and abs(n63 - tau_ms) <= 1, "tau_ms is -Δt/ln(1 - alpha), and n63 should be within a sample of it."
```

::: right
Right. After $n$ samples the step response is $1 - (1 - \alpha)^n$, so it crosses 63% at $n \approx -1/\ln(1 - \alpha)$ samples: the same time constant as an RC filter, counted in samples.
:::
:::

::: check
kind: python
given: k = 1..5 int; w = 3 | 5

## Write `median_filter(x, w)` returning the median of each window of `w` = {w} samples (a list `w - 1` shorter than `x`), and use it on the starter's readings, which include some single-sample glitches. Set `clean` to the result and `worst` to its largest distance from 1.0.

```python starter
import numpy as np
rng = np.random.default_rng(k)
x = 1 + rng.normal(0, 0.01, 300)
x[rng.choice(np.arange(10, 290, 12), 8, replace=False)] = rng.choice([-5.0, 9.0], 8)

def median_filter(x, w):
    return list(np.convolve(x, np.ones(w) / w, mode="valid"))

clean = median_filter(x, w)
worst = max(abs(v - 1) for v in clean)
print(worst)
```

```python solution
import numpy as np
rng = np.random.default_rng(k)
x = 1 + rng.normal(0, 0.01, 300)
x[rng.choice(np.arange(10, 290, 12), 8, replace=False)] = rng.choice([-5.0, 9.0], 8)

def median_filter(x, w):
    return [float(np.median(x[i:i + w])) for i in range(len(x) - w + 1)]

clean = median_filter(x, w)
worst = max(abs(v - 1) for v in clean)
print(worst)
```

```python tests
import numpy as np
want = [float(np.median(x[i:i + w])) for i in range(len(x) - w + 1)]
assert len(clean) == len(want) and np.allclose(clean, want), "Each output is the median of x[i:i + w]."
assert worst < 0.05, f"The glitches should be gone: the worst output is {worst:.3f} from 1.0."
```

::: right
Right. A glitch can't be the middle value of a window unless glitches make up half of it, so isolated ones vanish without touching the good readings. An average of the same window would let each glitch through at a third or a fifth of its size.
:::
:::

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

## A signal is sampled at {fs} Hz and carries {fh} Hz hum. How many samples long must a moving average be for its first null to fall on the hum?

::: right
Right. The first null is at $f_s/N$, so $N = \given{fs}/\given{fh}$ = {answer} samples, one cycle of the hum. That also nulls every harmonic of the hum.
:::

::: misses
- [fs/fh/2] That's half a cycle. The window has to span a whole cycle for the sine to average to zero.
- [fh/fs] That's upside down: one cycle lasts $1/\given{fh}$ s, which is $\given{fs}/\given{fh}$ samples.
- [any] Not yet. Count the samples in one cycle of the hum.
:::
:::

::: check
given: a = 0.01 | 0.05 | 0.2; dt = 0.1 | 1 | 10
answer: -dt*1e-3/ln(1 - a)
unit: s
tolerance: 0.5%

## An exponential smoother runs every {dt} ms with $\alpha$ = {a}. What's its time constant?

::: right
Right. $\tau = -\Delta t/\ln(1 - \alpha)$ = {answer}, slightly less than $\Delta t/\alpha$.
:::

::: misses
- [dt*1e-3/a] That's the small-α approximation. The exact time constant is $-\Delta t/\ln(1 - \alpha)$, a little shorter.
- [dt*1e-3*a] That's upside down. A small α means a slow filter, so the time constant grows as α shrinks.
- [-dt/ln(1 - a)] That's the number of milliseconds written as seconds. Convert {dt} ms to seconds.
- [any] Not yet. After $n$ samples the step response is $1 - (1 - \alpha)^n$; set $(1 - \alpha)^n = e^{-n\Delta t/\tau}$ and solve for $\tau$.
:::
:::

::: check
kind: choice

## A 21-point moving average, with each output placed at the end of its window, follows its input with what delay?

- [x] 10 samples
- [ ] 21 samples
- [ ] 1 sample
- [ ] No delay

::: right
Right. A symmetric window's output represents its middle, $(N - 1)/2$ = 10 samples back. Plotting the output against the window's center time instead lines it up with the input.
:::

::: misses
- [2] The window's middle, not its oldest sample, is what the average represents: $(N - 1)/2$.
- [3] One sample is the delay of a 3-point average. A 21-point one is centered 10 samples back.
- [4] Any filter that only uses past samples delays the signal. Here it's $(N - 1)/2$ samples.
:::
:::

::: explain
## Why is a median filter better than a moving average for removing occasional glitches, but no use for removing 60 Hz hum?

::: model
A glitch is one sample far from its neighbors. The median of a window holding it is one of the normal samples, so the glitch is dropped without affecting anything else, while an average includes it at $1/N$ of its size, spreading it over $N$ outputs. Hum is a smooth wave present in every sample, so there's no outlier for the median to reject: the median of a few samples of a sine is just one of them, and the hum passes through. Removing hum needs a linear filter that cancels a frequency, like a moving average exactly one cycle long.
:::
:::

::: practice

::: check
kind: python
given: N = 3 | 4 | 6

## Set `y` to the `N`-point moving average (`N` = {N}) of `[2, 4, 6, 8, 10, 12, 14, 16]` with `np.convolve` in `"valid"` mode.

```python starter
import numpy as np
y = np.array([2, 4, 6, 8, 10, 12, 14, 16])
print(y)
```

```python solution
import numpy as np
y = np.convolve([2, 4, 6, 8, 10, 12, 14, 16], np.ones(N) / N, mode="valid")
print(y)
```

```python tests
import numpy as np
assert np.allclose(y, np.convolve([2, 4, 6, 8, 10, 12, 14, 16], np.ones(N) / N, mode="valid")), "Use np.ones(N)/N as the filter and mode='valid'."
```
:::

::: check
kind: python
given: a = 0.1 | 0.3 | 0.5

## Starting from `y = 0`, apply exponential smoothing with `alpha` = {a} to five samples of 1.0 and set `y` to the final output.

```python starter
y = 0
print(y)
```

```python solution
y = 0.0
for _ in range(5):
    y += a * (1.0 - y)
print(y)
```

```python tests
assert abs(y - (1 - (1 - a)**5)) < 1e-12, "Five steps of y += alpha*(1 - y) give 1 - (1 - alpha)**5."
```
:::
:::
