The Kalman filter

A drone reports its GPS position ten times a second, and each fix lands about 6 m from where it really is. The Kalman filter turns those same fixes into a track that stays within about 2.5 m, and it keeps tracking when the GPS drops out.

Pick who you trust: the sensor, the motion model, or the filter. Drag the GPS noise up. Cut the GPS for three seconds. Then we build the filter from two numbers up, piece by piece.

You need a mean and a standard deviation and how to multiply two small matrices. We build the rest from zero.

Track the drone

Running
4.0 m

The grey dashed line is the drone's real path. Blue dots are GPS fixes. The warm line is the Kalman estimate.

A toy scene: the drone weaves at 8 m/s and the GPS reports ten times a second with Gaussian noise. Every number in the read-out is measured on this page over the last 10 seconds, so your run will differ a little from the lede.

Chapter 0

Two liars, one drone

Why neither the sensor nor the model can track the drone on its own

You fly a small drone over a field. You want to know where it is, right now, to within a metre or two. You have two sources of information. Both of them lie, and they lie in different ways.

The first source is the GPS receiver. It reports a position ten times a second. Each report is called a measurement, and we write it z. A fix is not wrong by a fixed amount. It is wrong by a fresh random amount every time, about 4 m in each direction.

Plot ten seconds of fixes and you get a cloud, not a line. The drone is somewhere in the cloud.

The second source is the motion model. You know the drone's speed and heading, because you commanded them. So you can predict: in a tenth of a second it moves 0.8 m along its heading. Add that to where you thought it was. Repeat. This is called dead reckoning, and sailors did it for centuries. It is smooth and it never jitters.

It also walks away from the truth. Your speed is a little off. The wind pushes. The drone turns a bit earlier than you commanded. Each tiny error joins the position and stays there forever.

After ten seconds, dead reckoning in the hero scene is off by about 40 m. After forty seconds, by about 180 m. Nothing ever pulls it back.

So the sensor is noisy but honest on average. Its errors do not pile up. The model is smooth but drifting. Its errors do nothing but pile up. Look at both failures in one picture.

Watch both liars

The drone climbs at 1 m/s for 20 seconds. The dashed grey line is the truth. Turn each liar on and off. Drag the noise and the speed error. Press New readings for a fresh set of sensor errors.

3.0 m
10 %

Illustrative: a one-dimensional climb, so you can read every error off the axis. The hero scene above is the same story in two dimensions.

Read the picture. The blue dots scatter around the truth and never settle. The purple line starts right and leaves, and the gap only grows. Notice that the two errors look nothing alike. One is a cloud. One is a slope.

Now try the obvious repairs. First repair: average the last ten GPS fixes. Averaging ten independent readings shrinks the spread by the square root of ten. Here is the number:

spread of one fix 4.0 m spread of a 10-fix average 4.0 / √10 = 4.0 / 3.162 = 1.26 m distance flown in those 10 fixes 8 m/s × 1.0 s = 8.0 m

The spread falls to 1.26 m. Good. But those ten fixes took a full second, and the drone flew 8 m in that second. The average sits in the middle of that second, 0.45 s in the past, which is 3.6 m behind the drone. Average more fixes and the lag grows. Average fewer and the noise returns. There is no setting of this knob that wins.

python# the moving average, measured: noise falls, a lag appears
dt, v, sigma = 0.1, 8.0, 4.0
truth = v * dt * np.arange(400)
z = truth + rng.normal(0, sigma, 400)
for n in (1, 5, 10, 20, 40):
    avg = np.convolve(z, np.ones(n) / n, mode="valid")       # mean of the last n fixes
    err = avg - truth[n - 1:]                                   # compare with the truth NOW
    print(n, "lag %.1f m  spread %.2f m  total %.2f m" % (-err.mean(), err.std(), np.sqrt((err**2).mean())))
#  1  lag 0.0 m  spread 4.02 m  total 4.02 m     the raw fix
#  5  lag 1.6 m  spread 1.79 m  total 2.41 m
# 10  lag 3.6 m  spread 1.27 m  total 3.82 m     the noise is gone, the lag is worse than the noise was
# 20  lag 7.6 m  spread 0.89 m  total 7.65 m
# 40  lag 15.6 m spread 0.63 m  total 15.61 m

Read the total column. It gets better until about five fixes and then gets worse, because the lag grows faster than the noise shrinks. The best moving average on this drone is still off by 2.4 m, and it only reaches that by knowing nothing about how the drone moves. The filter will do better by knowing one thing: that the drone has a velocity.

The sensor

noise

Each error is new and independent. Mean error near zero. Spread about 4 m and it never improves on its own. Averaging helps, and lags.

The model

drift

Each error is added to the last one. Starts near perfect. Spread grows without bound. Nothing inside the model can pull it back.

Second repair: fly on the model and correct it with the GPS now and then. This is the right idea. It raises the real question: correct by how much? If you snap to every fix, you are back to the cloud. If you nudge too gently, you are back to the drift.

The answer must depend on how wrong you think each source is right now. When the GPS is poor, lean on the model. When the model has been drifting for a while, lean on the GPS.

That sentence is the Kalman filter. Rudolf Kálmán published it in 1960, and it guided the Apollo spacecraft to the Moon nine years later. It keeps two numbers for every quantity it tracks: a best guess, and how unsure it is of that guess.

Then it does one thing over and over. It predicts with the model, which makes it more unsure. It corrects with the sensor, which makes it less unsure. And the size of each correction comes from comparing the two doubts.

Here is that loop as a chain. Every chapter from 3 to 6 is one link of it, done with numbers.

  1. Predict. Push the guess forward with the model. The doubt grows.
  2. Compare. A fix arrives. Subtract what you expected to see. The difference is the surprise.
  3. Weigh. Compare your doubt with the sensor's doubt. The ratio is the gain.
  4. Correct. Move the guess toward the fix by the gain times the surprise. The doubt shrinks.
  5. Repeat, ten times a second, for as long as the drone flies.
Why the doubt has to travel with the guess. A number on its own cannot be combined with anything. "The drone is at 120 m" and "the drone is at 128 m" give you no way to choose. "120 m, give or take 8" and "128 m, give or take 2" tell you the answer is near 128. Every step of the filter is this comparison, done with algebra.

Here is the same idea in code. We simulate both liars for twenty seconds so you can see their errors in numbers, not just in a picture.

pythonimport numpy as np
rng = np.random.default_rng(1)

dt, T   = 0.1, 200          # 10 Hz for 20 s
truth   = 1.0 * dt * np.arange(T)      # climbs at 1 m/s

# liar 1: the sensor. Fresh noise on every fix, spread 3 m, no memory.
z = truth + rng.normal(0, 3.0, size=T)

# liar 2: the model. Speed is 10 % too high. The error is added every step and never leaves.
model = np.cumsum(np.full(T, 1.1 * dt))

print("sensor: mean error %.2f, spread %.2f" % ((z - truth).mean(), (z - truth).std()))
print("model : error at 5 s %.2f, at 20 s %.2f" % (model[50] - truth[50], model[-1] - truth[-1]))
# sensor: mean error -0.03, spread 2.95   (unbiased, never settles)
# model : error at 5 s 0.51, at 20 s 2.09  (tiny, then grows without bound)

The sensor's mean error is near zero and its spread stays near 3. The model's error is a tenth of a metre at the start and keeps climbing. Two very different kinds of wrong. One filter will handle both.

Here is the road. Each line is a chapter, and each chapter adds one part of the filter you played with in the hero.

  1. A guess and a doubt: the two numbers the filter carries, and the bell curve behind them.
  2. Fuse two guesses: how to weight two uncertain numbers, and why the result is surer than both.
  3. Predict forward: the motion model, and why every prediction adds doubt.
  4. The Kalman gain: the trust slider that sets how far to move toward the sensor.
  5. The loop: predict, update, repeat, worked by hand for eight steps.
  6. Matrices: position and velocity together, and how the filter fixes a velocity it never measures.
  7. The tracker: the full two-dimensional filter from the hero, with every knob exposed.
  8. Tuning and breaking it: Q, R, the consistency check, and the ways the filter lies to you.
  9. Beyond: the cheat sheet, the code, and where EKF, UKF and SLAM pick up.
Why does averaging the last ten GPS fixes fail to solve the tracking problem?

Chapter 1

A guess and a doubt

Every quantity gets two numbers: a mean and a spread

Put the drone on the ground and read its altitude sensor five times. You get 9.8, 10.4, 10.1, 9.7 and 10.0 m. The drone did not move. The sensor did. We need a way to say "about 10, with this much wobble" as numbers.

The first number is the mean, the plain average. Add the five readings and divide by five. The second number is the variance: take each reading's distance from the mean, square it, and average those squares. The square root of the variance is the standard deviation, written σ (sigma). It has the same unit as the readings, so you can picture it. Here is every step:

readings 9.8 10.4 10.1 9.7 10.0 mean (9.8 + 10.4 + 10.1 + 9.7 + 10.0) / 5 = 50.0 / 5 = 10.0 deviations -0.20 +0.40 +0.10 -0.30 0.00 squared 0.04 0.16 0.01 0.09 0.00 variance (0.04 + 0.16 + 0.01 + 0.09 + 0.00) / 5 = 0.30 / 5 = 0.060 m² sigma √0.060 = 0.245 m

So the sensor says "10.0 m, give or take 0.245". The variance is in square metres, which is why we also keep its square root. The filter does its algebra in variances, because variances add. We read results in sigmas, because sigmas have the unit we care about.

Now the shape. Take not five readings but five thousand, and draw a histogram. The bars form a hill: tall at the mean, falling off on both sides, nearly nothing far out.

That hill is the Gaussian, also called the normal distribution or the bell curve. Its whole shape is set by the two numbers we already have. The mean says where the peak is. The sigma says how wide the hill is.

Draw readings from a Gaussian

The curve is the Gaussian for your mean and sigma. Press Take 50 readings and watch the dots pile up under it. The shaded band is one sigma each side. Count how many dots fall inside it.

