The Kalman Filter

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.

Track a drone through noise

3.0 m

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

A Noisy Reading, a Smooth Estimate

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.

Why not average the last few readings?

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.

Pooled readings beat the sensor

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.

Pool readings of a parked drone

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.

4

Illustrative: each reading has an error of 3 m (one standard deviation), independent of the others.

Readings fused, NError, 3 m divided by the square root of NCompared with one reading
13.00 mthe raw sensor
41.50 mtwo times sharper
160.75 mfour times sharper
1000.30 mten 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.

The road

  1. The guess and its doubt: the state x and the covariance P.
  2. Predict: slide the guess, grow the doubt by Q.
  3. The surprise: the innovation y and its expected size S.
  4. The gain: the trust dial K, from Lesson 3.
  5. One full cycle: correct, shrink, repeat (the Kalman line of the hero).
  6. The matrix form: a position reading corrects velocity.
  7. Showcase: a live 2-D tracker you can break.
  8. Tuning: R from the sensor, Q as the knob (the hero's noise slider).
  9. Debugging: read the normalized surprise.
  10. The field guide: numbers, terms, code and sources.
A 5-reading moving average follows a drone at a steady 10 m/s, one reading a second. About how far behind is its answer?

Chapter 1

Carry a Guess and Its Doubt

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 PMeaningExample
Top leftvariance of the position error4 m², so ±2 m
Bottom rightvariance of the velocity error1 (m/s)², so ±1 m/s
Off-diagonal (twice)how the two errors move together1.5: too far usually means too fast

Shape the belief blob

The teal ellipse is the filter's belief: position across, velocity up, one standard deviation wide. Drag the two sliders.

4 m²
0.75

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.

The filter reports a position variance P = 16 m². What is its one-standard-deviation position error?

Chapter 2

Predict: Slide the Guess, Grow the Doubt

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.

Say it aloud

p-bar equals p, plus v times delta-t.

p̄
p-bar the predicted position, before the reading, in metres.
p
p the position estimate after the last tick.
v
v the estimated velocity, in m/s. The constant-velocity model keeps it unchanged.
Δt
delta-t the time step, in seconds.
In plain words

Multiply the velocity v by the time step delta-t. Add it to the last position p. The sum is p-bar.

With numbers

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.

Say it aloud

Capital P-bar equals capital P plus Q.

P̄
capital P-bar the variance of the predicted position, in m².
P
capital P the variance after the last tick.
Q
Q the process noise: how far reality can stray from the model in one step, in m².
In plain words

Take the variance P you had. Add Q for the step you could not see. The result P-bar is always larger.

With numbers

P = 9 m², Q = 4 m²: P̄ = 9 + 4 = 13 m². The error grows from ±3.0 m to ±3.6 m.

Predict with no readings

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.

4.0 m²

Illustrative numbers from the worked example: start at 100 m and 10 m/s with a variance of 9 m².

Predict steps, no readingPositionVariance, add Q = 4 each stepError
start100 m9 m²3.0 m
1110 m13 m²3.6 m
3130 m21 m²4.6 m
10200 m49 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.

Start with a position variance of 9 m² and Q = 4 m². What is the variance after three predict steps with no reading?

Chapter 3

The Innovation: How Surprised Is the Filter?

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.

Say it aloud

y equals z minus p-bar.

y
y the innovation, the surprise, in metres.
z
z the reading from the sensor.
p̄
p-bar the predicted position from Chapter 2.
In plain words

Subtract the prediction p-bar from the reading z. The result y is the surprise. Zero means the reading told you nothing new.

With numbers

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.

Say it aloud

S equals capital P-bar plus R.

S
S the expected size of the surprise, as a variance, in m².
P̄
capital P-bar the doubt in the prediction.
R
R the doubt in the sensor.
In plain words

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.

With numbers

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.

Judge the surprise

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.

115 m
13 m²
9 m²

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.

The prediction is 50 m with variance 7 m². The reading is 54 m with variance 9 m². What are y and S?

Chapter 4

The Kalman Gain Is a Trust Dial

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.

Say it aloud

K equals capital P-bar, over capital P-bar plus R.

K
K the Kalman gain, from 0 to 1: the fraction of the surprise the filter acts on.
P̄
capital P-bar the variance of the prediction.
P̄ + R
capital P-bar plus R the total doubt, which is S from Chapter 3.
In plain words

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.

With numbers

P̄ = 13, R = 9: K = 13 / 22 = 0.59. The estimate moves 59% of the way from 110 m toward 115 m.

Set the trust dial

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.

13 m²
9 m²

Illustrative: the prediction is 110 m and the reading is 115 m.

CaseP̄RKWhat the filter does
Balanced1390.59leans a little toward the reading
Good sensor1310.93snaps almost to the reading
Noisy sensor131000.12stays near the prediction
Sensor dead13no reading0coasts 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.

The sensor suddenly gets much noisier, so R grows large. What does K do, and what does the filter do?

Chapter 5

One Full Cycle, by Hand

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.

Say it aloud

p equals p-bar, plus K times y.

p
p the corrected position estimate, in metres.
p̄
p-bar the predicted position.
K
K the gain from Chapter 4.
y
y the surprise from Chapter 3.
In plain words

Take the surprise y. Keep the fraction K of it. Add that to the prediction p-bar.

With numbers

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.

Say it aloud

Capital P equals one minus K, times capital P-bar.

P
capital P the variance after the update, in m².
1 − K
one minus K the fraction of the doubt that is left.
P̄
capital P-bar the variance of the prediction.
In plain words

Multiply the predicted variance P-bar by 1 minus K. The more you trust the reading, the more doubt you remove.

With numbers

K = 0.591, P̄ = 13 m²: P = 0.409 × 13 = 5.32 m². That is below 13 and below 9.

Step through two ticks

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.

We predicted 110 m (variance 13), read 115 m (variance 9), and got 112.95 m with variance 5.32. Why is 5.32 smaller than both 13 and 9?

Chapter 6

The Matrix Form: Same Steps, More Numbers

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.

StepOne variableMatrix form
Predict the statep̄ = p + vΔtx̄ = F x + B u
Predict the doubtP̄ = P + QP̄ = F P Fᵀ + Q
Surprisey = z − p̄y = z − H x̄
Its sizeS = P̄ + RS = H P̄ Hᵀ + R
GainK = P̄ / SK = P̄ Hᵀ S⁻¹
Correctp = p̄ + K yx = x̄ + K y
ShrinkP = (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.

Say it aloud

Capital P-bar equals F times capital P times F-transposed, plus capital Q.

P̄
capital P-bar the predicted 2 × 2 covariance of position and velocity.
F
F the state-transition matrix, [1, 1; 0, 1] with Δt = 1 s.
P
capital P the covariance after the last update.
Fᵀ
F-transposed F with rows and columns swapped, [1, 0; 1, 1].
Q
capital Q the process noise, now a 2 × 2 table.
In plain words

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 numbers

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.

Watch a position reading fix velocity

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.

The GPS measures only position (H = [1, 0]). How does the filter correct its velocity?

Chapter 7

Showcase: Track a Flying Drone, Then Break It

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.

Run the tracker, then break it

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.

4.0 m
0.01

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.

  1. Raise the sensor noise to the top. The dots scatter, K falls, and the track stays smooth but lags a little on turns.
  2. Drag Q to the bottom and wait. The ellipse shrinks to a dot, K dies, and the track cuts the corners. That is divergence.
  3. Switch the sensor off. The ellipse balloons as the filter coasts. Switch it on and the ellipse snaps back within a few ticks.

A tunnel, in numbers. Take Q = 1 m² per second and one GPS fix a second with R = 4 m².

SecondEventVariance before, then after the updateK
steadya fix each second2.56, then 1.56 m²0.39
1 to 5tunnel: predict only2.56, 3.56, 4.56, 5.56, 6.56 m²none
6GPS returns7.56, then 2.62 m²0.65
7next fix3.62, then 1.90 m²0.48
8next fix2.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.

In the tunnel table, why is the gain at the exit (0.65) higher than in steady state (0.39)?

Chapter 8

Tune the Two Noises and the Starting Doubt

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.

  1. R from the sensor. Read the datasheet, or log the sensor while it sits still and take the variance. A GPS rated ±2.5 m (one standard deviation) gives R = 6.25 m².
  2. Q as the main knob. Start from the largest acceleration the model ignores. Raise Q if the track lags. Lower it if the track jitters.
  3. P0 generous. P0 is the starting covariance. Start unsure, such as 25 m² for ±5 m. The first gains are then near 1, so the filter locks on in a few ticks.
  4. One unit system. Metres and seconds everywhere. A variance in centimetres is 10,000 times the same variance in metres.
  5. The real Δt. Timestamp every reading. In a constant-velocity model the position part of Q grows with Δt cubed, so a fixed Q is wrong when the gap changes.

Turn the Q knob

Dashed is the truth, warm dots are readings, teal is the estimate. Drag Q from far left to far right and read the verdict.

0.1

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.

QGainThe trackMean NISVerdict
Too smallnear 0lags and cuts turnswell above 1overconfident
Rightbalancedsmooth and on timeabout 1healthy
Too largenear 1almost as noisy as the readingsbelow 1underconfident

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.

Your tracker lags on every turn and drifts during fast moves. Which single change fixes it most directly?

Chapter 9

When the Filter Lies: Read the Surprises

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.

Say it aloud

Epsilon equals y squared over S.

ε
epsilon the normalized innovation squared (NIS), with no unit.
y2
y squared the surprise times itself, in m².
S
S the expected size of the surprise, P-bar plus R, in m².
In plain words

Square the surprise y. Divide by S, the size the filter expected. A healthy filter averages epsilon near 1 over many ticks.

With numbers

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.

Watch the NIS

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.

SymptomNISCauseFix
Drifts off with a tiny Pwell above 1, growingQ too smallraise Q
As noisy as the readingswell below 1Q too largelower Q
Lags realitywell below 1R too largelower R
Sudden jumpsrare huge spikesglitches, such as GPS multipathgate the update
Long runs of same-sign surprisesmean of y is not zerowrong motion modelricher model, or an EKF
Reading zSurprise yNIS, S = 22Gate at 9
115 m5 m1.14accept
118 m8 m2.91accept
140 m, a glitch30 m40.9reject, 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.

The estimate drifts from the truth while P stays tiny, and the surprises grow large and one-sided. What is wrong, and what is the fix?

Chapter 10

The Field Guide

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.

The numbers

StepEquationWorked numbers
Predict the statep̄ = p + vΔt100 + 10 × 1 = 110 m
Predict the doubtP̄ = P + Q9 + 4 = 13 m²
Surprisey = z − p̄115 − 110 = 5 m
Its sizeS = P̄ + R13 + 9 = 22 m²
GainK = P̄ / (P̄ + R)13 / 22 = 0.591
Correctp = p̄ + K y110 + 0.591 × 5 = 112.95 m
ShrinkP = (1 − K) P̄0.409 × 13 = 5.32 m²
Healthε = y² / S25 / 22 = 1.14, healthy near 1
Steady state, Q 4, R 9predict balances update8.33 m² before, 4.33 m² after, K 0.48

The terms

TermMeaning
State xThe numbers the filter needs to predict, such as position and velocity.
Covariance PHow spread out the filter thinks its error is.
Process noise QThe doubt one predict step adds for what the model misses.
Measurement noise RThe variance of the sensor's error.
Innovation yThe reading minus the prediction: the surprise.
Innovation covariance SThe expected size of the surprise.
Kalman gain KThe fraction of the surprise the filter acts on.
F and HThe motion model and what the sensor sees, as matrices.
NISThe surprise squared over S; averages 1 in a healthy filter.
GateSkip a reading whose NIS is too large to be honest.

The checklist

  1. Put everything you need to predict in the state.
  2. Measure R from the sensor, in variance and SI units.
  3. Start with a generous P0.
  4. Use the real Δt, and grow Q with it.
  5. Tune Q until the mean NIS sits near 1.
  6. Gate readings with NIS above 9.
  7. Check that P stays symmetric with a positive diagonal; use the Joseph form for long runs.
  8. Drop the sensor on purpose: P must grow, then recover when it returns.

The core as code

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)

Where it runs

ProductStatePredict model FReading H
Phone and car navigationposition, velocityinertial motion from the IMUGPS fix
Air-traffic radarposition, velocityconstant velocityradar return
Robot vacuumx, y, headingwheel odometrya landmark or wall
Spacecraftposition, velocity, attitudeorbital dynamicsstar tracker, ground radar
Financea hidden fair pricea slow driftthe observed price

Keep going

The takeaway. The Kalman gain is Lesson 3's trust weight, choosing each tick between your model and your sensor. You set Q and R; the filter sets K.
A colleague says the Kalman gain is deep matrix algebra, unrelated to the two-sensor fuse of Lesson 3. What is the correction?

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.

Sources

  1. R. E. Kalman, "A New Approach to Linear Filtering and Prediction Problems," Journal of Basic Engineering 82(1), 35–45, 1960. doi
  2. D. Simon, Optimal State Estimation: Kalman, H∞, and Nonlinear Approaches, Wiley, 2006. Wiley
  3. P. S. Maybeck, Stochastic Models, Estimation, and Control, Vol. 1, Academic Press, 1979. ScienceDirect
  4. G. Welch and G. Bishop, "An Introduction to the Kalman Filter," TR 95-041, University of North Carolina at Chapel Hill. UNC
Sensor Fusion: Classical to Modern · Lesson 5: The Kalman Filter
Next: Complementary Filters and AHRS · Back to Gleams