AnyLearn
All lessons
Roboticsadvanced

The Kalman filter: optimal state estimation from noisy measurements

How the Kalman filter fuses a motion model with noisy measurements by carrying a Gaussian belief, growing uncertainty on predict and shrinking it on update, weighting the two by the Kalman gain, plus the EKF and UKF for nonlinear systems.

Not signed in: your progress and quiz score won't be saved.
Progress1 / 12

The problem: a hidden state you can only glimpse

You want to know the true state of a system, say the position and velocity of a drone, but you cannot measure it directly or cleanly. You have two imperfect sources. First, a motion model that predicts how the state evolves, which drifts because the world is messier than the model. Second, measurements (GPS, a range sensor) that are noisy and often incomplete.

Neither source alone is good enough: the model drifts without correction, and the raw measurements jitter. The Kalman filter is the recipe for fusing them into an estimate that is better than either. Its core move is to track not just a best guess but an explicit measure of how uncertain that guess is, and to let that uncertainty decide how much to trust each new measurement.

Full lesson text

All 12 steps on one page, for reading, reference, and search.

Show

1. The problem: a hidden state you can only glimpse

You want to know the true state of a system, say the position and velocity of a drone, but you cannot measure it directly or cleanly. You have two imperfect sources. First, a motion model that predicts how the state evolves, which drifts because the world is messier than the model. Second, measurements (GPS, a range sensor) that are noisy and often incomplete.

Neither source alone is good enough: the model drifts without correction, and the raw measurements jitter. The Kalman filter is the recipe for fusing them into an estimate that is better than either. Its core move is to track not just a best guess but an explicit measure of how uncertain that guess is, and to let that uncertainty decide how much to trust each new measurement.

2. Two models: how the state moves, how it is seen

The classic Kalman filter assumes both models are linear with Gaussian noise. The state xx (say position and velocity) evolves as

xk=Fxk1+Buk+w,wN(0,Q)x_k = F\,x_{k-1} + B\,u_k + w,\qquad w \sim \mathcal{N}(0, Q)

Here FF is the transition matrix (how the state carries forward), BukB\,u_k is any known control input, and QQ is the process noise covariance, how much the model itself is untrustworthy.

Measurements relate to the state through

zk=Hxk+v,vN(0,R)z_k = H\,x_k + v,\qquad v \sim \mathcal{N}(0, R)

HH maps state to what the sensor sees (a GPS sees position, not velocity), and RR is the measurement noise covariance. Choosing FF, HH, QQ, and RR is the modelling work; the rest of the filter is mechanical.

3. The belief is a Gaussian: a mean and a covariance