10.0 m
1.0 m

Three facts about this hill come up again and again. About 68% of readings land within one sigma of the mean. About 95% land within two sigmas. About 99.7% land within three. These are not laws of nature. They are properties of this one shape, and they let you turn a sigma into a sentence: "19 times in 20, the fix is within 8 m".

BandShare of readings insideFor the drone's GPS, sigma 4 mShare outside
±1 sigma68.3%within 4 mabout 1 fix in 3
±2 sigma95.4%within 8 mabout 1 fix in 22
±3 sigma99.7%within 12 mabout 1 fix in 370

The last column is the one engineers use. A fix 13 m from where you expected it is a one-in-several-hundred event if the sensor is honest. If you see several of those in a minute, the sensor is not honest, and Chapter 8 shows what to do with it.

Here is the curve as a formula. You will not need to compute it by hand in this lesson, but you should recognise its parts. Hover or tap any symbol.

N(x; μ, σ²)
How likely a reading near x is, for a Gaussian with mean μ and variance σ². The height of the hill at x.
(x − μ)²
The squared distance from the mean. Squaring makes left and right count the same and punishes far-out readings hard.
2σ²
The scale of "far". Dividing by it means a reading one sigma out always lands at the same height, whatever the units.
exp( − … )
Turns the squared distance into a height that falls off fast: 1 at the mean, 0.61 at one sigma, 0.14 at two, 0.011 at three.
1 / √(2πσ²)
A normalising constant so the total area under the hill is exactly 1. It makes the hill shorter when it is wider.

Why this shape and not another? Two reasons, and both matter for the filter. First, errors that are the sum of many small independent effects come out Gaussian. That is the central limit theorem. GPS error is thermal noise plus ionosphere delay plus clock jitter plus multipath, and the sum is a bell.

You can watch it happen. Draw twelve numbers evenly from −0.5 to 0.5. That is a flat distribution, with nothing bell-like about it. Add the twelve, and the sum has sigma 1.00 and puts 68% of its draws within ±1. Twelve flat things added together make a bell.

python# the central limit theorem in three lines
flat = rng.uniform(-0.5, 0.5, size=(20000, 12))   # 12 flat errors per trial, each with variance 1/12
total = flat.sum(axis=1)                            # their sum: variance 12 × 1/12 = 1
print(total.std(), (np.abs(total) <= 1).mean())    # 0.996  0.682   a Gaussian with sigma 1

Second, the Gaussian is closed under the two operations the filter needs, and these two facts are the whole reason the filter can exist. Shift a Gaussian or scale it, and it is still a Gaussian:

if x ~ N(μ, σ²) then a·x + b ~ N(aμ + b, a²σ²) (Chapter 3 uses this)

Multiply two Gaussian curves together, and the result is still a Gaussian curve, with a precision that is the sum of the two precisions:

N(μ1, σ1²) × N(μ2, σ2²) ∝ N(μ, σ²) with 1/σ² = 1/σ1² + 1/σ2² (Chapter 2 derives this)

No other common shape has both properties. A flat distribution shifted is still flat, but two flat distributions multiplied are not flat, and a flat distribution pushed through a motion model with noise is not flat. The Gaussian comes back as a Gaussian from everything the filter does to it. That is why a Kalman filter only ever has to carry two numbers, and why it stops being exact the moment the noise stops being a bell.

One more rule, and then you have everything Chapter 2 needs. When you add two independent uncertain quantities, their variances add. Not their sigmas. Suppose a drone's position is uncertain with sigma 3 m, and you move it by an uncertain step with sigma 4 m. The result:

variance of position 3² = 9 variance of the step 4² = 16 variance of the sum 9 + 16 = 25 sigma of the sum √25 = 5 m (not 3 + 4 = 7)

The sigmas combine like the sides of a right triangle, not like lengths laid end to end. The reason is that the two errors are as likely to cancel as to reinforce. This one rule is the whole of the "predict" step in Chapter 3.

Here is the same arithmetic as code, first by hand and then with the library call, so you can see they agree.

pythonimport numpy as np
xs = [9.8, 10.4, 10.1, 9.7, 10.0]

# by hand
mean = sum(xs) / len(xs)                           # 10.0
var  = sum((x - mean) ** 2 for x in xs) / len(xs)   # 0.060
sigma = var ** 0.5                                   # 0.245

# the library does the same thing
print(np.mean(xs), np.var(xs), np.std(xs))            # 10.0 0.06 0.2449

# the bell curve itself, evaluated at a few points
def gauss(x, mu, var):
    return np.exp(-(x - mu) ** 2 / (2 * var)) / np.sqrt(2 * np.pi * var)

print(gauss(10.0, 10, 1), gauss(11.0, 10, 1), gauss(12.0, 10, 1))
# 0.3989 0.2420 0.0540   (the peak, one sigma out, two sigmas out)

# variances add; sigmas do not
print(np.sqrt(3**2 + 4**2))                              # 5.0
A position has sigma 3 m. You add an independent step with sigma 4 m. What is the sigma of the result?

Chapter 2

Fuse two guesses

Weight each guess by how sure it is, and the result is surer than both

Two rangefinders point at the same wall. Sensor A says 10.0 m with sigma 2. Sensor B says 14.0 m with sigma 4. Where is the wall?

The plain average, 12.0, treats them as equals. But A is twice as sure as B. The answer should sit closer to A.

Let us find the best weight, not guess it. Call the combined estimate x̂ (x hat; the hat means "our estimate of"). Mix the two readings with a weight w on A and 1 − w on B, so the weights add to one and the estimate has no built-in bias:

x̂
The fused estimate. The hat means "our best guess of x", not x itself.
a
Sensor A's reading, 10.0 m, with variance σa² = 4.
b
Sensor B's reading, 14.0 m, with variance σb² = 16.
w
How much of the answer comes from A. A number between 0 and 1 that we will choose.
1 − w
What is left for B. The two weights sum to 1, so a true wall at 12 gives an estimate centred on 12.

Which w is best? The one that makes the estimate's own variance as small as possible. The variance rule from Chapter 1 tells us what that variance is. Scaling a quantity by w scales its variance by w², and independent variances add:

Var(x̂) = w² σa² + (1 − w)² σb²

This is a bowl-shaped curve in w. Its lowest point is where the slope is zero. Take the derivative with respect to w and set it to zero. Every step:

derivative 2w σa² − 2(1 − w) σb² = 0 divide by 2 w σa² = (1 − w) σb² expand w σa² = σb² − w σb² collect w w (σa² + σb²) = σb² solve w = σb² / (σa² + σb²)

Read that result slowly. The weight on A is B's variance over the total. The worse B is, the more you trust A. That is exactly the instinct we started with, now as a formula. Put in the numbers:

weight on A w = 16 / (4 + 16) = 16 / 20 = 0.80 weight on B 1 − w = 0.20 estimate x̂ = 0.80 × 10.0 + 0.20 × 14.0 = 8.0 + 2.8 = 10.8 m variance 0.80² × 4 + 0.20² × 16 = 0.64 × 4 + 0.04 × 16 = 2.56 + 0.64 = 3.2 sigma √3.2 = 1.79 m

The fused sigma is 1.79 m. Sensor A alone had 2.0. Sensor B alone had 4.0. The combination is better than the better sensor. A worse sensor still helped, because its error is independent and sometimes cancels A's. Play with that claim before we go on.

Fuse two Gaussians

Blue is sensor A, purple is sensor B, warm is the fused result. Drag the sigmas. Watch the warm curve sit closer to the narrower one, and stay narrower than either.

2.0 m
4.0 m
14.0 m

There is a second way to write the same variance, and it is the one worth memorising. Take the reciprocal of each variance. Call it precision: how sure you are, as a number that gets bigger when you get surer. Then:

1 / σ² = 1 / σa² + 1 / σb² (precisions add)

precision of A 1 / 4 = 0.2500 precision of B 1 / 16 = 0.0625 fused precision 0.2500 + 0.0625 = 0.3125 fused variance 1 / 0.3125 = 3.2 (the same 3.2 as before)

Precisions add. That is why a second sensor can only help, never hurt, as long as its error is independent. Even a terrible sensor has a small positive precision to contribute.

The precision form also tells you what to do with three sensors, or thirty. Add all the precisions. Then weight each reading by its own precision and divide by the total. Add a third rangefinder, C, that says 11.0 m with sigma 3:

precisions A: 1/4 = 0.2500 B: 1/16 = 0.0625 C: 1/9 = 0.1111 total 0.2500 + 0.0625 + 0.1111 = 0.4236 fused variance 1 / 0.4236 = 2.361, sigma 1.54 m (was 1.79 with two) fused mean (10.0 × 0.2500 + 14.0 × 0.0625 + 11.0 × 0.1111) / 0.4236 = (2.500 + 0.875 + 1.222) / 0.4236 = 4.597 / 0.4236 = 10.85 m

Every sensor votes with a weight equal to its precision. No sensor is ever thrown away, and no sensor ever gets more than its share. This is the rule a whole fusion stack runs on, whether it fuses two rangefinders or a GPS, a camera, and an inertial unit.

Two things break the rule, and you should know them before you trust it. First, correlated errors. Two GPS receivers on the same drone share the same ionosphere delay, so their errors move together. Fuse them as if they were independent and you will claim a precision you do not have.

Second, bias. A sensor that always reads 2 m high is not noisy, it is wrong, and no weight fixes it. Its variance can be tiny and it will drag the fused answer toward its lie with full confidence. Both of these come back in Chapter 8.

The trade, in one line. Every measurement you fuse adds its precision to yours. Every prediction you make (next chapter) adds variance to yours. The filter is the bookkeeping of those two opposite motions, and the gain is where they balance.

Now a rewrite that will look trivial and is the whole filter in disguise. Start from A and move toward B by a fraction:

