A noisy reading
A sensor sends one reading x[n] per tick. Inside is a slow wave, but a fast wobble rides on top: +3, −1, −1, −1, repeating every 4 samples. We want the slow wave back.
The averaging machine
Each new sample enters on the left, and every stored sample moves one place right. The oldest falls off the end. So the line always holds the last four readings: x[n], x[n−1], x[n−2], x[n−3].
Each stored sample is multiplied by its weight, 1/4, and the adder sums the four products: y[3] = (20.82 + 20.24 + 19.63 + 23.00) / 4 = 20.92. That is the average of the last four readings.
The window slides one sample each tick and gives a new average. Any four samples in a row hold one whole wobble, +3 − 1 − 1 − 1 = 0, so the wobble cancels exactly. A smooth curve comes out.
Finite impulse response
Now feed in one 1 and then only zeros: an impulse. The 1 walks through the four cells, so the output is 1/4, 1/4, 1/4, 1/4 and then 0 for ever. This output is the impulse response h[n].
The impulse response stops after 4 samples: it is finite. A filter like this is an FIR filter. Every FIR filter computes y[n] = Σ h[k]·x[n−k], a convolution. The moving average is the simplest: all M weights equal 1/M.
What it does to frequencies
Compare y[n] with the clean slow wave: same shape, 1.5% smaller and 1.5 samples late. A 4-point average describes the middle of its window, so it lags by (M − 1)/2 = (4 − 1)/2 = 1.5 samples.
Feed in a sine of frequency ω and a sine of the same ω comes out, scaled by the gain |H(ω)| = |sin(2ω) / (4·sin(ω/2))|. Slow sines pass with gain near 1; fast ones shrink. It is a low-pass filter.
The gain is exactly 0 at ω = π/2 and π, a quarter and half of the sample rate. The wobble lives exactly there, so it vanishes. In between the gain climbs back to 0.27: a cheap but leaky low-pass.
Code and design
With numpy, np.ones(4)/4 makes the four weights and np.convolve slides them along x. Mode "valid" keeps only outputs whose window holds four real samples, so y[0] here is y[3] above: 20.92.
A longer average smooths more but lags more: (M − 1)/2 samples. On random noise, averaging M readings shrinks the noise by √M, so M = 4 halves it. For sharper filters, see FIR design by windowing.
The working
# step 1/11 · noisy
x[n] = s[n] + w[n], n = 0, 1, 2 ... 39
s[n] = 20 + 4·sin(2π·n/40) slow wave
w[n] = 2·cos(π·n/2) + (−1)ⁿ wobble
= +3, −1, −1, −1, +3, −1 ...
x[0..5] = 23.00, 19.63, 20.24, 20.82, 25.35, 21.83
The slow wave and the wobble are a chosen example: the wobble repeats every 4 samples and adds to zero over any 4 in a row, so a 4-point average removes it exactly. Every number in the figure is computed from this model. The filter starts from rest: before n = 0 the delay line holds zeros, so y[0], y[1] and y[2] are warm-up values and are not plotted. numpy's "valid" mode drops them too.