A4 · Lesson 51 · Filtering signals in code
Moving averages, smoothing and medians, with what each one costs
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?
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 samples has a null at and at every multiple of it, so choosing to make the window one hum cycle long removes the hum and its harmonics exactly.
Name it
The moving average
y = np.convolve(x, np.ones(N) / N, mode="valid") # N - 1 fewer samples
Its gain at frequency is
which is 1 at DC, falls with frequency, and is exactly zero at . A symmetric window like this delays the signal by 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
Each new sample pulls the estimate a fraction of the way toward itself. It needs one stored number instead of , which is why firmware uses it. It's the digital RC low-pass: a step reaches 63% after a time constant
with corner frequency . 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) |
Worked example
A 5 Hz signal with 60 Hz hum, , is sampled at 600 Hz and passed through a 10-point moving average. What comes out?
Show the solution
- Filter the signal and evaluate the response.
His the moving average's gain at a frequency.
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
- The hum. It's gone, since 60 Hz is , a null.
- The 5 Hz signal. It comes through with gain 0.989, delayed by
- The output. It matches 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.
Worked example
Firmware smooths a sensor sampled every 1 ms with = 0.1. What's its time constant and corner frequency?
Show the solution
- The time constant. a little less than the = 10 ms estimate.
- The corner frequency.
- The step response. A step input reaches 63% after about 9.5 samples and 99% after about 44.
- 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.
Worked 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.
Show the solution
- Filter the readings both ways. A 3-point moving average with
np.convolve, and a 3-point median over each window.
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
- The average. It spreads the 9 V glitch over three outputs, each about 3.6 V, worse than leaving it alone.
- 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
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 = 8.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Sample a 1 V sine at f = 3 Hz for 2 s at fs = 1000 Hz, pass it through an N-point moving average (N = 10, mode "valid"), and set measured to the output's amplitude, half its peak-to-peak over the last second. Set formula to from the lesson.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
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 = 0.05. Set n63 to the number of samples after the step until the output first reaches 0.632, and tau_ms to the formula in ms.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write median_filter(x, w) returning the median of each window of w = 3 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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
A signal is sampled at 1200 Hz and carries 50 Hz hum. How many samples long must a moving average be for its first null to fall on the hum?
Check
An exponential smoother runs every 0.1 ms with = 0.05. What's its time constant?
Write units the way you normally would: 1.5 s and 1500 ms are the same answer.
Check
A 21-point moving average, with each output placed at the end of its window, follows its input with what delay?
Explain why
Why is a median filter better than a moving average for removing occasional glitches, but no use for removing 60 Hz hum?
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 of its size, spreading it over 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
Keep practicing
8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.