start from the mix x̂ = w a + (1 − w) b regroup x̂ = a + (1 − w)(b − a) name the fraction K = 1 − w = σa² / (σa² + σb²) so x̂ = a + K (b − a) with our numbers K = 4 / 20 = 0.20, x̂ = 10.0 + 0.20 × (14.0 − 10.0) = 10.0 + 0.8 = 10.8

Read it as a sentence. "Start at A. Look at how far B disagrees. Move that way by a fraction K." The fraction K is large when A is unsure and small when A is sure.

In Chapter 4, A will be the filter's prediction, B will be the new measurement, and K will be called the Kalman gain. Nothing else changes.

Where does the product-of-Gaussians picture in the device come from? From Bayes' rule. Sensor A's curve is your belief before you hear from B. Sensor B's curve is the likelihood of B's reading. Bayes says: multiply them, then rescale so the area is one.

Multiplying two exponentials adds their exponents. The exponent is a quadratic in x, so the result is still a Gaussian. Complete the square and its centre and width are exactly the w and the variance above. Here is the algebra with our numbers, so you can see the two routes meet:

exponent of A −(x − 10)² / (2 · 4) = −(x − 10)² / 8 exponent of B −(x − 14)² / (2 · 16) = −(x − 14)² / 32 add them −[ 4(x − 10)² + (x − 14)² ] / 32 expand −[ 4x² − 80x + 400 + x² − 28x + 196 ] / 32 collect −[ 5x² − 108x + 596 ] / 32 complete square −5 [ (x − 10.8)² + … ] / 32 = −(x − 10.8)² / 6.4 + const read off centre 10.8, 2σ² = 6.4 so σ² = 3.2

Same centre, same variance. The weighted average and the Bayesian product are one operation seen from two sides. Here it is as code, in both forms:

pythondef fuse(a, var_a, b, var_b):
    """Fuse two independent Gaussian estimates of the same quantity."""
    K   = var_a / (var_a + var_b)        # how far to move from a toward b
    x   = a + K * (b - a)                # the fused mean
    var = (1 - K) * var_a                # the fused variance (see below)
    return x, var

print(fuse(10.0, 4.0, 14.0, 16.0))     # (10.8, 3.2)

# the precision form gives the same numbers
prec = 1/4.0 + 1/16.0
print(1/prec, (10.0/4.0 + 14.0/16.0) / prec)   # 3.2 10.8

One line in that code deserves a check: the fused variance written as (1 - K) * var_a. With K = 0.2 and var_a = 4 that is 0.8 × 4 = 3.2. Correct. In general, (1 − K)σa² = σa² · σb² / (σa² + σb²), which is the precision formula turned upside down. This compact form is the one the filter uses.

Sensor A has variance 4 and sensor B has variance 16. What weight does the optimal fusion put on A, and why?

Chapter 3

Predict forward

The motion model moves the guess and widens the doubt

Back to the drone. At time zero you know its altitude: 10 m, give or take 1. It climbs at 1 m/s. One second passes, and no new fix has arrived yet. Where is it now, and how sure are you?

The guess is easy. Add the motion: 10 + 1 × 1 = 11 m. We write the new guess x̂−. The small minus means "before this step's measurement". It is also called the prior. Your old guess, after last step's measurement, was the posterior, written with no minus.

The doubt is the interesting part. Your old doubt was sigma 1. The climb was not exactly 1 m. A gust pushed, the motor sagged, the command rounded. Call the unknown nudge's variance q, the process noise. It is the part of the motion your model cannot predict.

Chapter 1's rule says independent variances add. So the new doubt is the old doubt plus q. Your prediction made you less sure, never more.

x̂
Where you believed the drone was after the last fix: 10 m.
v Δt
The modelled motion: velocity times the time step, 1 × 1 = 1 m.
x̂−
The prior, the predicted position before the next fix: 11 m.
P
The variance of your belief after the last fix. From now on the filter's variance is always called P. Here 1.
Q
The process noise variance: how much unmodelled motion one step can add. A number you choose when you build the filter.
P−
The prior variance, always at least as big as P.

Suppose q is 0.5 per step. Predict five steps in a row with no fix in between, and watch the doubt grow:

step P (variance) sigma start 1.00 1.000 1 1.00 + 0.5 = 1.50 √1.50 = 1.225 2 1.50 + 0.5 = 2.00 √2.00 = 1.414 3 2.00 + 0.5 = 2.50 √2.50 = 1.581 4 2.50 + 0.5 = 3.00 √3.00 = 1.732 5 3.00 + 0.5 = 3.50 √3.50 = 1.871

Five predictions nearly doubled the sigma. The variance grows in a straight line. The sigma grows like a square root, fast at first and then slower. This is exactly what you saw in the hero when you cut the GPS for three seconds: the warm ellipse swelled, step by step, until a fix arrived.

Push the guess forward

Each press of Step moves the bell by the modelled motion and widens it by the process noise. Older bells stay behind, faded, so you can see the doubt growing. Try a large q, then a tiny one.

0.5 m² per step

Now the honest version of the problem. We do not know the velocity exactly either. So let the filter estimate both. The thing we track becomes a list of two numbers, the state: position and velocity. We write it as a column vector x = [p, v]. The motion model becomes a small matrix F that takes the old state to the new one:

x̂
The state after the last fix: [position, velocity].
F
The transition matrix. Its first row says: new position = 1 × position + Δt × velocity. Its second row says: new velocity = velocity. Constant velocity, in matrix form.
x̂−
The predicted state. With x̂ = [10, 1] and Δt = 1: [10 + 1, 1] = [11, 1].

And the doubt? It is now a 2 × 2 matrix P, the covariance. Its diagonal holds the two variances: how unsure we are about position, and about velocity. Its off-diagonal holds how the two errors move together. Zero means "knowing one tells you nothing about the other". We will see it stop being zero in a moment.

How does a matrix of doubt go through F? In one dimension, scaling a quantity by a number c scales its variance by c². The matrix version of "c squared" is F on the left and F transposed on the right. Here is why, in one line: the covariance is the average of (error)(error)T. The new error is F times the old error. So the new covariance is the average of F e eT FT, and F comes out of the average on both sides.

F P FT
Push the old covariance through the motion. FT is F flipped across its diagonal. This term moves and stretches the doubt; it never adds any.
Q
The process noise covariance, now a 2 × 2 matrix: how much one step of unmodelled motion disturbs position, velocity, and both together.
P−
The prior covariance, ready for the next fix.

Let us do it with numbers, every multiplication shown. Start with position variance 4 and velocity variance 1, no correlation, and Δt = 1:

F = [ 1 1 ] P = [ 4 0 ] FT = [ 1 0 ] [ 0 1 ] [ 0 1 ] [ 1 1 ] F P row 1: [1·4 + 1·0, 1·0 + 1·1] = [ 4 1 ] row 2: [0·4 + 1·0, 0·0 + 1·1] = [ 0 1 ] (F P) FT row 1: [4·1 + 1·1, 4·0 + 1·1] = [ 5 1 ] row 2: [0·1 + 1·1, 0·0 + 1·1] = [ 1 1 ]

Two things happened. The position variance rose from 4 to 5. Why 5? Because the velocity was uncertain by variance 1, and one second of an uncertain velocity leaks that variance into position: 4 + 1² × 1 = 5.

And a 1 appeared off the diagonal. That is a correlation: if the true velocity was higher than we thought, the true position is now further than we thought, too. The two errors are no longer independent. Hold on to that 1. In Chapter 6 it is how the filter fixes a velocity it never measures.

Now Q. Where does a 2 × 2 process noise come from? From one assumption: during each step, an unknown acceleration a acts, with variance σa². Over Δt it moves position by aΔt²/2 and velocity by aΔt. Write that as a vector [Δt²/2, Δt] times a, and take the outer product times σa²:

G = [ Δt²/2 ] Q = σa² G GT = σa² [ Δt⁴/4 Δt³/2 ] [ Δt ] [ Δt³/2 Δt² ] with Δt = 1, σa² = 0.4: Q = [ 0.1 0.2 ] [ 0.2 0.4 ] P− = F P FT + Q = [ 5 + 0.1 1 + 0.2 ] = [ 5.1 1.2 ] [ 1 + 0.2 1 + 0.4 ] [ 1.2 1.4 ]

This P− is the one we will carry into Chapter 6. Before the code, three things the matrix form lets you see that the one-dimensional form hid.

A known input. The hero drone is commanded. If you know the command, say a climb of 1 m/s, you add it to the prediction of the mean and to nothing else. A known input carries no doubt. The textbook writes this as an extra term:

x̂− = F x̂ + B u (u is the input, B maps it into the state; P− is unchanged)

The time step sets the size of Q. Put the hero's numbers into the Q formula: Δt = 0.1 s and σa = 4 m/s², so σa² = 16.

position term 16 × 0.1⁴ / 4 = 16 × 0.000025 = 0.0004 cross term 16 × 0.1³ / 2 = 16 × 0.0005 = 0.008 velocity term 16 × 0.1² = 16 × 0.01 = 0.16

In a tenth of a second an unknown acceleration barely moves the position, so position gets almost no Q directly. It does change the velocity, so velocity gets most of it. Position then inherits that doubt on later steps through F. This is why Q is written in terms of σa, a physical quantity, and not as four numbers you guess: change Δt and the right Q follows.

Doubt grows faster than linearly when a velocity is uncertain. Predict n steps with no fix and no Q, from P = diag(4, 1). F applied n times is [[1, n], [0, 1]], so the position variance becomes 4 + n² × 1:

steps n 1 2 3 4 5 pos var 4 + 1 4 + 4 4 + 9 4 + 16 4 + 25 = 5 = 8 = 13 = 20 = 29 sigma 2.24 2.83 3.61 4.47 5.39

The variance grows with the square of the number of steps, because an uncertain velocity error is multiplied by the time it has been acting. That is the shape of the swelling ellipse in the hero when the GPS is lost: slow at first, then faster. In the one-dimensional climb, where the velocity was known, the variance only grew in a straight line.

