Skip to main content

Moving Average

Easydifficulty

You've probably used this filter already without calling it one: a "7-day average" of case counts, or a stock's 50-day average.

Steady jitter needs averaging; bursts and lag do not forgive it​

Averaging is the natural way to clean up random jitter, but an average over all past readings can never follow a signal that moves. The fix is a sliding window: average only the last N readings, and drop the oldest each time a new one comes in. A bigger window is smoother but slower, and, as the demo will show, one bad reading affects the output for N loops.

The average of a sliding window​

Keep the last N readings and report their average. Next loop, the window slides forward one reading. With N = 4 and readings 10, 12, 11, 13, the output is 46/4=11.546/4 = 11.5. When a 14 arrives, the 10 drops out, and the output becomes 50/4=12.550/4 = 12.5.

x^k=1N∑i=0N−1zk−i\hat{x}_k = \frac{1}{N}\sum_{i=0}^{N-1} z_{k-i}

Here zk−iz_{k-i} runs from this loop's reading back to the oldest one in the window. Every reading inside the window gets the same weight, 1/N1/N, and everything older gets zero. That's the big difference from the low-pass filter, which never completely forgets anything.

data stream (newest on the right) →average these N = 4output

The window holds the most recent N readings; their mean is the output. Next loop the window slides one step forward.

Side by side with the low-pass filter:

Moving averageLow-pass (EMA)
Rememberslast N readings, equallyall readings, fading
StorageN valuesone number
Settingwindow size Nsmoothing α
Best atkilling steady jittercheap real-time smoothing

The clearest way to see the difference is to feed both filters one wild reading and watch what happens afterwards:

Math explorerOne outlier, two memories
samples since the spikeshare of the spike in the outputa single wild spike lands hereforgotten at k = N
MA: spike weight: 1/N = 0.083 for exactly 12 samplesEMA: first hit: α = 0.20, then fadesEMA half-life: 3.1 samples
moving average — equal weights, hard cutoffEMA — fading weights, long soft tailthe outlier

This graph is each filter's impulse response, which is just its weights played out over time. The moving average gives the spike a weight of exactly 1/N1/N for exactly NN loops and then forgets it completely. The low-pass filter usually takes a bigger hit at first (α>1/N\alpha > 1/N for typical settings) and then fades it out gradually. Make NN bigger and the moving average's disturbance gets smaller but lasts longer. You can't make it both small and short.

The live demo runs the moving average on a noisy signal. Raise N to smooth it, then run the step test to see the lag a big window costs.

Live demoSliding-window average
True signalNoisy sensorMoving average
More readings = smoother but laggier.
Window covers ≈ — of data
Warn
The two weaknesses

With a large window, the step test ramps up slowly instead of jumping: that's lag. And a single wild reading shifts the average for N loops. No averaging filter, this one or the low-pass or even a Kalman filter, gets rid of outliers by itself. For that, check each reading before it goes in and throw out ones that are physically impossible, like a distance that changed by more than the robot could have moved in one loop.

A fixed-cost ring buffer​

On the robot, store the window in a ring buffer and keep a running sum, so each update costs the same no matter how big N is. The tradeoff against the low-pass filter is storing N values instead of one.

FTCMoving average in constant time
private final double[] buffer = new double[N];
private int index;
private int count;
private double sum;

double update(double reading) {
sum -= buffer[index]; // drop the sample that is now N loops old
buffer[index] = reading;
sum += reading;

index = (index + 1) % buffer.length;
count = Math.min(count + 1, buffer.length);

return sum / count; // count, not N, until the window fills
}
ExerciseTrace the ring buffer

The slot you're about to overwrite always holds the reading from exactly NN loops ago, so one subtraction and one addition keep the sum correct. Run N=4N = 4 with readings 1, 2, 3, 4, 5, 6 and write down buffer, index, sum, and the output at each step. Then: what would loop 2 output if you divided by N instead of count?

Show solution

The outputs are 1, 1.5, 2, 2.5, 3.5, 4.5. On loop 5 the 1 leaves and the 5 comes in, so the sum goes from 10 to 14 with one subtraction and one addition. Dividing by N on loop 2 gives 0.75 instead of 1.5, because the two unused slots still hold zeros that were never measurements. count fixes that until the window fills up.

ExerciseOne wild outlier

This filter forgets a reading completely after NN loops, while the low-pass filter never quite does. Feed both one wild spike and describe how each recovers. Which would you rather have on a distance sensor that sometimes reads through a gap in the field wall?

There's a third problem with equal weights, and it has nothing to do with noise. On a signal that curves, the average of a window sits below the peak even with a perfect sensor. The Savitzky-Golay filter keeps the window but fits a curve to it, for the same cost per loop.

Sources & references
  • WPILib: Filters - robotics filtering reference for moving averages and related filters.
  • Tyler Veness, Controls Engineering in FRC - practical controls background for measurement noise and estimator design.
  • Low-Pass Filter - the companion Control Lab lesson comparing exponential smoothing against fixed-window averaging.