A451 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

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?

Name it

The moving average

y[n]=1N∑k=0N−1x[n−k]
y = np.convolve(x, np.ones(N) / N, mode="valid")    # N - 1 fewer samples

Its gain at frequency f is

|H(f)|=|sin⁡(πfN/fs)Nsin⁡(πf/fs)|

which is 1 at DC, falls with frequency, and is exactly zero at f=kfs/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]+α(x[n]−y[n−1])

Each new sample pulls the estimate a fraction α 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

τ=−Δtln⁡(1−α)≈Δtα

with corner frequency 1/(2πτ). 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

ProblemFilter
Hum or ripple at a known frequencyMoving average one cycle long
Broadband noise, little memory availableExponential smoothing
Occasional wild readingsMedian of 3 or 5
A precise frequency responseA designed FIR or IIR filter (S7)

Worked example

A 5 Hz signal with 60 Hz hum, x=sin⁡(2π⋅5t)+0.5sin⁡(2π⋅60t), is sampled at 600 Hz and passed through a 10-point moving average. What comes out?

Show the solution
  1. Filter the signal and evaluate the response. H is 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
  1. The hum. It's gone, since 60 Hz is fs/N, a null.
  2. The 5 Hz signal. It comes through with gain 0.989, delayed by N−12=4.5samples=7.5ms
  3. The output. It matches 0.989sin⁡(2π⋅5(t−7.5 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.

Worked example

Firmware smooths a sensor sampled every 1 ms with α = 0.1. What's its time constant and corner frequency?

Show the solution
  1. The time constant. τ=−1msln⁡0.9=9.49ms a little less than the Δt/α = 10 ms estimate.
  2. The corner frequency. fc=12π×9.49ms=16.8Hz
  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.

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
  1. 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
  1. The average. It spreads the 9 V glitch over three outputs, each about 3.6 V, worse than leaving it alone.
  2. 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 |H(f)| 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 −Δt/ln⁡(1−α) 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?

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.