The whole predict step, as code, first with plain lists so you see every product, then with NumPy:

pythonimport numpy as np

# --- by hand, 2x2, no library ---
def mat2(A, B):                       # 2x2 times 2x2
    return [[A[0][0]*B[0][0] + A[0][1]*B[1][0], A[0][0]*B[0][1] + A[0][1]*B[1][1]],
            [A[1][0]*B[0][0] + A[1][1]*B[1][0], A[1][0]*B[0][1] + A[1][1]*B[1][1]]]

def predict_by_hand(x, P, dt, var_a):
    F  = [[1, dt], [0, 1]]
    Ft = [[1, 0], [dt, 1]]
    Q  = [[var_a*dt**4/4, var_a*dt**3/2], [var_a*dt**3/2, var_a*dt**2]]
    x_new = [x[0] + dt*x[1], x[1]]         # F x
    FPFt  = mat2(mat2(F, P), Ft)
    P_new = [[FPFt[i][j] + Q[i][j] for j in range(2)] for i in range(2)]
    return x_new, P_new

x, P = predict_by_hand([10, 1], [[4, 0], [0, 1]], dt=1.0, var_a=0.4)
print(x, P)      # [11, 1]  [[5.1, 1.2], [1.2, 1.4]]

# --- the same thing with NumPy: one line each ---
F = np.array([[1, 1.0], [0, 1]]);  Q = 0.4 * np.array([[0.25, 0.5], [0.5, 1]])
x = F @ np.array([10.0, 1.0])
P = F @ np.diag([4.0, 1.0]) @ F.T + Q
print(x, P)      # [11. 1.]  [[5.1 1.2] [1.2 1.4]]   same answer
Prediction never makes you surer. F P FT rearranges doubt; Q adds doubt. Neither can shrink the total. Only a measurement can do that, and that is the next chapter. If you ever see a filter's P fall during a predict step, the code has a bug.
Position variance is 4, velocity variance is 1, with no correlation. After one second of constant-velocity prediction (before adding Q), what is the position variance, and why?

Chapter 4

The Kalman gain

A trust slider between the prediction and the measurement

The fix arrives. Your prediction said the drone is at 10 m with variance 4. The GPS says 13 m, and this GPS has measurement variance 2. We call that variance R. Two Gaussian guesses of the same thing: this is Chapter 2 again, and nothing new is needed. Sensor A is the prediction. Sensor B is the measurement.

First, name the disagreement. The difference between what you measured and what you expected to measure is the innovation, y = z − x̂− = 13 − 10 = 3. It is the surprise. If the innovation is zero, the fix told you nothing you did not already believe. Here it is 3 m, so something has to move.

How far? Chapter 2 said: move from A toward B by K = σa² / (σa² + σb²). In the filter's names, σa² is P− and σb² is R. This fraction is the Kalman gain:

P−
The prediction's variance, 4. Big P− means "I am not sure where it is", so listen to the sensor.
R
The measurement variance, 2. Big R means "the sensor is noisy", so listen to the prediction.
K
The Kalman gain, a number from 0 to 1. The fraction of the innovation you accept. 0 means ignore the fix; 1 means jump to it.
y
The innovation, z − x̂−: the surprise in the fix, 3 m here.
x̂
The posterior estimate: the prediction, moved toward the fix by K times the surprise.
P
The posterior variance. A fraction (1 − K) of the prior variance. Always smaller than P−, because K is never negative.
gain K = 4 / (4 + 2) = 4 / 6 = 0.667 innovation y = 13 − 10 = 3 estimate x̂ = 10 + 0.667 × 3 = 10 + 2.0 = 12.0 m variance P = (1 − 0.667) × 4 = 0.333 × 4 = 1.333 sigma √1.333 = 1.155 m

The estimate landed at 12, two thirds of the way from the prediction to the fix, because the prediction was twice as uncertain as the fix. And the sigma fell from 2.0 to 1.155. The fix did not just move the guess; it tightened it.

Is two thirds really the best fraction? Drag the slider and find out. The lower panel shows the variance you would end up with for every possible K. There is one bottom to that bowl.

Set the trust by hand

Purple is the prediction, blue is the fix, warm is where your K puts the estimate. Below, the bowl is the posterior variance for every K. Drag K and watch the dot roll. Then press Snap to the best K. Change P− or R and the bottom of the bowl moves.

0.40
4.0
2.0

Here is the bowl as numbers. For any K, the estimate is (1 − K) parts prediction and K parts fix, so by the variance rule its variance is (1 − K)² P− + K² R. Fill in a few values:

K (1−K)²·4 + K²·2 = variance 0.00 4.000 + 0.000 = 4.000 (ignore the fix: keep the prior) 0.30 1.960 + 0.180 = 2.140 0.50 1.000 + 0.500 = 1.500 0.667 0.444 + 0.889 = 1.333 (the bottom of the bowl) 0.80 0.160 + 1.280 = 1.440 1.00 0.000 + 2.000 = 2.000 (jump to the fix: inherit its noise)

At K = 1 you simply believe the GPS, and your variance is the GPS's variance, 2. At K = 0 you ignore it, and you keep the prior's 4. In between, at 0.667, you do better than either: 1.333. That is the same "better than the better source" result from Chapter 2, and it is why the filter is not just a fancy average.

We should check that the shortcut P = (1 − K) P− really is the bottom of the bowl, and not a coincidence of these numbers. Put the optimal K into the bowl formula and simplify:

start (1 − K)² P− + K² R with K = P−/(P−+R), 1 − K = R/(P−+R) substitute R² P− / (P−+R)² + P−² R / (P−+R)² factor P− R (R + P−) / (P−+R)² cancel P− R / (P− + R) rewrite = [ R / (P− + R) ] · P− = (1 − K) P− ✓

Three limits tell you how the gain behaves at the edges. If the sensor is perfect, R goes to zero and K goes to 1: jump straight to every fix. If the sensor is useless, R goes to infinity and K goes to 0: ignore it and coast on the model. If the prediction is perfect, P− goes to zero and K goes to 0 as well: a filter that is certain will not listen. That last limit is the dangerous one, and Chapter 8 is about what happens when the filter is certain and wrong.

Why is it called a gain? In control engineering, a gain is a number that multiplies an error signal to make a correction. The innovation is the error signal. K is the gain on it. What makes this gain special is that it is not a constant someone picked. It is recomputed from P− and R at every step, so it is large right after you lost the GPS and small once you have had many good fixes.

Here is a property that will matter when you have several sensors. Suppose two fixes arrive at the same instant: 13 and 12, each with R = 2. You can fuse them with each other first and then update once, or you can update twice in a row. The answer is the same either way:

one at a time fix 13: K = 4/6 = 0.667, x̂ = 12.000, P = 1.333 fix 12: K = 1.333/3.333 = 0.400, x̂ = 12.000 + 0.4 × (12 − 12) = 12.000, P = 0.6 × 1.333 = 0.800 both at once fuse the fixes: mean 12.5, variance 1/(1/2 + 1/2) = 1 then update: K = 4/5 = 0.800, x̂ = 10 + 0.8 × 2.5 = 12.000, P = 0.2 × 4 = 0.800

Same mean, same variance. Updates commute, because each one is a multiplication of Gaussian curves and multiplication does not care about order. In practice this means a filter with a GPS and a barometer and a compass can process each sensor's reading one after the other with its own small R, instead of building one big stacked measurement. Engineers call this sequential processing, and it is how most real filters are written.

One more thing to notice about the innovation, because Chapter 8 is built on it. If the filter is honest, the surprise should be zero on average. Some fixes land above the prediction and some below, and over a hundred steps they should cancel. A surprise that is always positive means the prediction is always too low: the model is biased, or something in it is wrong. The filter does not check this for you. You can, and you should.

pythondef update(x_prior, P_prior, z, R):
    """One-dimensional Kalman update. Returns the posterior mean and variance."""
    y = z - x_prior                 # innovation: the surprise
    K = P_prior / (P_prior + R)     # gain: how much of the surprise to accept
    x = x_prior + K * y             # move toward the fix by that fraction
    P = (1 - K) * P_prior           # and become surer
    return x, P, K

print(update(10.0, 4.0, z=13.0, R=2.0))      # (12.0, 1.333, 0.667)
print(update(10.0, 4.0, z=13.0, R=0.01))     # (12.99, 0.00998, 0.9975)  near-perfect sensor: jump
print(update(10.0, 4.0, z=13.0, R=400.0))    # (10.03, 3.96, 0.0099)    useless sensor: ignore
print(update(10.0, 0.01, z=13.0, R=2.0))     # (10.015, 0.00995, 0.005) a certain filter will not listen

Compare the last two lines. A useless sensor and a certain filter produce almost the same move: nearly none. From the outside they look alike. From the inside, one is right and one may be very wrong. Keep that in mind for Chapter 8.

Prediction variance is 4 and measurement variance is 2. The fix disagrees with the prediction by 3 m. How far does the estimate move, and why?

Chapter 5

The loop

Predict, update, repeat: eight steps worked by hand

You now own both halves. Predict moves the guess and adds doubt. Update pulls the guess toward the fix and removes doubt. The Kalman filter is nothing more than those two halves, taken in turn, forever. Let us run it by hand, with real numbers, and watch what it settles into.

The scene: the drone climbs at a known 1 m/s, so the state is just its altitude. One step is one second. Process noise Q is 0.5 per step. The altimeter has variance R = 2, so its sigma is 1.41 m. We start sure of nothing much: x̂ = 0 with P = 4. The eight fixes, one per second, are:

z = −0.4, 1.6, 0.4, 2.4, 4.3, 7.7, 6.6, 5.5 (the truth was 1, 2, 3, 4, 5, 6, 7, 8)

Step one, every line. Predict first:

