One bad reading of 400 centimeters in a stream of distance measurements that should say 100 is enough to wreck a 5-sample moving average: the output jumps by about 60 centimeters and stays wrong for five samples. A 5-sample median filter fed the same data doesn’t move at all. That difference, an average that spreads every spike around and a median that throws spikes away, is the whole case for median filtering in hobby sensor projects. A simulated run of 400 readings with a step change and a dozen dropouts shows how large the gap is, and also where the median loses.
Two filters in one paragraph each
Moving average
A moving average replaces each reading with the mean of the last w readings. Gaussian noise, the small random jitter around the true value, shrinks by a factor of about the square root of w. Every reading in the window carries equal weight, so a single wild value pulls the result by its error divided by w.
Median filter
A median filter replaces each reading with the middle value of the last w readings once they are sorted. As long as fewer than half the readings in the window are bad, the middle value comes from the good ones. SciPy’s medfilt function, documented as performing “a median filter on an N-dimensional array”, requires an odd kernel size so a single middle value exists, and zero-pads the edges of the array, a detail that matters at the start of a recording.

The test data
What was simulated
The script built 400 readings of a distance sensor. The true distance is 100 cm for the first 200 samples and then steps to 150 cm. Every reading carries Gaussian noise with a standard deviation of 1 cm. Twelve randomly chosen readings were replaced with either 0 or 400, the kind of value a sensor returns when an echo is missed or the reading times out. The random generator was seeded at 7.
Both filters run causally
Each output uses only the current reading and earlier ones, the way a microcontroller filtering live data would work:
import numpy as np
def moving_average(x, w):
return np.array([np.mean(x[max(0, i-w+1):i+1]) for i in range(len(x))])
def moving_median(x, w):
return np.array([np.median(x[max(0, i-w+1):i+1]) for i in range(len(x))])Results
Spikes
Scored away from the step, from sample 10 onward, skipping samples 200 to 214:
| Filter | Window | Root-mean-square error | Worst single error |
|---|---|---|---|
| Raw readings | n/a | 38.6 cm (whole run) | 300 cm |
| Moving average | 5 | 16.5 cm | 69.6 cm |
| Moving average | 9 | 12.6 cm | 38.7 cm |
| Median | 5 | 0.50 cm | 2.0 cm |
| Median | 9 | 0.35 cm | 1.3 cm |
The moving average never recovers from its job. A 400-cm spike in a 9-sample window still shifts the output by about 33 cm, and it does so for nine samples in a row. The median filter’s worst error anywhere outside the step was 2 cm, which is just the ordinary noise.
Three spikes in five samples
The simulation happened to put spikes at samples 313, 315 and 317, values of 400, 0 and 400. That’s three bad readings inside a single 5-sample window, more than half. The 5-sample median still held at about 149.6 to 149.9 cm through that stretch, because one low spike and two high ones sorted to opposite ends and the middle value came from a good reading. That was luck. Three high spikes in that window would have pushed the median to 400.
The step
| Filter | Window | Samples to settle within 2 cm of the new value |
|---|---|---|
| Moving average | 5 | 4 |
| Moving average | 9 | 8 |
| Median | 5 | 2 |
| Median | 9 | 4 |
A real change in distance passes through the median filter in about half the window, because once more than half the window holds new values, the middle value is a new one. The moving average ramps across the whole window.

Where the median loses
Gaussian noise alone
With no spikes at all, the moving average is the more efficient smoother. Run on 200,000 samples of pure noise with a standard deviation of 1, a 9-sample moving average left a standard deviation of 0.33, close to the theoretical 1/√9 = 0.333. A 9-sample median left 0.41. For well-behaved noise, the average squeezes more out of the same number of samples.
Speed
Sorting costs more than adding. On the same machine, SciPy’s medfilt with a 9-sample kernel took about 3.8 milliseconds on 100,000 samples, against 0.41 milliseconds for a 9-sample average computed by numpy.convolve, roughly nine times slower. For a microcontroller sampling a sensor a few times a second, either is trivial. For long recordings processed offline, the gap can add up.
Edges and zeros
SciPy’s zero-padding at the edges means the first and last few outputs of medfilt are pulled toward zero on a signal that sits far from zero, such as a 100-centimeter distance. The causal version above uses a shrinking window at the start instead. Either way, the first few outputs of any filter deserve less trust than the rest.
Using both together
Median first, then average
The two filters solve different problems, so chaining them is common practice: a short median filter to throw out spikes, followed by a moving average or an exponential average to smooth the remaining jitter. On the simulated data, a 5-sample median followed by a 5-sample average cut the jitter on the flat section from 0.42 cm (median alone) to 0.30 cm, kept the worst error outside the step at 1.3 cm, and settled after the step in 6 samples instead of 2. Spike rejection from the median, extra smoothing from the average, paid for with a few samples of delay.
Choosing a window
- Make the median window at least twice the longest burst of consecutive bad readings plus one. A sensor that sometimes misses two readings in a row needs a window of 5 or more.
- Keep the average window as short as the application’s response time allows. Each extra sample adds delay.
- If spikes always go one direction, such as dropouts to zero, a simple sanity check that discards impossible values can do the median’s job for free.

On a microcontroller
A five-sample median without a sort library
On an Arduino-class board there’s no NumPy, but a 5-sample median needs very little: a small ring buffer for the last five readings and a copy of it sorted with insertion sort, which is fast for tiny arrays.
float buf[5]; int idx = 0;
float median5(float x) {
buf[idx] = x; idx = (idx + 1) % 5;
float s[5];
for (int i = 0; i < 5; i++) { // insertion sort into s
float v = buf[i]; int j = i - 1;
while (j >= 0 && s[j] > v) { s[j + 1] = s[j]; j--; }
s[j + 1] = v;
}
return s[2]; // middle value
}Testing the sketch
Compiled on a desktop with g++ and fed the sequence 100, 101, 400, 99, 100, 0, 100, 101, 400, 400, 400, 100, the function returned 0, 0, 100, 100, 100, 100, 100, 100, 100, 101, 400, 400. The first two outputs show the startup problem: the buffer still holds zeros. The isolated 400 and the isolated 0 vanish completely. The run of three 400s at the end breaks through, exactly as the majority rule predicts, because three bad readings out of five make the middle value a bad one. A sensor that can fail three times in a row needs a window of 7 or more.
Costs on a small chip
Five floats of history take 20 bytes, and sorting five values takes at most ten comparisons. At the few readings per second an ultrasonic sensor typically delivers, the filter’s cost disappears next to the time spent waiting for an echo. The first four outputs use a buffer that still holds startup values, zeros in this sketch, so they should be discarded, or the buffer can be filled with the first reading before filtering begins. A moving average on the same board is even cheaper, a running sum and one division, which is part of why it shows up in so much example code. The cheaper filter is only the better one when the data has no spikes.
Trying it on a real sensor
An inexpensive test bench
Ultrasonic distance modules are a common choice for collecting this kind of data, since a reading depends on catching an echo that soft or angled surfaces can scatter. Log a few minutes of readings at a fixed distance, then move the target, and run both filters on the recording. The size and frequency of outliers decide the median window, and the remaining jitter decides whether an average is worth adding.
- ELEGOO 5PCS HC-SR04 Ultrasonic Module Distance Sensor Kit: five HC-SR04 ultrasonic distance modules listed for 3 to 450 cm, compatible with Arduino boards. See it on Amazon (affiliate link)
As an Amazon Associate I earn from qualifying purchases. A commission may be earned if you buy through this link, at no extra cost to you.
Sources
- SciPy documentation,
scipy.signal.medfilt: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.medfilt.html