The filter never commits to a single number. It carries a Gaussian belief about the state: a mean x^\hat{x} (the current best estimate) and a covariance matrix PP (how uncertain that estimate is, and how the components' errors correlate).

Think of PP as an uncertainty ellipse around x^\hat{x}. A tight ellipse means confident; a wide one means unsure. Everything the Kalman filter does is move this ellipse and resize it:

  • Predict slides the ellipse along the motion model and inflates it (we get less sure over time).
  • Update pulls the ellipse toward a new measurement and shrinks it (a measurement buys certainty).

Because a Gaussian is fully described by its mean and covariance, tracking just x^\hat{x} and PP is enough to represent the entire probability distribution over the state.

4. Predict: push the belief forward

Between measurements, the filter runs the motion model on its belief. The mean moves forward and the covariance grows by the process noise:

xˉk=Fx^k1+Buk\bar{x}_k = F\,\hat{x}_{k-1} + B\,u_k Pˉk=FPk1F+Q\bar{P}_k = F\,P_{k-1}\,F^\top + Q

The bar denotes a prior (before seeing the new measurement). The first line is just the model applied to the last estimate. The second is the important one: transforming the old uncertainty through FF (the FPFF P F^\top term), then adding QQ.

That added QQ is why prediction always makes you less certain: the ellipse inflates. Run predict many times with no measurements and PP blows up, which correctly says the estimate is now mostly a guess. This is dead reckoning, and it is exactly what the update step exists to rein in.

5. The predict-update cycle

Predict grows the uncertainty; a measurement and the Kalman gain shrink it. Repeat.

flowchart TD
A["Start: belief (x-hat, P)"] --> B["PREDICT: x-bar = F x-hat, P-bar = F P F-transpose + Q (uncertainty grows)"]
B --> C["New measurement z arrives"]
C --> D["Innovation: y = z minus H x-bar"]
D --> E["Kalman gain: K = P-bar H-transpose times S-inverse"]
E --> F["UPDATE: x-hat = x-bar + K y, P = (I minus K H) P-bar (uncertainty shrinks)"]
F --> B

6. Update, part 1: the innovation

A measurement zkz_k arrives. The filter first asks: how surprised am I? It compares the actual measurement to what its prediction expected to see, HxˉkH\,\bar{x}_k. The difference is the innovation (or measurement residual):

yk=zkHxˉky_k = z_k - H\,\bar{x}_k

If yky_k is near zero, the measurement agrees with the prediction and little correction is needed. A large yky_k means a surprise worth acting on.

How much a given surprise should move the estimate depends on how uncertain both sides are. That combined uncertainty is the innovation covariance:

Sk=HPˉkH+RS_k = H\,\bar{P}_k\,H^\top + R

SkS_k blends the predicted uncertainty (mapped into measurement space by HH) with the sensor noise RR. It is the denominator that keeps the correction properly scaled.

7. Update, part 2: the Kalman gain

The Kalman gain is the heart of the algorithm. It decides how much of the innovation to actually apply:

Kk=PˉkHSk1K_k = \bar{P}_k\,H^\top\,S_k^{-1}

Read it as a ratio of confidences. The numerator carries the prediction's uncertainty Pˉk\bar{P}_k; the denominator SkS_k carries the total uncertainty including the sensor noise RR. So:

  • Prediction very uncertain (Pˉk\bar{P}_k large) or sensor very precise (RR small) → KK large → trust the measurement, move a lot.
  • Prediction confident or sensor noisy (RR large) → KK small → mostly ignore the measurement, trust the model.

The gain is recomputed every step from the current uncertainties, so the filter automatically leans on whichever source is currently more trustworthy. No manual tuning of "how much to believe the sensor" is needed once QQ and RR are set.

8. Update, part 3: apply the correction

With the gain in hand, the correction is a weighted step toward the measurement, and the uncertainty shrinks:

x^k=xˉk+Kkyk\hat{x}_k = \bar{x}_k + K_k\,y_k Pk=(IKkH)PˉkP_k = (I - K_k H)\,\bar{P}_k

The mean moves from the prior xˉk\bar{x}_k by the gain times the surprise. The covariance contracts: (IKkH)(I - K_k H) is between 0 and 1 in the relevant directions, so a measurement always reduces uncertainty (or leaves it unchanged if the gain is zero).

That is the whole loop. Predict inflates PP; update deflates it. In steady state the two balance, and PP settles to a value where each new measurement buys exactly as much certainty as the next prediction step loses. The estimate then tracks the true state as tightly as the noise allows.

9. One step, in code

The five equations are just matrix algebra. A single predict-plus-update step:

import numpy as np

def kalman_step(x, P, F, Q, H, R, z, B=None, u=None):
    # --- predict ---
    x = F @ x + (B @ u if u is not None else 0)   # mean forward
    P = F @ P @ F.T + Q                            # uncertainty grows
    # --- update ---
    y = z - H @ x                                  # innovation (residual)
    S = H @ P @ H.T + R                            # innovation covariance
    K = P @ H.T @ np.linalg.inv(S)                 # Kalman gain
    x = x + K @ y                                  # corrected mean
    P = (np.eye(len(x)) - K @ H) @ P               # uncertainty shrinks
    return x, P

Call it once per timestep with the latest measurement z. Everything the filter "knows" lives in x and P; there is no history to store. That recursive, constant-memory structure is a big part of why the Kalman filter runs happily on tiny embedded hardware.

10. Why it works, and the fine print

For a system that really is linear with Gaussian noise, the Kalman filter is not just reasonable, it is optimal: among all estimators it minimizes the mean-squared error, and it exactly tracks the true Bayesian posterior over the state. It is also recursive: it needs only the previous estimate, not the full measurement history, so cost and memory stay constant per step.

The assumptions are the fine print, and they bite:

  • Linearity. Real dynamics and sensors are often nonlinear (angles, ranges, perspective).
  • Gaussian noise. Heavy tails or outliers (a GPS multipath spike) violate this and can yank the estimate.
  • Known QQ and RR. These are usually guessed and tuned; wrong values make the filter over- or under-trust its sensors.

When these hold, the filter is beautiful. When they do not, you reach for a variant.

11. When the world is nonlinear: EKF and UKF

Most real navigation is nonlinear, so two variants dominate:

FilterHandlesHowCaveat
Kalman (KF)linear + Gaussianexact predict/updateoptimal, but linear only
Extended (EKF)nonlinearlinearize with Jacobians around the current estimatecheap and standard; can diverge if nonlinearity is strong
Unscented (UKF)nonlinearpush a set of sigma points through the true nonlinear functionno Jacobians, captures mean and covariance more accurately; a bit more compute

The EKF replaces FF and HH with their Jacobians (local linear approximations) at each step, then runs the ordinary equations. The UKF skips linearization entirely: it samples a few carefully chosen points, transforms them through the real function, and reassembles a Gaussian. UKF is usually more accurate on sharp nonlinearities; EKF is lighter and often good enough. Both keep the exact same predict-update skeleton.

12. The durable mental model

Strip away the matrices and one idea remains: keep a Gaussian belief about a hidden state; predict it forward while growing the uncertainty, correct it with each measurement while shrinking the uncertainty, and weight the two by their relative confidence. The Kalman gain is just that weighting made precise.

That framing is why the filter is everywhere: GPS and inertial (IMU) sensor fusion, robot localization and SLAM, target tracking, spacecraft navigation, even smoothing in finance and signal processing. Any time you must combine a model you trust somewhat with measurements you trust somewhat, this is the canonical tool. When you evaluate a variant, ask the two questions the math forces: is my system linear enough for these equations, and do I trust my noise covariances QQ and RR. Those answers, not the branding, decide which filter you want.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. What does a Kalman filter carry as its estimate of the hidden state at each step?
    • A single best-guess value with no notion of uncertainty
    • A full Gaussian belief: a mean vector and a covariance matrix
    • The entire history of past measurements
    • A list of candidate states with equal weight
  2. During the predict step, what happens to the state covariance P?
    • It grows: P-bar = F P F^T + Q, because the model adds process noise
    • It shrinks, because prediction improves the estimate
    • It stays exactly constant until a measurement arrives
    • It is reset to the identity matrix
  3. The Kalman gain K comes out large (the filter moves strongly toward a measurement) when:
    • The process noise Q is zero
    • The state is one-dimensional
    • The prediction uncertainty is large or the measurement noise R is small
    • The measurement disagrees with the prediction, regardless of any uncertainties
  4. Under what conditions is the plain Kalman filter the optimal (minimum mean-squared-error) estimator?
    • For any system, as long as you tune Q and R
    • Only when there is no process noise
    • Only for one-dimensional states
    • When the dynamics are linear and the noise is Gaussian
  5. For a strongly nonlinear system, how does the Unscented Kalman Filter (UKF) differ from the Extended Kalman Filter (EKF)?
    • The UKF pushes sigma points through the true nonlinear function instead of linearizing with Jacobians like the EKF
    • The UKF assumes the system is actually linear
    • The UKF discards the covariance and tracks only the mean
    • The UKF requires storing the full measurement history

Related lessons