predict x̂− = 0 + 1 = 1.00 P− = 4 + 0.5 = 4.500 gain K = 4.5 / (4.5 + 2) = 4.5 / 6.5 = 0.692 surprise y = −0.4 − 1.00 = −1.40 update x̂ = 1.00 + 0.692 × (−1.40) = 1.00 − 0.969 = 0.03 P = (1 − 0.692) × 4.5 = 0.308 × 4.5 = 1.385

The first fix was a bad one, 1.4 m low. The filter trusted it a lot, K = 0.69, because its own prior was so vague. It landed at 0.03 instead of the true 1. But look at P: it fell from 4 to 1.385 in one step. Now step two:

predict x̂− = 0.03 + 1 = 1.03 P− = 1.385 + 0.5 = 1.885 gain K = 1.885 / 3.885 = 0.485 surprise y = 1.6 − 1.03 = +0.57 update x̂ = 1.03 + 0.485 × 0.57 = 1.03 + 0.28 = 1.31 P = (1 − 0.485) × 1.885 = 0.515 × 1.885 = 0.970

The gain already dropped from 0.69 to 0.49. The filter is becoming harder to push around. Step the device through the remaining six and watch the table fill. Every row is the same five lines.

Run the loop by hand

Step 0 of 8

Press Predict: the purple arrow pushes the guess up by 1 and the band widens. Press Update: the blue fix arrives and the warm estimate moves toward it by K. The table keeps the numbers.

stepx̂−P−Kzyx̂P

Here are all eight rows, so you can check your own arithmetic against them:

stepx̂−P−Kzyx̂Ptruth
11.004.5000.692−0.4−1.400.031.3851
21.031.8850.4851.6+0.571.310.9702
32.311.4700.4240.4−1.911.500.8473
42.501.3470.4032.4−0.102.460.8054
53.461.3050.3954.3+0.843.790.7905
64.791.2900.3927.7+2.915.930.7846
76.931.2840.3916.6−0.336.800.7827
87.801.2820.3915.5−2.306.900.7818

Read the K column top to bottom: 0.692, 0.485, 0.424, 0.403, 0.395, 0.392, 0.391, 0.391. It falls fast, then stops falling. The P column does the same: 1.385 down to 0.781 and then flat. After about five steps the filter has reached a steady state. Each predict adds 0.5 of variance, and each update removes exactly 0.5 again. The two halves balance.

Where will K settle? We can solve for it. At steady state the prior variance after a predict equals the posterior after the update plus Q. Write that as an equation in P− alone:

steady state P− = P + Q = P− R / (P− + R) + Q multiply out P− (P− + R) = P− R + Q (P− + R) expand P−² + P− R = P− R + Q P− + Q R cancel P−R P−² − Q P− − Q R = 0 quadratic P− = ( Q + √(Q² + 4 Q R) ) / 2 numbers = ( 0.5 + √(0.25 + 4.0) ) / 2 = ( 0.5 + 2.062 ) / 2 = 1.281 gain K = 1.281 / (1.281 + 2) = 0.390 posterior P = (1 − 0.390) × 1.281 = 0.781

Those are the numbers in rows 7 and 8. So after it settles, this filter is a very simple machine: predict up by one, then move 39% of the way toward each fix. The steady-state gain depends only on Q and R, not on where you started. A filter that starts with P = 100 and one that starts with P = 1 arrive at the same 0.390 within a few steps.

Change Q and the settled gain changes with it. Here is the same formula for five values of Q, with R held at 2:

Q per stepSteady P−Steady KSteady PWhat the filter believes
0.050.3420.1460.292the model is nearly perfect: take 15% of each fix, average over about 7 steps
0.10.5000.2000.400take a fifth of each fix
0.51.2810.3900.781our run
23.2360.6181.236the model wanders: lean on the fixes
89.6570.8281.657the model is nearly useless: almost follow the sensor

Only the ratio of Q to R matters for K. Double both and the gain is unchanged; only P doubles. That is why tuning is really one knob, how much you trust the model relative to the sensor, even though you write it as two numbers.

Once settled, a Kalman filter with a fixed gain is an old friend in disguise: an exponential moving average. Writing x̂ = (1 − K) x̂− + K z and unrolling it, each past fix contributes with a weight that shrinks by (1 − K) per step. With K = 0.39 the weights are 0.39, 0.24, 0.15, 0.09, … and the effective memory is about 1/K, two or three fixes. The difference from a plain moving average in Chapter 0 is the prediction in between, which removes the lag, and the start-up, where K is large and the filter learns fast. Here is the fixed-gain version next to the real one, so you can see where they agree:

pythondef fixed_gain(zs, x, v, dt, K):
    """The same loop with K frozen. No P at all."""
    out = []
    for z in zs:
        x = x + v * dt                  # predict
        x = x + K * (z - x)             # update with a constant gain
        out.append(round(x, 2))
    return out

print(fixed_gain(zs, x=0.0, v=1.0, dt=1.0, K=0.39))
# [0.45, 1.51, 1.69, 2.58, 3.86, 5.97, 6.82, 6.92]
# Kalman: [0.03, 1.31, 1.50, 2.46, 3.79, 5.93, 6.80, 6.90]
# The early rows differ: the Kalman filter used K = 0.69 and 0.49 while it was still unsure, and that head start
# takes a few steps to fade. By row 6 the two agree within 4 cm, and by row 8 within 2 cm.

Look at step six. The fix said 7.7 when the truth was 6, a 1.7 m error, more than one sigma of the altimeter. The filter did not follow it. It moved 0.39 × 2.91 = 1.14 m, to 5.93, and was off by only 0.07. The steady gain is a shock absorber. It is also why the filter lagged in row eight: the fix said 5.5 for a truth of 8, and the estimate was dragged back to 6.90. A low gain damps noise and also damps truth. Q is where you set that balance, and Chapter 8 is about setting it.

What if a fix is missing? Then you predict and do not update. The variance keeps its Q and adds another:

after step 8 P = 0.781 predict, no fix P− = 0.781 + 0.5 = 1.281 predict again P− = 1.281 + 0.5 = 1.781 predict again P− = 1.781 + 0.5 = 2.281 sigma 1.51, double the settled value next fix arrives K = 2.281 / 4.281 = 0.533 the gain jumps back up, and the fix is believed

This is the hero's "Lose GPS for 3 s" button in numbers. While the GPS is gone, P swells. When a fix returns, K is large again and the filter snaps most of the way to it. The filter does not need to be told the GPS was lost. The arithmetic knows.

pythondef kalman_1d(zs, x, P, v, dt, Q, R):
    """Known velocity v. Each z may be None when the fix is missing."""
    out = []
    for z in zs:
        x, P = x + v * dt, P + Q                 # PREDICT: move and widen
        if z is not None:                       # UPDATE, only when a fix exists
            K = P / (P + R)
            x, P = x + K * (z - x), (1 - K) * P
        out.append((round(x, 2), round(P, 3)))
    return out

zs = [-0.4, 1.6, 0.4, 2.4, 4.3, 7.7, 6.6, 5.5]
for row in kalman_1d(zs, x=0.0, P=4.0, v=1.0, dt=1.0, Q=0.5, R=2.0):
    print(row)
# (0.03, 1.385) (1.31, 0.97) (1.5, 0.847) (2.46, 0.805) (3.79, 0.79) (5.93, 0.784) (6.8, 0.782) (6.9, 0.781)

# the steady state, in closed form
Q, R = 0.5, 2.0
P_minus = (Q + (Q*Q + 4*Q*R) ** 0.5) / 2
print(P_minus, P_minus / (P_minus + R))         # 1.2808  0.3904

Eleven lines, and that is the complete one-dimensional Kalman filter. Everything in the hero is this loop with matrices in place of numbers.

In the eight-step run, the Kalman gain went 0.69, 0.49, 0.42, 0.40, 0.39, 0.39, 0.39. What does it do next, and why?

Chapter 6

Position and velocity together

The full equations, and how the filter fixes a velocity it never measures

The GPS reports position. Nobody measures the drone's velocity. Yet the filter in the hero knows the velocity well enough to coast through a three-second GPS loss. Where does that knowledge come from? From the off-diagonal entry we found in Chapter 3. This chapter shows exactly how.

First we need to say what the sensor sees. The state has two numbers, position and velocity. The fix has one, position. The measurement matrix H picks out the part of the state the sensor can see: H = [1 0]. Multiply H by the state and you get "what the sensor should report if my state were exactly right". That is the expected measurement, H x̂−.

Now the five update equations in their full form. Each one is the Chapter 4 line with matrices in place of numbers. Hover the symbols.

H
What the sensor sees of the state. [1 0] here: position, not velocity. In 1-D it was the number 1.
y
The innovation: the fix minus what you expected the fix to be. Still "the surprise".
S
The innovation covariance: how big a surprise is normal. Your doubt about the measured part, plus the sensor's doubt. In 1-D it was P− + R.
R
The sensor's noise covariance. One number here, since the fix is one number.
K
The gain, now a column: one entry per state. "Doubt about each state, as it relates to the measured part, divided by the normal size of a surprise." In 1-D: P− / (P− + R).
x̂
The posterior state: every entry moves by its own gain times the one surprise.
P
The posterior covariance. I is the identity matrix. In 1-D this was (1 − K) P−.

Now the numbers. Take the prior from the end of Chapter 3: x̂− = [11, 1] and P− = [[5.1, 1.2], [1.2, 1.4]]. The fix says z = 13 with R = 2. Every product:

expected fix H x̂− = 1·11 + 0·1 = 11 surprise y = 13 − 11 = 2 H P− HT picks the top-left entry of P−: 5.1 S 5.1 + 2 = 7.1 P− HT picks the first column of P−: [ 5.1 ] [ 1.2 ] K [ 5.1 / 7.1 ] = [ 0.718 ] gain on position [ 1.2 / 7.1 ] [ 0.169 ] gain on velocity x̂ [ 11 + 0.718 × 2 ] = [ 12.437 ] [ 1 + 0.169 × 2 ] [ 1.338 ]

