December 5, 2026

A Simple 1D Kalman Filter in Python: Tested Against a Moving Average on Noisy Sensor Data

A temperature probe in a glass of water wired to a microcontroller

Ten minutes of fake temperature readings, a slow warm-up in the middle, and noise of half a degree on every sample: that is enough to show what a Kalman filter actually does and where its reputation outruns it. On this data, a one-dimensional Kalman filter tuned well cut the error from 0.49 °C to 0.10 °C. A plain 20-sample moving average got to 0.11 °C. And once the Kalman filter settles down, its update equation turns out to be the same as an exponential moving average, which is the most useful thing to know before reaching for one. The full script is below, along with the numbers it printed and the version that does beat the simple averages.

Video: MATLAB on YouTube

Where the filter comes from

A recursive least-squares estimate

The Kalman filter dates to a 1960 paper by Rudolf E. Kalman. Greg Welch and Gary Bishop’s widely used tutorial from the University of North Carolina, An Introduction to the Kalman Filter (technical report TR 95-041), describes it as a set of mathematical equations that provides “an efficient computational (recursive) solution of the least-squares method.” Recursive is the important word. The filter never stores the past readings. It keeps one estimate and one number describing how uncertain that estimate is, and updates both each time a new reading arrives.

Predict, then correct

The Welch and Bishop report splits each step in two: a time update that predicts the next state and its uncertainty, and a measurement update that blends the prediction with the new reading. For a single value that isn’t expected to change much, such as a room temperature, the whole filter fits in six lines.

Close-up photo of monitor displaying graph

The filter in six lines

The code

def kalman_1d(readings, Q, R, x0, P0=1.0):
    x, P, out = x0, P0, []
    for z in readings:
        P = P + Q                 # predict: uncertainty grows
        K = P / (P + R)           # gain: how much to trust the new reading
        x = x + K * (z - x)       # correct: move toward the reading
        P = (1 - K) * P           # uncertainty shrinks after the correction
        out.append(x)
    return out

What Q and R mean

R is the measurement noise variance: how much a single reading scatters around the truth. Q is the process noise variance: how much the real value is expected to wander between readings. R usually comes from the sensor, by logging readings of something held steady and computing their variance. Q is the tuning knob, and almost every disappointing Kalman filter on a hobby project comes down to a guessed Q.

The test data

What was simulated

The script built 600 readings, one per second. The true temperature holds at 20.00 °C for five minutes, rises at 0.01 °C per second for 150 seconds to about 21.49 °C, then holds again. Each reading adds Gaussian noise with a standard deviation of 0.5 °C, so R = 0.25. The random generator was seeded at 42 so the run can be repeated exactly.

The yardstick

Every filter was scored by root-mean-square error against the true value, over the whole run and over two sections: the flat stretch from second 50 to 300, and the ramp from 310 to 450. Raw readings scored 0.49 °C overall.

Sextant, watch, dividers, and ruler on map

Results

Kalman filter with different Q

Q Overall error Flat section Ramp section Lag at the end of the ramp Steady-state gain K
0.000001 0.620 °C 0.023 °C 0.757 °C 1.21 °C 0.002
0.0001 0.204 °C 0.036 °C 0.367 °C 0.50 °C 0.020
0.001 0.102 °C 0.070 °C 0.165 °C 0.16 °C 0.061
0.01 0.151 °C 0.141 °C 0.169 °C −0.06 °C 0.181

What the table says

A tiny Q makes the filter confident the temperature never changes. It produces a beautifully smooth line on the flat section, 0.023 °C of error, and then falls 1.2 degrees behind when the room actually warms. A large Q trusts each reading more, follows the ramp closely, and lets more noise through. Q = 0.001 was the best compromise on this data. The trade between smoothness and lag never goes away; tuning only chooses where to sit on it.

Against simple averages

Method Overall Flat Ramp
Raw readings 0.487 °C 0.480 °C 0.493 °C
20-sample moving average 0.106 °C 0.088 °C 0.139 °C
Exponential moving average, α = 0.0613 0.101 °C not split not split
Kalman 1D, Q = 0.001 0.102 °C 0.070 °C 0.165 °C
Kalman with a rate state, q = 0.000001 0.104 °C 0.086 °C 0.086 °C

Why it matched an exponential average

The gain stops changing

In this one-dimensional filter, Q and R are fixed, so the gain K settles to a constant after a few dozen readings. Solving the update equations for their steady state gives K = 0.0613 for Q = 0.001 and R = 0.25, the same number the simulation printed. From then on, the correction line reads x = x + 0.0613 × (z − x). That is exactly an exponential moving average with a smoothing factor of 0.0613. Running a plain exponential average with that factor gave an overall error of 0.101 °C, matching the Kalman filter to within a thousandth of a degree.

So why use it at all

Three reasons survive. The filter picks its own gain from Q and R, which are physical quantities that can be measured or reasoned about, instead of a smoothing factor picked by eye. It starts fast: the gain is large while P is large, so it locks onto the first readings in seconds instead of crawling up from zero. And it extends to cases the averages can’t handle, such as readings that arrive at irregular intervals, sensors with different noise levels and states with more than one variable.

Gaps in the data

The averages also have no good answer for missing readings. A sensor on a flaky wireless link might drop out for a minute, and a moving average simply resumes as if nothing happened. The Kalman filter handles it through the predict step: run P = P + Q once per elapsed second, or equivalently add Q multiplied by the gap length. Uncertainty grows while nothing is measured, so the first reading after a gap gets more weight. With Q = 0.001 and R = 0.25, the settled filter gives a new reading a weight of 0.061 after a normal one-second step. After a 10-second gap, the weight rises to 0.092. After 60 seconds it is 0.232, and after five minutes of silence it is 0.558, meaning the filter jumps more than halfway to the first fresh reading. That is the right behavior: after five minutes, the old estimate has had plenty of time to go stale, and the filter knows it.

Three clear drinking glass on table

Adding a rate makes it better

A two-state model

The last row of the comparison table tracks two numbers: the temperature and its rate of change. The prediction step moves the temperature forward by the rate each second, so during a steady warm-up the filter expects the next reading to be higher and stops lagging. With a small process noise of q = 0.000001 on the rate, the ramp error fell to 0.086 °C, about half that of the one-state filter and well below the 20-sample moving average’s 0.139 °C.

The price

When the warm-up stopped abruptly at second 450, the two-state filter kept predicting a rise for a while and overshot by as much as 0.235 °C before settling. A real heating system rarely switches off that cleanly, but the effect is worth knowing: a model that predicts motion will predict it past the moment it ends. The one-state filter never overshoots, because it never predicts anything but “same as before.”

Using it on a real sensor

Log a few hundred readings of something whose temperature isn’t changing, such as a probe in a glass of water that has sat for an hour. The variance of those readings is R. Start with Q at about R divided by a few hundred and adjust while watching how quickly the output follows a real change, such as moving the probe into a warmer glass. A waterproof digital probe on a microcontroller is an easy way to collect the data.

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

  • Greg Welch and Gary Bishop, “An Introduction to the Kalman Filter,” University of North Carolina at Chapel Hill, TR 95-041 (updated April 5, 2004): https://techreports.cs.unc.edu/papers/95-041.pdf
  • Welch and Bishop tutorial, copy hosted by the University of Edinburgh’s CVonline: https://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/WELCH/kalman.html

920 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *