Each tick, the filter predicts where a drone should be, then blends in a noisy reading by trust. Predict 110 m with variance 13, read 115 m with variance 9, and the answer is 112.95 m with variance 5.32: tighter than both.
Pick a tracker and drag the sensor noise. Watch which one follows the drone without lag. Then we build the filter piece by piece, from the guess and its doubt to tuning and debugging.
You need a weighted average by variance (Lesson 3) and a little Python. We build the rest from zero.
Lesson 5 of 22 in Sensor Fusion: Classical to Modern. The filter is from R. E. Kalman (1960). Before: The Recursive Bayes Filter. Next: Complementary Filters and AHRS.
Illustrative toy: the drone swings 30 m each way over 90 s, one reading a second. The moving average uses the last 7 readings. The Kalman filter uses a constant-velocity model. Error is the root mean square from second 10 to second 120.
Chapter 0
See why a filter beats a moving average, and how pooled readings beat the sensor
You track a delivery drone with one GPS-like receiver. Every second it gives a position, true to about 3 m. The raw readings tremble around the true path. Send them to the autopilot and the drone twitches.
But the drone has momentum. If it was at 100 m and moving at 10 m/s, it is near 110 m one second later. A motion model is a rule for how the state changes between readings. It lets you predict before the next reading arrives. The prediction is smooth but slowly wrong. The reading is noisy but tied to reality.
The Kalman filter fuses the two, every tick. It is the precision-weighted average of Lesson 3, run over time. One source is the prediction. The other is the reading.
A moving average of the last N readings cuts the jitter, but it reports where the drone was. A 5-reading window has its centre two seconds back. At a steady 10 m/s it lags by 20 m. In the hero, pick Moving average: it trails every turn. The filter carries velocity forward, so it does not lag.
Park the drone. Each reading has an error of 3 m. Fuse N independent readings and their precisions add, so the error shrinks with the square root of N.
Warm dots are readings of a drone parked at 50 m. The teal band is the pooled estimate, plus or minus one error. Drag N.
Illustrative: each reading has an error of 3 m (one standard deviation), independent of the others.
| Readings fused, N | Error, 3 m divided by the square root of N | Compared with one reading |
|---|---|---|
| 1 | 3.00 m | the raw sensor |
| 4 | 1.50 m | two times sharper |
| 16 | 0.75 m | four times sharper |
| 100 | 0.30 m | ten times sharper |
A moving drone is harder. Each prediction adds fresh doubt, so the error stops at a floor. The rest of the lesson finds that floor.
The failure: a smoother with no model. Symptom: the track trails every turn. Measure: plot the estimate minus the truth against speed; the gap grows with speed. Fix: put velocity in the state and predict.
Chapter 1
Hold a best guess and a measure of how wrong it can be, and see why velocity belongs in the guess
Between ticks the filter holds two things. The first is the state x: the smallest set of numbers it needs to predict. For a drone on a line, x = [p, v]: position p in metres and velocity v in metres per second.
The GPS never measures velocity. It is in the state because you cannot predict without it. The filter infers it from how position changes. Put in the state everything you need to predict, measured or not.
The second thing is the covariance P: how spread out the filter thinks its error is. With one variable, P is the variance. P = 9 m² means about plus or minus 3 m, because the standard deviation is the square root of P.
With two variables, P is a 2 × 2 table. The diagonal holds the variance of each error. The off-diagonal says whether the two errors lean the same way.
| Entry of P | Meaning | Example |
|---|---|---|
| Top left | variance of the position error | 4 m², so ±2 m |
| Bottom right | variance of the velocity error | 1 (m/s)², so ±1 m/s |
| Off-diagonal (twice) | how the two errors move together | 1.5: too far usually means too fast |
The teal ellipse is the filter's belief: position across, velocity up, one standard deviation wide. Drag the two sliders.
Illustrative. The velocity variance stays at 1 (m/s)². The off-diagonal is the correlation times both standard deviations.
With numbers: correlation 0.75, position error 2 m, velocity error 1 m/s. The off-diagonal is 0.75 × 2 × 1 = 1.5. The blob tilts, so a reading that corrects position also corrects velocity. Chapter 6 shows how.
We carry one set of numbers through the lesson: x = [100 m, 10 m/s] with a position variance of 9 m².
The failure: a state without a quantity you need. Symptom: a position-only state predicts "it stays here", so the track falls behind a moving drone. Measure: the surprises of Chapter 3 keep the same sign tick after tick. Fix: add velocity, or acceleration, to the state.
Chapter 2
Push the guess forward with the motion model and add doubt for what the model misses
Predict runs before the new reading arrives. Shut your eyes for a second while you watch a thrown ball. You still know about where it is. You get less sure the longer your eyes stay shut.
Call the time step Δt, in seconds. Call the predicted position p̄: the bar means "before the reading". With constant velocity, the drone moves v times Δt in one step.
p-bar equals p, plus v times delta-t.
Multiply the velocity v by the time step delta-t. Add it to the last position p. The sum is p-bar.
p = 100 m, v = 10 m/s, Δt = 1 s: p̄ = 100 + 10 × 1 = 110 m.
The model is a little wrong. Wind and thrust changes push the drone off it. So predict must also grow the doubt. Call the variance the model adds in one step the process noise Q.
Capital P-bar equals capital P plus Q.
Take the variance P you had. Add Q for the step you could not see. The result P-bar is always larger.
P = 9 m², Q = 4 m²: P̄ = 9 + 4 = 13 m². The error grows from ±3.0 m to ±3.6 m.
The blue bell is the predicted belief. Each Predict slides it by v times Δt and widens it by Q. No reading arrives. Try Q = 0.
Illustrative numbers from the worked example: start at 100 m and 10 m/s with a variance of 9 m².
| Predict steps, no reading | Position | Variance, add Q = 4 each step | Error |
|---|---|---|---|
| start | 100 m | 9 m² | 3.0 m |
| 1 | 110 m | 13 m² | 3.6 m |
| 3 | 130 m | 21 m² | 4.6 m |
| 10 | 200 m | 49 m² | 7.0 m |
With no readings, P grows without limit. That is dead-reckoning drift from Lesson 1, written as a variance. A known command, such as thrust, adds a term B·u to the predicted state. It improves the guess. Q still grows the doubt, because no command runs perfectly.
The failure: Q = 0. Symptom: P shrinks at every update and never grows back, so the filter becomes sure and stops listening to readings. Measure: P falls toward zero while the error grows. Fix: give Q an honest value. Q keeps the filter listening.
Chapter 3
Compare the reading with the prediction, and judge the gap against the doubt on both sides
Now the sensor speaks. Call the reading z. It has its own error, with variance R, the measurement noise. R is to the sensor what Q is to the model. A GPS rated ±3 m has R = 9 m².
First the filter computes the gap between the reading and the prediction. Call it y, the innovation: the part of the reading the filter did not expect.
y equals z minus p-bar.
Subtract the prediction p-bar from the reading z. The result y is the surprise. Zero means the reading told you nothing new.
z = 115 m, p̄ = 110 m: y = 115 − 110 = 5 m.
Is 5 m a lot? The gap can be big because the prediction was fuzzy or because the sensor is noisy. Call the total doubt S, the innovation covariance.
S equals capital P-bar plus R.
Add the prediction's variance P-bar to the sensor's variance R. The square root of S is the size of a normal surprise.
P̄ = 13 m², R = 9 m²: S = 22 m², and its square root is 4.7 m. A surprise of 5 m is about one standard deviation: normal.
Blue is the prediction, warm is the reading, and the pink band is a normal surprise around the prediction. Drag the reading out of the band.
Illustrative numbers. The prediction stays at 110 m.
The filter never sees the truth. The surprises are its only feedback. In a healthy filter they are small, average zero and match S. Chapter 9 turns this into a health check.
The failure: judging the gap without S. Symptom: the filter rejects good readings when its prediction is fuzzy, or accepts glitches when it is sure. Measure: divide y squared by S on each tick. Fix: compare every surprise with the square root of S, never with a fixed number of metres.
Chapter 4
Set how far the estimate moves toward the reading from the two variances
We have a prediction, 110 m with variance 13, and a reading, 115 m with variance 9. How far should the estimate move from the prediction toward the reading? That fraction is the Kalman gain K.
Lesson 3 fused two readings by precision. The weight on the second came out as the first variance over the sum of both variances. Here the two sources are the prediction and the reading.
K equals capital P-bar, over capital P-bar plus R.
Divide the prediction's variance P-bar by the total doubt, P-bar plus R. The fuzzier the prediction, the closer K gets to 1.
P̄ = 13, R = 9: K = 13 / 22 = 0.59. The estimate moves 59% of the way from 110 m toward 115 m.
The bar splits the total doubt into blue (prediction) and warm (sensor). K is the blue share. Below, the estimate moves that far toward the reading. Drag both sliders, then cut the sensor.
Illustrative: the prediction is 110 m and the reading is 115 m.
| Case | P̄ | R | K | What the filter does |
|---|---|---|---|---|
| Balanced | 13 | 9 | 0.59 | leans a little toward the reading |
| Good sensor | 13 | 1 | 0.93 | snaps almost to the reading |
| Noisy sensor | 13 | 100 | 0.12 | stays near the prediction |
| Sensor dead | 13 | no reading | 0 | coasts on the model |
You never set K by hand. You set Q and R, and the filter computes K every tick. A dead sensor needs no special code: its R goes to infinity and K goes to 0. For linear models with Gaussian noise, this K leaves the smallest error variance any estimator can reach.
The failure: R set too small. Symptom: the estimate jumps with every glitch and looks as noisy as the raw sensor. Measure: log the sensor while it sits still and compare that variance with R. Fix: use the measured R.
Chapter 5
Correct the guess, shrink the doubt, and feed the result into the next tick
Two equations finish the tick. Move the prediction by K times the surprise. Then shrink the variance, because the reading taught you something. Call the corrected position p and its variance P.
p equals p-bar, plus K times y.
Take the surprise y. Keep the fraction K of it. Add that to the prediction p-bar.
p̄ = 110 m, K = 0.591, y = 5 m: p = 110 + 0.591 × 5 = 112.95 m. Lesson 3's weighted average of 110 (variance 13) and 115 (variance 9) gives the same 112.95 m.
Capital P equals one minus K, times capital P-bar.
Multiply the predicted variance P-bar by 1 minus K. The more you trust the reading, the more doubt you remove.
K = 0.591, P̄ = 13 m²: P = 0.409 × 13 = 5.32 m². That is below 13 and below 9.
Each press runs one stage: predict, read, gain, correct. Blue is the prediction, warm the reading, teal the estimate. Watch the bell widen and narrow.
Illustrative numbers: v = 10 m/s, Q = 4 m², R = 9 m², readings 115 m and then 124 m.
The variance breathes: 9, then 13, 5.32, 9.32 and 4.58. Each update leaves it a little tighter. It settles where the Q added by predict balances what the update removes. For Q = 4 and R = 9 that is a predicted variance of 8.33 m², K = 0.48, and 4.33 m² after each update.
The failure: a wrong time step. Symptom: the estimate runs ahead or falls behind when readings arrive late. Measure: log the real gap between timestamps. Fix: use the real Δt in predict, and grow Q with it.
Chapter 6
Write the cycle for position and velocity together, and watch a position reading correct velocity
Real states have several numbers that change together. Stack position and velocity into x = [p, v]. The steps stay the same. Each number becomes a matrix.
| Step | One variable | Matrix form |
|---|---|---|
| Predict the state | p̄ = p + vΔt | x̄ = F x + B u |
| Predict the doubt | P̄ = P + Q | P̄ = F P Fᵀ + Q |
| Surprise | y = z − p̄ | y = z − H x̄ |
| Its size | S = P̄ + R | S = H P̄ Hᵀ + R |
| Gain | K = P̄ / S | K = P̄ Hᵀ S⁻¹ |
| Correct | p = p̄ + K y | x = x̄ + K y |
| Shrink | P = (1 − K) P̄ | P = (I − K H) P̄ |
The state-transition matrix F moves the state one step. For the drone it is [1, Δt; 0, 1]: new position is position plus velocity times Δt, and velocity stays. The measurement matrix H picks what the sensor sees. For a GPS it is [1, 0]: position, not velocity. S⁻¹, "S inverse", divides by a matrix. With one variable, F = H = 1 and every row collapses to the left column.
The new idea is how predict creates correlation. Call the 2 × 2 covariance P, and Fᵀ, "F transposed", F with rows and columns swapped.
Capital P-bar equals F times capital P times F-transposed, plus capital Q.
Push the blob P through the motion model, F on the left and F-transposed on the right. Then add Q. The position doubt grows by the velocity doubt, and the two errors start to lean together.
With made-up numbers: P = [4, 0; 0, 1] and Q = [0.5, 0; 0, 0.5]. F P Fᵀ = [5, 1; 1, 1], so P̄ = [5.5, 1; 1, 1.5]. The off-diagonal 1 is new: a position error now comes with a velocity error.
Now a GPS reading arrives 5 m ahead of the prediction, with R = 9 m². S = 5.5 + 9 = 14.5. K = [5.5, 1] / 14.5 = [0.38, 0.07]. Position moves 0.38 × 5 = 1.9 m. Velocity moves 0.07 × 5 = 0.34 m/s, though no sensor measured it.
Velocity is up, position offset from the truth is across. Press Predict and the blob tilts. Press Update and it shrinks, and the velocity estimate climbs toward the true 12 m/s.
Illustrative: the drone starts at 103 m at 12 m/s. The filter starts at 100 m and 10 m/s with P = [4, 0; 0, 1]. Q = [0.5, 0; 0, 0.5], R = 9 m², readings without noise.
These equations give the smallest mean squared error when F and H are linear and the noise is Gaussian. With other noise they still give the best linear estimate. When F or H bend, as with a camera, the Extended Kalman Filter of Lesson 7 linearises them.
The failure: rounding breaks P after many ticks. Symptom: the output turns to not-a-number, or a gain falls outside 0 to 1. Measure: check that P's diagonal stays positive and that P equals its transpose. Fix: use the Joseph form, (I − KH) P̄ (I − KH)ᵀ + K R Kᵀ, which keeps P symmetric and much harder to break.
Chapter 7
Tune Q and R on a live tracker, cut the sensor, and read the filter's health from its ellipse
This tracker runs the matrix filter with four numbers in the state: x, y and the two velocities. The ellipse is the position part of P, one standard deviation wide. It grows at each predict and shrinks at each update.
The dashed loop is the truth, warm dots are readings, teal is the estimate and its ellipse. Press Run, then drag Q and R or switch the sensor off.
Illustrative toy: a 100 m by 60 m loop, 20 ticks a second, a constant-velocity model. The Q slider is a power of ten. Error is the root mean square over the last 100 ticks.
A tunnel, in numbers. Take Q = 1 m² per second and one GPS fix a second with R = 4 m².
| Second | Event | Variance before, then after the update | K |
|---|---|---|---|
| steady | a fix each second | 2.56, then 1.56 m² | 0.39 |
| 1 to 5 | tunnel: predict only | 2.56, 3.56, 4.56, 5.56, 6.56 m² | none |
| 6 | GPS returns | 7.56, then 2.62 m² | 0.65 |
| 7 | next fix | 3.62, then 1.90 m² | 0.48 |
| 8 | next fix | 2.90, then 1.68 m² | 0.42 |
The gain at the exit is high because the prediction is fuzzy, so the first fix pulls hard. During the tunnel the filter also told the planner it was unsure. A moving average gives a confident wrong number with no warning.
The failure: reading a small ellipse as a good filter. Symptom: the ellipse stays a dot while the track leaves the truth. Measure: compare the ellipse with the scatter of readings around the track. Fix: raise Q until the ellipse breathes with each fix.
Chapter 8
Measure R, turn Q until the surprises have the right size, and keep units and time steps honest
Most bad Kalman filters have correct code and wrong numbers. Set the numbers in this order.
Dashed is the truth, warm dots are readings, teal is the estimate. Drag Q from far left to far right and read the verdict.
Illustrative: the hero's drone with a sensor error of 3 m. The slider is a power of ten. Mean NIS is the average of y squared over S (Chapter 9), from second 10 on.
| Q | Gain | The track | Mean NIS | Verdict |
|---|---|---|---|---|
| Too small | near 0 | lags and cuts turns | well above 1 | overconfident |
| Right | balanced | smooth and on time | about 1 | healthy |
| Too large | near 1 | almost as noisy as the readings | below 1 | underconfident |
A worked case. A drone has a GPS rated ±2.5 m at 5 Hz, so Δt = 0.2 s, and gusts of up to 2 m/s². R = 6.25 m² on each axis. One gust moves the drone about 0.5 × 2 × 0.2² = 0.04 m off the model in a step. So start the position part of Q near 0.04² = 0.0016 m², then tune by the NIS. Start with P0 = 25 m².
The failure: tuning by eye alone. Symptom: two engineers pick values of Q ten times apart and both call the track smooth. Measure: the mean NIS over a long run. Fix: tune until it sits near 1.
Chapter 9
Use the normalized surprise to catch an overconfident filter, glitches and a wrong model
A broken Kalman filter rarely crashes. It keeps running and reports a tight P while it drifts away. The witness is the surprise y. Scale each surprise by the size the filter expected, S.
Epsilon equals y squared over S.
Square the surprise y. Divide by S, the size the filter expected. A healthy filter averages epsilon near 1 over many ticks.
y = 5 m, S = 22 m²: ε = 25 / 22 = 1.14, normal. A reading of 140 m gives y = 30 m and ε = 900 / 22 = 40.9.
Each bar is one tick's NIS, on a scale that grows ten times per line. The green line is 1, the red line is the gate at 9. Pick a filter, then switch the gate on.
Illustrative: the hero's drone with a sensor error of 3 m. Glitches add 30 m to four readings. The gate skips any reading whose NIS is above 9, about 3 standard deviations.
| Symptom | NIS | Cause | Fix |
|---|---|---|---|
| Drifts off with a tiny P | well above 1, growing | Q too small | raise Q |
| As noisy as the readings | well below 1 | Q too large | lower Q |
| Lags reality | well below 1 | R too large | lower R |
| Sudden jumps | rare huge spikes | glitches, such as GPS multipath | gate the update |
| Long runs of same-sign surprises | mean of y is not zero | wrong motion model | richer model, or an EKF |
| Reading z | Surprise y | NIS, S = 22 | Gate at 9 |
|---|---|---|---|
| 115 m | 5 m | 1.14 | accept |
| 118 m | 8 m | 2.91 | accept |
| 140 m, a glitch | 30 m | 40.9 | reject, coast on the prediction |
One line of code is the gate: skip the update if y squared over S is above 9. The filter coasts on its prediction for that tick. The covariance cannot police itself. The surprises police it.
Chapter 10
Keep the equations, the numbers, the checks and the core code of the filter on one page
The Kalman filter keeps a guess x and its doubt P. Predict slides the guess and adds Q. The reading gives a surprise y with expected size S. The gain K, the prediction's share of S, sets how far the guess moves. The update shrinks the doubt, and the result feeds the next tick. Watch the NIS to know it works.
| Step | Equation | Worked numbers |
|---|---|---|
| Predict the state | p̄ = p + vΔt | 100 + 10 × 1 = 110 m |
| Predict the doubt | P̄ = P + Q | 9 + 4 = 13 m² |
| Surprise | y = z − p̄ | 115 − 110 = 5 m |
| Its size | S = P̄ + R | 13 + 9 = 22 m² |
| Gain | K = P̄ / (P̄ + R) | 13 / 22 = 0.591 |
| Correct | p = p̄ + K y | 110 + 0.591 × 5 = 112.95 m |
| Shrink | P = (1 − K) P̄ | 0.409 × 13 = 5.32 m² |
| Health | ε = y² / S | 25 / 22 = 1.14, healthy near 1 |
| Steady state, Q 4, R 9 | predict balances update | 8.33 m² before, 4.33 m² after, K 0.48 |
| Term | Meaning |
|---|---|
| State x | The numbers the filter needs to predict, such as position and velocity. |
| Covariance P | How spread out the filter thinks its error is. |
| Process noise Q | The doubt one predict step adds for what the model misses. |
| Measurement noise R | The variance of the sensor's error. |
| Innovation y | The reading minus the prediction: the surprise. |
| Innovation covariance S | The expected size of the surprise. |
| Kalman gain K | The fraction of the surprise the filter acts on. |
| F and H | The motion model and what the sensor sees, as matrices. |
| NIS | The surprise squared over S; averages 1 in a healthy filter. |
| Gate | Skip a reading whose NIS is too large to be honest. |
pythonimport numpy as np def kalman_step(p, v, P, z, Q, R, dt=1.0): # one variable, velocity fixed p = p + v * dt # predict the state P = P + Q # predict the doubt y = z - p # surprise S = P + R # its expected size if y * y / S > 9: # gate: skip a glitch return p, v, P K = P / S # gain, the trust dial return p + K * y, v, (1 - K) * P def kf_matrix(x, P, z, F, H, Q, R): # the same steps, any size x = F @ x; P = F @ P @ F.T + Q y = z - H @ x; S = H @ P @ H.T + R K = P @ H.T @ np.linalg.inv(S) I = np.eye(len(x)) return x + K @ y, (I - K @ H) @ P kalman_step(100, 10, 9, 115, 4, 9) # (112.95, 10, 5.32)
| Product | State | Predict model F | Reading H |
|---|---|---|---|
| Phone and car navigation | position, velocity | inertial motion from the IMU | GPS fix |
| Air-traffic radar | position, velocity | constant velocity | radar return |
| Robot vacuum | x, y, heading | wheel odometry | a landmark or wall |
| Spacecraft | position, velocity, attitude | orbital dynamics | star tracker, ground radar |
| Finance | a hidden fair price | a slow drift | the observed price |
Now press Present or Teach and run one tick from memory: 100 m, 9 m², Q 4, reading 115 m, R 9. Then go back to the drone, pick Moving average and then Kalman filter, and say why one lags and the other does not.