Look at the second entry of K. It is 0.169, not zero. The fix said nothing about velocity, and yet the velocity estimate rose from 1.000 to 1.338. The reason is the 1.2 in the corner of P−. That entry says: "if my position guess is too low, my velocity guess is probably too low as well". The fix revealed that the position guess was 2 m too low. So the filter raised the velocity too, by the cross-covariance over S: 1.2 / 7.1 of the surprise.

Now the covariance. First the matrix I − K H, then its product with P−:

K H [ 0.718 ] [ 1 0 ] = [ 0.718 0 ] [ 0.169 ] [ 0.169 0 ] I − K H [ 1 − 0.718 0 ] = [ 0.282 0 ] [ 0 − 0.169 1 ] [ −0.169 1 ] P row 1: [ 0.282·5.1 + 0·1.2, 0.282·1.2 + 0·1.4 ] = [ 1.437 0.338 ] row 2: [ −0.169·5.1 + 1·1.2, −0.169·1.2 + 1·1.4 ] = [ 0.338 1.197 ] position sigma √5.1 = 2.258 → √1.437 = 1.199 velocity sigma √1.4 = 1.183 → √1.197 = 1.094 smaller, though velocity was never measured

The velocity doubt fell by 8%. Not much, from one fix. But every fix does it again, and a few seconds later the velocity is pinned down to a fraction of a metre per second. That is how the hero's filter learns the drone's speed from a sensor that only ever reports where it is.

Here is the geometry, which is easier to feel than the algebra. Draw the doubt as an ellipse in the position–velocity plane: the set of states the filter thinks are likely. When position and velocity errors are correlated, the ellipse tilts. A position-only fix is a vertical band in that plane: it says "the position is near here" and nothing about velocity. The update is the overlap of the tilted ellipse and the band. Because the ellipse is tilted, cutting it with a vertical band also cuts its vertical extent. That cut is the velocity getting fixed.

Cut the ellipse

The purple ellipse is the prior doubt in the position–velocity plane. Each predict step tilts it more. The blue band is a fix of position only. Press Measure and the warm ellipse is what survives. Watch its height shrink: that is velocity, never measured, getting surer.

1
13.0 m

Starts from the Chapter 3 numbers: P = diag(4, 1), Δt = 1, process noise 0.4, R = 2. Zero predict steps gives an upright ellipse, and then the fix cannot touch the velocity at all.

Try zero predict steps. The ellipse is upright, the corner of P is 0, the second entry of K is 0, and the fix leaves the velocity exactly where it was. The correlation is not a side effect. It is the only channel through which information reaches an unmeasured state.

Correlation is how unmeasured states get fixed. The predict step couples position to velocity, because a wrong velocity shows up as a wrong position one step later. The update step then uses that coupling backwards: a surprising position implies a surprising velocity. Every state that is linked to a measured state through F gets corrected. That is why a filter with the right F can estimate things no sensor on board can see: velocity from position, bias from drift, wind from ground track.

The full filter in code, general in the size of the state. This is the version you will actually use, and the hero runs its exact twin in JavaScript with a four-entry state.

pythonimport numpy as np

def predict(x, P, F, Q):
    return F @ x, F @ P @ F.T + Q

def update(x, P, z, H, R):
    y = z - H @ x                          # surprise          (m,)
    S = H @ P @ H.T + R                    # normal surprise   (m, m)
    K = P @ H.T @ np.linalg.inv(S)         # gain              (n, m)
    x = x + K @ y                          # every state moves by its own row of K
    P = (np.eye(len(x)) - K @ H) @ P       # and every doubt shrinks
    return x, P, y, S

# the worked example: state [position, velocity], one fix of position
F = np.array([[1.0, 1.0], [0.0, 1.0]])
Q = 0.4 * np.array([[0.25, 0.5], [0.5, 1.0]])
H = np.array([[1.0, 0.0]])
R = np.array([[2.0]])

x, P = predict(np.array([10.0, 1.0]), np.diag([4.0, 1.0]), F, Q)
print(x, P)              # [11. 1.]  [[5.1 1.2] [1.2 1.4]]
x, P, y, S = update(x, P, np.array([13.0]), H, R)
print(x)                 # [12.437  1.338]   velocity moved, though never measured
print(P)                 # [[1.437 0.338] [0.338 1.197]]
print(y, S)              # [2.]  [[7.1]]

Read the shapes in the comments. With n states and m measured quantities, K is n by m: one row per state, one column per sensor channel. The hero has n = 4 and m = 2, so K is 4 by 2. The two velocity rows of that K are never zero, for the reason you just worked through.

Now turn the question around. Suppose the sensor measured velocity only, H = [0 1], and never position. Does the same trick fix the position? Run the loop with R = 0.5 on the velocity and watch the position variance:

step 1 2 5 10 20 40 60 pos var 4.34 4.83 6.32 8.82 13.8 23.8 33.8 grows forever vel var 0.368 0.303 0.290 0.290 0.290 0.290 0.290 settles at once

The velocity settles in a few steps. The position variance never stops growing, about 0.5 per step. Each fix tells the filter how fast it is going, and the correlation does pass a little of that into position, which is why the first step dropped it from 5.1 to 4.34. But nothing ever says where it is. Knowing your speed perfectly does not tell you where you started, and the error in where you started never goes away. Position is unobservable from velocity alone. Velocity is observable from position alone, because position is the integral of velocity and the filter can undo an integral by watching the position change. The arrow of correlation only runs one way.

This is the practical test for any filter you design. For each state, ask: is there a chain through F from this state to something H sees? If not, its variance will grow without bound, its gain will do nothing useful, and the filter will quietly report a number it has no right to. Add a sensor that sees it, or remove it from the state.

The sensor measures position only, with H = [1 0]. Why does the velocity estimate change at the update step?

Chapter 7

The tracker

The full two-dimensional filter from the hero, with every knob exposed

Now build the thing you played with at the top of the page. The drone moves on a plane, so the state is four numbers: two positions and two velocities, x = [px, py, vx, vy]. The GPS reports two: z = [zx, zy]. Everything else is Chapter 6, with the matrices one size bigger:

F = [ 1 0 Δt 0 ] H = [ 1 0 0 0 ] R = [ σz² 0 ] [ 0 1 0 Δt ] [ 0 1 0 0 ] [ 0 σz² ] [ 0 0 1 0 ] [ 0 0 0 1 ] Q = σa² · [ Δt⁴/4 0 Δt³/2 0 ] the Chapter 3 block, once per axis [ 0 Δt⁴/4 0 Δt³/2 ] [ Δt³/2 0 Δt² 0 ] [ 0 Δt³/2 0 Δt² ]

Follow one fix through the machine, with shapes. The state is a 4-vector and P is 4 × 4. Predict: F x̂ is a 4-vector, F P FT + Q is 4 × 4. The fix z is a 2-vector. The surprise y = z − H x̂− is a 2-vector. S = H P− HT + R is 2 × 2: the top-left block of P− plus R. K = P− HT S−1 is 4 × 2: the first two columns of P−, times the inverse of S. Then x̂ moves by K y, a 4-vector, and P shrinks by (I − K H). Ten steps per second, forever.

Here is that same step as a table of shapes, which is how you will debug a filter in practice. Every line is one matrix product, and the shapes must chain:

QuantityShapeComputed fromCost per step
x̂−4F (4×4) · x̂ (4)16 multiplies
P−4×4F P FT + Qtwo 4×4 products
y2z (2) − H (2×4) · x̂− (4)trivial: H just picks entries
S2×2H P− HT + R = top-left block of P− + Rtwo additions
K4×2P− HT (first two columns of P−) · S−1one 2×2 inverse
x̂4x̂− + K (4×2) · y (2)8 multiplies
P4×4(I − K H) P−one 4×4 product

The whole step is a few hundred multiplications. That is why Kalman filters run at kilohertz rates on the smallest microcontrollers, and why the Apollo guidance computer, with about 4 kB of memory, could run one in 1969. The only matrix ever inverted is S, and it is the size of the measurement, not the state.

Two knobs set the filter. σz is how noisy you tell it the GPS is. σa is how hard you tell it the drone can accelerate between fixes. The device lets you set both, and separately lets you choose how the drone really moves, so you can lie to the filter on purpose and watch what the lie costs.

Run the tracker

Stopped

Grey dashed is the truth, blue dots are GPS fixes, the purple tick is the prediction before each fix, warm is the estimate with its two-sigma ellipse. Choose a path, set the noises, then play. Turn layers off to see each one alone.

4.0 m
4.0 m/s²

The drone flies at 8 m/s; the weave turns at up to 0.4 rad/s, the zigzag snaps its heading every 4 s. Errors are root-mean-square over the last 10 s. "Claimed" is the filter's own position sigma, from the diagonal of P. When claimed is much smaller than actual, the filter is lying to you; Chapter 8 is about catching that.

Five experiments, in order. Each one teaches a different thing, and each is a minute of play.

  1. Raise the GPS noise to 10 m. The dots scatter wildly. The warm track stays smooth, and the ellipse grows to match. The read-out shows the filter cutting the raw error roughly in half: on the weave, about 14 m of GPS error becomes about 7.5.
  2. Drop σa to 0.3 on the weave. You have told the filter the drone cannot turn. It believes you. The estimate cuts the corners, the error climbs to around 10 m, and the ellipse stays tiny. Claimed sigma 0.5 m, actual error 10 m. This is a filter that is certain and wrong.
  3. Raise σa to 20. Now you have told it the drone can jump anywhere. It stops trusting its own prediction and follows every GPS wobble. The track is honest about its doubt, but it is barely better than the raw fixes.
  4. Lose the GPS for 3 s. The ellipse swells step by step, exactly as in Chapter 3, and the estimate coasts on the last velocity. On the straight path it coasts almost perfectly. On the weave it leaves the truth, and when the GPS returns the large gain snaps it back.
  5. Straight path, σa = 0.5. The model is nearly exact, so the filter can trust it hard. The error falls well below 1 m from fixes that are 5.7 m off. This is the best case: a good model lets you average over a long memory without lag.

Here are the numbers behind the first experiment, measured over many runs of this exact simulation on the weave with σa = 4. The filter's gain is about half the raw error at every noise level, because the weave limits how much the constant-velocity model can help:

GPS noise σz, per axisRaw fix error (RMS distance)Kalman error (RMS distance)Ratio
1 m1.4 m0.9 m0.64
2 m2.9 m1.8 m0.63
4 m5.7 m2.6 m0.46
6 m8.6 m5.0 m0.58
10 m14.3 m7.5 m0.52

Notice the raw error is 1.41 times σz. That is Chapter 1 again: two independent axes with sigma 4 give a distance error with sigma √(4² + 4²) = 5.66. And notice the ratio is not constant. At small noise the GPS is already good and the model adds little; at large noise the model does most of the work.

How does the filter start? It has no idea where the drone is or how fast it moves. We set the first state to the first fix with zero velocity, and the covariance to something honest: σz² for position and 100 for velocity, a velocity sigma of 10 m/s. Because P is large, the first gains are near 1 and the filter believes the first few fixes almost completely. Within a second or two, the velocity rows of P have collapsed and the track settles. Starting with a small P would be a lie, and Chapter 8 shows what lies cost.

pythonimport numpy as np

class Tracker2D:
    """Constant-velocity Kalman filter: state [px, py, vx, vy], measures [px, py]."""
    def __init__(self, z0, dt, sigma_z, sigma_a):
        self.dt = dt
        self.x = np.array([z0[0], z0[1], 0.0, 0.0])          # first fix, velocity unknown
        self.P = np.diag([sigma_z**2, sigma_z**2, 100.0, 100.0])  # honest: velocity sigma 10 m/s
        self.F = np.array([[1, 0, dt, 0], [0, 1, 0, dt], [0, 0, 1, 0], [0, 0, 0, 1]], float)
        self.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], float)
        self.R = np.eye(2) * sigma_z**2
        q4, q3, q2 = dt**4/4, dt**3/2, dt**2
        self.Q = sigma_a**2 * np.array([[q4, 0, q3, 0], [0, q4, 0, q3], [q3, 0, q2, 0], [0, q3, 0, q2]])

    def predict(self):
        self.x = self.F @ self.x
        self.P = self.F @ self.P @ self.F.T + self.Q

    def update(self, z):
        y = z - self.H @ self.x
        S = self.H @ self.P @ self.H.T + self.R
        K = self.P @ self.H.T @ np.linalg.inv(S)
        self.x = self.x + K @ y
        self.P = (np.eye(4) - K @ self.H) @ self.P
        return y @ np.linalg.solve(S, y)          # the NIS, for Chapter 8

# one second of tracking: ten predict/update cycles, with one lost fix
rng = np.random.default_rng(0)
truth = np.array([0.0, 0.0]); vel = np.array([8.0, 0.0])
kf = Tracker2D(truth + rng.normal(0, 4, 2), dt=0.1, sigma_z=4.0, sigma_a=4.0)
for k in range(10):
    truth = truth + vel * 0.1
    kf.predict()
    if k != 5:                                     # fix number 5 is lost: predict only
        kf.update(truth + rng.normal(0, 4, 2))
    print(k, np.round(kf.x, 2), "pos sigma %.2f" % np.sqrt(kf.P[0, 0]))

Run it and watch the printed position sigma: it drops fast over the first fixes, rises at k = 5 when the fix is lost, and falls again at k = 6. The JavaScript behind the device is a line-for-line port of this class, with the 2 × 2 inverse written out by hand.

What the tracker does when its inputs degrade, because that is what separates a demo from a system:

On the weaving path you set the filter's σa to 0.3, far below how hard the drone really turns. What do you see?

Chapter 8

Tuning and breaking it

Q, R, the consistency check, and the ways a filter lies

The filter never sees the truth. It only sees fixes, and the two noise budgets you gave it, Q and R. Everything it claims about its own accuracy comes from those two. So the practical questions are: where do Q and R come from, and how do you know when they are wrong?

R is the easy one. It is a property of the sensor, and you can measure it. Put the receiver on a known point, log a thousand fixes, and compute the variance exactly as in Chapter 1. Most data sheets also quote it. If the sensor's noise changes with conditions, as GPS does under trees, let R change with it: a filter accepts a different R on every step.

python# measuring R on the bench: a thousand fixes from a receiver that is not moving
fixes = np.loadtxt("static_gps.csv", delimiter=",")      # shape (1000, 2): east, north in metres
centred = fixes - fixes.mean(axis=0)                        # remove the (unknown) true point
R = np.cov(centred.T)                                       # 2x2: variances on the diagonal, their correlation off it
print(np.sqrt(np.diag(R)))                                  # e.g. [3.9 4.2]: sigma per axis
print(R[0, 1] / np.sqrt(R[0, 0] * R[1, 1]))                     # correlation between axes, often near 0

Q is the hard one. It is not a property of a sensor. It is your budget for what the model leaves out. A physical argument gets you close: if the drone can pull at most about 8 m/s², then an unknown acceleration with sigma of about half that, 4 m/s², is a reasonable guess. Then you check. And the check does not need the truth.

Here is the check. If the filter is honest, each surprise y should be a draw from a Gaussian with mean zero and covariance S. The filter computed S itself: it is the filter's own claim about how big a normal surprise is. So square the surprise in units of S. That number is the normalised innovation squared, the NIS:

y
The surprise on this step. A 2-vector in the tracker.
S−1
The inverse of the filter's claimed surprise covariance. Dividing by S turns metres into "how many sigmas".
NIS
The surprise, squared, in sigmas. In 1-D it is simply y² / S. If the filter is honest, NIS averages m, the number of measured quantities, and stays under a known line 95% of the time: 3.84 in 1-D, 5.99 in 2-D.

Those 95% lines come from the chi-squared distribution with m degrees of freedom, the distribution of a sum of m squared standard Gaussians. You do not need to derive them; you need to use them. One NIS value says little. A few hundred say everything. Count how many fall under the line:

What you told the filterNIS under the 95% lineMean NIS (should be 2)Verdict
R ten times too small26%20.1badly overconfident
R four times too small50%8.6overconfident
R correct, Q correct93%2.1consistent
R four times too large100%1.0underconfident
Q a hundred times too small46%8.5overconfident
Q ten times too large95%2.0consistent, but noisier than it needs to be

These were measured on the weave with the Chapter 7 tracker. Even the correct settings give 93%, not 95%, because the constant-velocity model is a slight lie about a drone that turns. That small shortfall is itself information: the model is a little too stiff. The device lets you dial each lie and watch the NIS trace react.

Audit the filter

Each dot is one step's NIS. The line is the 95% level, 5.99. Tell the filter the GPS is cleaner or dirtier than it really is, or that the drone is stiffer or looser than it really is, then press Run 50 s. An honest filter keeps about one dot in twenty above the line.

1.0×
1.0×

"True Q" here means σa = 4 on the weave, the setting that audits as consistent in Chapter 7. The sliders are logarithmic: the middle is 1×, the ends are 0.1× and 10× (R) or 0.01× and 10× (Q).

Two shapes of failure, and you have now seen both. Overconfident: P is too small, because Q or R or the starting P was set too small. The gain is small, the filter ignores fixes, the estimate drifts, and the NIS trace climbs above the line and stays there. In the worst case the gain goes to zero and the filter stops learning at all, confidently tracking a drone that left long ago. This is called divergence. Underconfident: P is too big, because Q is too generous. The filter trusts every fix too much, the estimate is noisy, and the NIS trace hugs the floor. You waste information, but you never lose the drone.

That asymmetry gives the one tuning rule worth memorising. If you must err, err toward a larger Q. An underconfident filter is noisy. An overconfident filter is wrong. Noise you can see. Wrong you cannot, until the NIS tells you.

A diagnosis table, from the symptoms you can observe without the truth to the knob that fixes them:

SymptomLikely causeFix
NIS mostly above the line; estimate drifts away from the fixesP too small: Q or R or the initial P too smallraise Q first; check R against the bench
NIS all near zero; estimate follows every fix wobbleP too big: Q too generouslower Q until NIS reaches about 95%
Innovations have a nonzero meana bias in the sensor or the model, or a wrong Δtadd the bias to the state; timestamp the fixes
Innovations are fine on the straight, bad in the turnsthe motion model is too stiffraise Q, or change the model (EKF, turning model)
Rare huge NIS values; otherwise fineoutliers in the sensorgate at 3 sigma
P goes negative or the gain explodes after a long runnumerical driftJoseph form; symmetrise P

You can even let the filter estimate R for itself. The innovations have covariance S = H P− HT + R, and the filter knows the first term. So average the observed y yT over a window and subtract it:

R̂ ≈ mean( y yT ) − H P− HT (over the last few hundred steps)

This is the seed of the adaptive Kalman filter, which has its own lesson in the links at the end. Use it with care: a window too short chases noise, and if the model is also wrong the blame lands on R where it does not belong.

The NIS also gives you a gate. A single fix with an enormous NIS is not a normal surprise. On a GPS, it is usually multipath: a signal bounced off a building. Reject it:

prior x̂− = 11, P− = 5.1, R = 2, so S = 7.1 a normal fix z = 13: y = 2, NIS = 2² / 7.1 = 4 / 7.1 = 0.56 accept a bounced fix z = 20: y = 9, NIS = 9² / 7.1 = 81 / 7.1 = 11.4 above 9 (the 99.7% line): reject, predict only

This is the innovation gate, and every real tracker has one. Be careful with it, though. A gate that is too tight will reject the very fixes that would have corrected a drifting filter, and then the filter diverges with a clean conscience. Gate at three sigmas, not two, and if you reject several fixes in a row, suspect the filter before the sensor.

Other ways the filter lies, and what to do about each:

pythonimport numpy as np
from scipy.stats import chi2

def nis(y, S):
    return float(y @ np.linalg.solve(S, y))

def audit(nis_values, m):
    """Fraction of steps under the 95% line, and the mean. Honest: ~0.95 and ~m."""
    line = chi2.ppf(0.95, df=m)                 # 3.84 for m=1, 5.99 for m=2
    v = np.asarray(nis_values)
    return (v < line).mean(), v.mean()

def update_gated(kf, z, gate=9.0):
    """Reject a fix whose surprise is beyond ~3 sigma (chi2 with 1 dof: 9 is 99.7%)."""
    y = z - kf.H @ kf.x
    S = kf.H @ kf.P @ kf.H.T + kf.R
    if nis(y, S) > gate * len(y):             # scale the gate by the measurement size
        return False                           # skip: the predict step already ran
    kf.update(z)
    return True

# Joseph form: the same P, kept symmetric and positive under rounding
def joseph(P, K, H, R):
    I_KH = np.eye(len(P)) - K @ H
    return I_KH @ P @ I_KH.T + K @ R @ K.T
The filter cannot tell you it is wrong. Its surprises can. P is a claim the filter makes about itself, computed from the numbers you gave it. The innovations are the only place the real world touches the filter. If their size matches the claim, trust P. If it does not, P is fiction, and the smaller it is, the more dangerous the fiction.
Over a long run, only 50% of a filter's NIS values fall under the 95% line, and their mean is 8. What is wrong, and which way should you adjust?

Chapter 9

Beyond

The cheat sheet, the code, and where EKF, UKF and SLAM pick up

Here is the whole lesson in one paragraph. Every quantity gets a mean and a variance. Variances add when you predict and precisions add when you measure. The gain is the prediction's doubt over the total doubt, and the estimate moves toward each fix by that fraction. With a state vector, the predict step couples the states through F, and the update step uses that coupling to correct states no sensor sees. The innovations are the audit. That is the Kalman filter.

Why is it the best you can do, and not just a good idea? Because under its assumptions it is the exact Bayes filter. A Bayes filter carries a whole probability distribution over the state, pushes it through the motion model, and multiplies it by the likelihood of each measurement. If the starting belief is Gaussian, the motion is linear with Gaussian noise, and the sensor is linear with Gaussian noise, then the belief stays Gaussian forever, and the two numbers the filter carries are the belief. Nothing is thrown away. The posterior mean is the estimate with the smallest possible expected squared error, and the posterior covariance is its true spread. Drop the Gaussian assumption and the filter is still the best linear estimator, which is why it works so well even when the noise is only roughly a bell.

Every equation, in one place

StepEquationIn wordsChapter
Predict meanx̂− = F x̂Push the guess through the motion model.3
Predict covarianceP− = F P FT + QPush the doubt through the motion, then add the model's own doubt.3
Innovationy = z − H x̂−The surprise: what you saw minus what you expected to see.4, 6
Innovation covarianceS = H P− HT + RHow big a surprise is normal.6
GainK = P− HT S−1Prediction doubt over total doubt, per state.4, 6
Update meanx̂ = x̂− + K yMove toward the fix by the gain's fraction of the surprise.4
Update covarianceP = (I − K H) P−Become surer, in proportion to the gain.4
AuditNIS = yT S−1 yShould average m and stay under the 95% line 19 times in 20.8
SymbolShapeMeaningWho sets it
x̂nThe state estimate: everything you track.the filter
Pn × nThe covariance: variances on the diagonal, correlations off it.the filter (you give the start)
Fn × nThe motion model over one step.you, from physics
Qn × nProcess noise: what the motion model leaves out.you, then audit
Hm × nWhat the sensor sees of the state.you, from the sensor
Rm × mMeasurement noise.you, measured on the bench
zmOne measurement.the sensor
Kn × mThe gain: never set by hand.the filter, every step

The core, as code

pythonimport numpy as np

class KalmanFilter:
    """Linear Kalman filter. n states, m measurements. Every symbol as in the cheat sheet."""
    def __init__(self, x0, P0, F, Q, H, R):
        self.x, self.P = np.array(x0, float), np.array(P0, float)
        self.F, self.Q, self.H, self.R = (np.array(M, float) for M in (F, Q, H, R))

    def predict(self, F=None, Q=None):
        F = self.F if F is None else F        # pass a fresh F when dt changes
        Q = self.Q if Q is None else Q
        self.x = F @ self.x
        self.P = F @ self.P @ F.T + Q
        return self.x, self.P

    def update(self, z, R=None, gate=None):
        R = self.R if R is None else R        # pass a fresh R when the sensor's quality changes
        y = z - self.H @ self.x
        S = self.H @ self.P @ self.H.T + R
        nis = float(y @ np.linalg.solve(S, y))
        if gate is not None and nis > gate:
            return nis                           # rejected: keep the prior
        K = self.P @ self.H.T @ np.linalg.inv(S)
        self.x = self.x + K @ y
        I_KH = np.eye(len(self.x)) - K @ self.H
        self.P = I_KH @ self.P @ I_KH.T + K @ R @ K.T   # Joseph form
        return nis

# the Chapter 5 run, through the general class: same eight numbers
kf = KalmanFilter(x0=[0.0], P0=[[4.0]], F=[[1.0]], Q=[[0.5]], H=[[1.0]], R=[[2.0]])
for z in [-0.4, 1.6, 0.4, 2.4, 4.3, 7.7, 6.6, 5.5]:
    kf.x = kf.x + 1.0                                 # the known 1 m/s climb (a control input)
    kf.predict()
    kf.update(np.array([z]))
    print(round(float(kf.x[0]), 2), round(float(kf.P[0, 0]), 3))
# 0.03 1.385 / 1.31 0.97 / 1.5 0.847 / 2.46 0.805 / 3.79 0.79 / 5.93 0.784 / 6.8 0.782 / 6.9 0.781

One addition in that code deserves a word: the climb is added to x before the predict. A known input, like a commanded velocity or a measured acceleration, enters the predict step as an extra term, B u, where u is the input and B maps it into the state. It changes the mean and nothing else, because a known input carries no doubt. Everything on this page still holds.

Where it sits, and what comes next

The Kalman filter is one member of a family. Each relative drops one assumption, and each pays for it.

FilterWhat it dropsHowWhat it costs
Kalmannothingtwo numbers, closed formlinear, Gaussian only
Extended Kalman (EKF)linear F and Hlinearise around the current estimate with Jacobianscan diverge when the curve is sharp; P is only approximate
Unscented Kalman (UKF)linear F and Hpush a handful of chosen points through the real functions, refit a Gaussiana few times the compute; still a Gaussian
Particle filterGaussian beliefthousands of weighted samplescompute grows fast with the state size
Information filternothingcarries precision instead of covariancesame answer; measurements add, predictions get costly
RTS smootherthe "now" constraintruns the filter forward, then sweeps backward using later fixesneeds the whole record; not real time
SLAMa known mapputs landmark positions into the state next to the robotthe state grows with the map

Two of those deserve a line each, because the hero already pointed at them. The extended Kalman filter is what you reach for when the drone turns: it keeps the same five update lines but recomputes F and H every step as the local slope of the real motion and sensor functions. The smoother is what you run after the flight: a backward pass that lets the fix at second 20 improve the estimate at second 19, which no real-time filter can do. In the Chapter 5 table, a smoother would have pulled row 8 back toward 8, because it would know row 9 and row 10.

Here is how little changes for the EKF. The motion becomes a function f(x) and the sensor a function h(x). Their slopes, the Jacobian matrices, stand in for F and H in the covariance lines only. The means use the real functions:

python# EKF: the same five lines, with f and h as functions and their Jacobians where F and H were
def ekf_predict(x, P, f, F_jac, Q):
    return f(x), F_jac(x) @ P @ F_jac(x).T + Q          # mean through f, covariance through its slope

def ekf_update(x, P, z, h, H_jac, R):
    H = H_jac(x)
    y = z - h(x)                                          # the surprise uses the real sensor function
    S = H @ P @ H.T + R
    K = P @ H.T @ np.linalg.inv(S)
    return x + K @ y, (np.eye(len(x)) - K @ H) @ P

# a drone that turns: state [px, py, speed, heading], f integrates along the heading
def f(x, dt=0.1):
    px, py, v, th = x
    return np.array([px + v*np.cos(th)*dt, py + v*np.sin(th)*dt, v, th])
def F_jac(x, dt=0.1):
    px, py, v, th = x
    return np.array([[1, 0, np.cos(th)*dt, -v*np.sin(th)*dt],
                     [0, 1, np.sin(th)*dt,  v*np.cos(th)*dt],
                     [0, 0, 1, 0],
                     [0, 0, 0, 1]])

And the smoother, in its two lines. After the forward filter has stored every x̂k, Pk, x̂−k+1 and P−k+1, sweep backward from the last step:

Ck = Pk FT (P−k+1)−1   x̂k|N = x̂k + Ck ( x̂k+1|N − x̂−k+1 )

Ck is a gain again, now on the difference between what the future turned out to be and what the filter had predicted for it. It is the same idea as K, pointed backward in time: a surprise about the future corrects the past. If the hero recorded a flight and ran this afterward, every point of the track would use fixes from both sides of it, and the error would fall below what any real-time filter can reach.

Keep going

The takeaway. The Kalman filter is not a trick for smoothing noisy data. It is the arithmetic of doubt: carry a doubt with every guess, let prediction grow it and measurement shrink it, and let the ratio of the two decide every correction. Everything else on this page, the matrices, the ellipse, the gain, the audit, is that one sentence with the details filled in.
Your drone now flies tight circles, and its motion depends on its heading in a way no constant F can express. Which change keeps the predict–update loop and fixes the model?

Now press Present or Teach and explain, out loud and from memory, why the velocity changes when only the position is measured. If you can, you own this filter. Then go back to the drone, cut the GPS, and watch the ellipse grow with the numbers you now know.

The Kalman filter
Back to Gleams