A range sensor reports a square root, and the Kalman filter only multiplies. The EKF draws a tangent line at its current guess and redraws it every step. In this toy, a frozen tangent ends up 10 m off; a redrawn one stays within 0.1 m.
Pick a filter and watch one lap of a robot that sees four beacons. Then we build the EKF piece by piece: the models, the tangent, predict, the Jacobian, one update and the failures.
You need the Kalman filter from Lesson 5 and what a derivative is. We build the rest from zero.
Lesson 7 of 22 in Sensor Fusion: Classical to Modern. It follows Complementary Filters and AHRS and leads to The Unscented Kalman Filter.
Toy simulation, illustrative: a 10 m room and a 3 m circle. Range noise 0.12 m, bearing noise 0.03 rad, a sighting every 5 steps. The ellipse shows two standard deviations.
Chapter 0
See why a range sensor breaks the linear Kalman filter, and find the escape hatch
A delivery robot rolls across a warehouse. Its wheels and IMU tell it how far it moved, so it can dead-reckon: add up its own motion to track its position. Every small error adds up too. After a minute it is half a metre off.
A beacon hangs on a pillar at a known spot. The robot measures the range, the straight-line distance to the beacon, and the bearing, the angle it must turn to face it. Lasers, radar and cameras that track a marker all give this pair.
The Kalman filter from Lesson 5 can fuse a prediction with a measurement. It needs the measurement to be a matrix times the state: z = H x. A range is a square root of a sum of squares. No matrix produces a square root.
The grey curve is the range to a beacon 3 m to the side, as the robot moves along x. Drag the robot and watch how much one metre of motion changes the range.
Exact geometry: range = square root of (x squared + 9), beacon at the origin, robot on the line y = 3 m.
| Robot at x | Range | Change for the next 1 m |
|---|---|---|
| 0 m | 3.00 m | +0.16 m |
| 2 m | 3.61 m | +0.64 m |
| 3 m | 4.24 m | +0.76 m |
| 10 m | 10.44 m | +0.96 m |
A matrix has one slope everywhere. The range has a different slope at every point, so no single matrix fits it. But near one point the slope barely changes. A small piece of the curve is almost a straight line.
Chapter 1
Write down how a wheeled robot moves and what a beacon sensor reads, and see where each one bends
The Kalman filter loops two steps. Predict moves the estimate forward with a motion model and grows its doubt. Update pulls the estimate toward a measurement and shrinks its doubt. Each step uses one model, and each model must be a matrix.
| Step | Linear Kalman filter | What the robot has |
|---|---|---|
| Predict | new state = F × state + B × command | a cosine and a sine of the heading |
| Update | expected reading = H × state | a square root and an arctangent |
Call the robot's pose its position x, y and its heading theta, the direction it faces. Each step it receives a command: drive forward a distance v, then turn by an angle omega. Call the new pose x-prime, y-prime, theta-prime.
f of x and u is a column of three: x plus v cos theta, y plus v sin theta, and theta plus omega.
Split the forward distance v into an x part, v cos theta, and a y part, v sin theta. Add them to x and y. Add the turn omega to theta.
The robot is at (2, 1) facing theta = 30° and drives v = 1 m. x-prime = 2 + 0.866 = 2.866 m and y-prime = 1 + 0.5 = 1.5 m. Facing 90°, the same metre adds 0 to x and 1 to y.
The same command moves x by a different amount for each heading. That is the curve. If the robot never turns, theta stays fixed, the cosine is a constant, and the model is linear.
The dashed grey path is the true motion. The blue path uses a model made straight at the start pose. Raise the turn rate and press Drive.
Illustrative toy: v = 0.5 m per step, no noise. The blue model is f with its slope frozen at the start heading.
Put a landmark at a known spot x-L, y-L. Call the offsets from the robot to it dx = x-L − x and dy = y-L − y. The sensor returns the range r and the bearing phi.
h of x is a column of two. r equals the root of dx squared plus dy squared. phi equals atan-two of dy and dx, minus theta.
Find the offsets dx and dy. The range r is the length of that arrow. The bearing phi is the arrow's angle, minus the way the robot faces.
The robot is at (2, 1) with theta = 0.3 rad. The landmark is at (5, 5). dx = 3 and dy = 4, so r = √25 = 5 m. phi = 0.927 − 0.3 = 0.627 rad.
Chapter 2
Replace a curve with its straight line at one point, and collect every slope of a model in one grid
Take the range to the beacon again, with the robot on the line y = 3: r(x) = √(x² + 9). We want a straight line that matches it near one point. Call that point the anchor, x-zero. The filter will put the anchor at its current estimate.
A straight line needs a value and a slope. The value is r(x-zero). The slope is the derivative r-prime, how much r changes for each metre of x. For this curve the chain rule gives r-prime(x) = x / r(x).
r of x is about r of x-zero, plus r-prime of x-zero times x minus x-zero.
Start at the anchor value r(x-zero). For each metre you step away, add the slope r-prime(x-zero). The line is good while the step x − x-zero is small.
Anchor x-zero = 3: r(3) = 4.243 and r-prime(3) = 3/4.243 = 0.707. At x = 3.1 the line says 4.243 + 0.0707 = 4.314; the truth is 4.3139. At x = 8 the line says 7.778; the truth is 8.544, off by 0.77 m.
The grey curve is the true range. The pink line is its tangent at the anchor. The red bars are the error of the line. Drag the anchor.
Exact geometry: r(x) = square root of (x squared + 9).
A real model has several inputs (x, y, theta) and several outputs (r, phi). So it has one slope for each pair. A partial derivative is the slope of one output when you nudge one input and hold the others still. The Jacobian is the grid of all of them: one row per output, one column per input.
| Row | Nudge x | Nudge y | Nudge theta |
|---|---|---|---|
| Range r | ∂r/∂x | ∂r/∂y | ∂r/∂θ |
| Bearing phi | ∂φ/∂x | ∂φ/∂y | ∂φ/∂θ |
Read ∂r/∂x as "the change in r per small change in x". Near the anchor, the model behaves like its value there plus the Jacobian times the small step. That is a matrix, which is what the Kalman equations need. Chapter 4 fills in these six numbers.
Chapter 3
Push the estimate through the true curve and push the doubt through its slope
The filter keeps two things: a best guess of the pose, written x-hat, and a covariance P, the size and shape of its doubt. Draw P as an ellipse around x-hat. Predict must move both forward one step.
Moving the guess is easy. Put x-hat into the true motion model. A single point goes through any curve exactly. Call the result x-hat-minus, the guess before the next measurement.
x-hat-minus equals f of x-hat and u.
Run the real motion model on the guess x-hat with the command u. The answer is x-hat-minus. No approximation.
x-hat = (2, 1, 30°) and u = (1 m, 0). x-hat-minus = (2.866, 1.5, 30°), the same numbers as Chapter 1.
The doubt is harder. A cloud of possible poses bent through cosines is no longer an ellipse. So the EKF makes its one approximation here: it pushes P through the tangent of f. Call the Jacobian of f at x-hat the matrix F. Call the doubt the motion adds each step Q, the process noise.
P-minus equals F times P times F-transpose, plus Q.
Build F from the slopes of f at x-hat. Squeeze and turn the ellipse P through F from both sides. Then add Q, because every step adds new doubt.
With made-up numbers: theta = 30°, v = 1 m, so F has −0.5 and 0.866 in its last column. P = 0.01 on each diagonal, Q = (0.001, 0.001, 0.0005). P-minus has x variance 0.0135, y variance 0.0185 and an x-y covariance of −0.0043. The heading doubt leaked into position doubt.
The blue ellipse is P-minus around the predicted pose. The filter uses no beacon. Press Step 20 times, or Auto, and watch the doubt grow and turn.
Illustrative toy: the hero's robot with its beacons switched off. The ellipse shows two standard deviations.
Only a measurement can shrink the ellipse. Predict alone always grows it. The approximation is good when f is nearly straight across the ellipse. It is poor when the ellipse is wide and f bends inside it (Chapter 7).
Chapter 4
Derive the six slopes of the range-bearing sensor, put in numbers, and check them by nudging
The update step needs H, the Jacobian of the sensor model h at the predicted pose. Use the same names as Chapter 1: offsets dx = x-L − x and dy = y-L − y, and range r. Moving the robot right shrinks dx, so each slope with respect to x picks up a minus sign.
H is a two by three matrix. Row one: minus dx over r, minus dy over r, zero. Row two: dy over r squared, minus dx over r squared, minus one.
Compute dx, dy and r at the predicted pose. Divide the offsets by r for the range row. Divide them by r squared, swap and fix the signs for the bearing row. End the rows with 0 and −1.
Pose (2, 1, 0.3), landmark (5, 5): dx = 3, dy = 4, r = 5, r² = 25. Row one: −0.600, −0.800, 0. Row two: 0.160, −0.120, −1.
Where do the entries come from? The range is √(dx² + dy²), so the chain rule gives dx/r for a change in dx, and dx falls when x rises. The arctangent gives −dy/r² for a change in dx and dx/r² for a change in dy. Each sign flips once more for the robot's own x and y.
A wrong Jacobian is the most common EKF bug. The filter still runs, so nothing warns you. The check is a finite difference: nudge one input by a tiny amount epsilon, run the true h again, and divide the change by epsilon.
∂r/∂x ≈ (r at x = 2.001 − r at x = 2) / 0.001 = (4.999400 − 5.000000) / 0.001 = −0.600
Each cell shows the formula's value in pink and the nudge result below it. Slide epsilon from huge to tiny, then plant a sign bug.
Exact arithmetic in double precision, forward differences. A cell passes if the two values agree within 0.0002.
A huge epsilon measures a chord, not the tangent. A tiny one loses the change in rounding error. Here every entry passes from 10−3 to 10−11. Make this check a unit test, and run it on F too.
Chapter 5
Predict the reading with the true h, weigh the surprise with the slope H, and shrink the ellipse
A reading z arrives. The linear filter compared it with H x-hat-minus. The EKF compares it with the true model h(x-hat-minus). Call the gap y, the innovation: the surprise. The Kalman gain K decides how much of the surprise to believe.
x-hat equals x-hat-minus plus K times, z minus h of x-hat-minus.
Predict the reading with h. Subtract it from z to get the surprise y. Multiply y by the gain K and add the result to x-hat-minus. Then shrink the doubt: P = (I − K H) P-minus.
With made-up numbers, the bearing alone: expected 0.627 rad, measured z = 0.500 rad, so y = −0.127. With K = −0.8 for the heading, theta moves from 0.300 to 0.300 + 0.102 = 0.402 rad.
The gain uses two new names. R is the sensor's noise covariance. S = H P-minus H-transpose + R is how big the filter expects the surprise to be. Here is the whole bearing-only update, with heading variance P-minus = 0.04 rad², R = 0.01 rad² and the Jacobian entry ∂φ/∂θ = −1.
| Step | Rule | Number |
|---|---|---|
| Expected reading | h(x-hat-minus) = atan2(4, 3) − 0.3 | 0.627 rad |
| Innovation y | z − h = 0.500 − 0.627 | −0.127 rad |
| Expected surprise S | (−1)(0.04)(−1) + 0.01 | 0.05 rad² |
| Gain K | 0.04 × (−1) / 0.05 | −0.8 |
| New heading | 0.3 + (−0.8)(−0.127) | 0.402 rad |
| New variance | (1 − (−0.8)(−1)) × 0.04 | 0.008 rad² |
The sensor saw a smaller bearing than expected, so the robot must face further left: theta went up. The variance fell five times. The sign of K came from H, so a sign bug in H would push theta the wrong way.
The blue ellipse is the prediction, the dashed ring the true pose, the orange square the landmark. Press Sense and update. Drag the landmark to change which direction it pins down.
Illustrative toy with the Code Lab's numbers: prior (2, 1, 0.3), P-minus = diag(0.4, 0.4, 0.05), true pose (2.3, 1.25, 0.3), R = diag(0.04, 0.01).
Chapter 6
Run the whole filter on a loop with landmarks, and find the settings that make it confidently wrong
Here is the full EKF. Each step it predicts with f and F. Every fifth step it sights each beacon within 5.2 m and updates with h and H. The teal ellipse should grow between sightings and snap smaller at each one.
Teal is the EKF estimate, dashed grey the truth. Press Run. Then try a bad start with one landmark.
Illustrative toy. Bad start: 1.9 m off and 115° wrong, with a start ellipse of ±0.1 m. Humble start: the same error with a start ellipse of ±1.6 m. The claim ± is the root of the summed x and y variances.
Experiments 2 and 3 are the lesson. High noise made the filter fuzzy. A wrong anchor made it wrong, because it drew every tangent in the wrong place. The danger is a small ellipse around a wrong guess: the filter then ignores the sightings that could save it.
Chapter 7
Measure how curved is too curved, and set the start and the two noise dials so the tangent stays honest
The tangent is right at the anchor and wrong far away. The filter's doubt sets how far is "far". If the ellipse is small, the curve is nearly straight across it. If the ellipse is wide and the curve bends inside it, the EKF's mean and spread are both off.
Top: the blue bell of possible positions under the curve, and the pink tangent at its centre. Bottom: the true spread of ranges in grey and the EKF's bell in teal. Widen the bell, then move it to x = 0.
Exact numerical integration over r(x) = square root of (x squared + 9). The EKF bell has mean r(centre) and spread |r-prime(centre)| × sigma.
At centre 3 with sigma 0.3, the EKF's mean is off by 0.005 m. With sigma 2, the true mean range is 4.51 m and the EKF says 4.24 m. At centre 0 the slope is zero, so the EKF says the range has no spread. With sigma 1 the true spread is ±0.21 m.
| Situation | Use | Why |
|---|---|---|
| Mild curves, frequent sightings, small ellipse | EKF | the tangent fits across the ellipse; one Jacobian per step is cheap |
| Sharp curves or a wide ellipse | UKF | it pushes a few sample points through the true curve; no Jacobian |
| The robot could be in two places | Particle filter | EKF and UKF both keep one bell |
| Dial | Too small | Too large |
|---|---|---|
| R (sensor noise) | the estimate chases every noisy reading | it ignores good readings and drifts |
| Q (process noise) | a tight, overconfident ellipse that can ignore readings | a fat ellipse and a noisier, safer estimate |
Chapter 8
Name the four traps, and use one number from the innovations to catch a filter that lies
A linear Kalman filter is exact when its models hold, so its bugs are usually typos. The EKF approximates, so it can be wrong and sure at once. Divergence means the estimate runs away from the truth and does not come back.
| Trap | Symptom | Test | Fix |
|---|---|---|---|
| Wrong Jacobian | tracks a while, then drifts or wobbles | finite-difference every entry | fix the sign or the chain-rule factor |
| Bad anchor | runs away while the ellipse shrinks | innovations large and one-sided | better start, larger P and Q, or a UKF |
| Angle wrap | sudden jumps when a bearing crosses ±180° | raw innovation near ±2π | wrap every angle residual into (−π, π] |
| False confidence | doubt shrinks in a direction no sensor sees | observability analysis, NIS creeping up | observability-constrained EKF, or a factor graph |
Angle wrap catches everyone once. A predicted bearing of +179° and a reading of −179° are 2° apart. Subtracted naively they give −358°, and the filter yanks hard the wrong way.
Is the ellipse honest? Take the innovation y and the expected surprise S from the update step. Divide each surprise by its expected size and add up the squares. That is the NIS, the normalized innovation squared.
NIS equals y-transpose times S-inverse times y.
Square each part of the surprise y and divide it by the variance S says it should have. Add the parts. If the filter is honest, the NIS averages the number of measurement dimensions: 2 for range and bearing.
With made-up numbers: y = (0.3 m, −0.05 rad) and S has variances 0.05 m² and 0.002 rad². NIS = 0.09/0.05 + 0.0025/0.002 = 1.8 + 1.25 = 3.05. One update above 2 is normal; an average of 6 is not.
Each dot is the NIS of one update. The dashed green line is 2, the dashed red line the 95% bound of 5.99. Make the filter overconfident, or forget the angle wrap.
Illustrative toy: 150 seeded two-dimensional innovations. For an honest filter the NIS follows a chi-squared law with 2 degrees of freedom: mean 2, 95% of values under 5.99.
An average far above 2 means the filter is overconfident: raise Q or R, or look for a bug. Far below 2 means it is underconfident and wastes good data. The test needs no ground truth, so it works in the field.
Chapter 9
Keep the equations, the numbers, the checklist and the code in one place
The EKF is the Kalman filter with two changes. It moves the estimate and predicts the reading with the true models f and h. Wherever the old filter multiplied by F or H to move doubt, it uses their Jacobians, recomputed at the newest estimate every step.
| Quantity | Formula | Numbers from this page |
|---|---|---|
| Tangent line | r(x) ≈ r(x0) + r′(x0)(x − x0) | 4.314 at x = 3.1 (truth 4.3139) |
| Predict mean | x̂− = f(x̂, u) | (2, 1, 30°) to (2.866, 1.5, 30°) |
| Predict doubt | P− = F P FT + Q | F column (−0.5, 0.866, 1) |
| Range-bearing Jacobian | rows (−dx/r, −dy/r, 0), (dy/r², −dx/r², −1) | (−0.6, −0.8, 0), (0.16, −0.12, −1) |
| Innovation | y = z − h(x̂−) | 0.500 − 0.627 = −0.127 rad |
| Gain | K = P−HTS−1, S = H P−HT + R | S = 0.05, K = −0.8 |
| Correct | x̂ = x̂− + K y, P = (I − K H)P− | theta 0.402 rad, variance 0.008 |
| Honesty | NIS = yTS−1y, average = measurement dimension | 3.05 for one update; average near 2 |
pythonimport numpy as np def wrap(a): return (a + np.pi) % (2 * np.pi) - np.pi def ekf_step(x, P, u, z, Q, R, f, h, F_jac, H_jac): x_pred = f(x, u) # move the mean with the TRUE model F = F_jac(x, u) # slope of f at the current estimate P_pred = F @ P @ F.T + Q # grow the doubt (the one approximation) y = z - h(x_pred) # innovation, from the TRUE model y[1] = wrap(y[1]) # wrap the bearing residual H = H_jac(x_pred) # slope of h at the PREDICTED pose S = H @ P_pred @ H.T + R # expected size of the surprise K = P_pred @ H.T @ np.linalg.inv(S) # gain nis = float(y @ np.linalg.inv(S) @ y) # log it: average should be near 2 return x_pred + K @ y, (np.eye(len(x)) - K @ H) @ P_pred, nis def fd_jacobian(h, x, eps=1e-6): # the unit-test partner of H_jac cols = [(h(x + eps * e) - h(x - eps * e)) / (2 * eps) for e in np.eye(len(x))] return np.array(cols).T # assert np.allclose(H_jac(x), fd_jacobian(h, x), atol=1e-5)
| System | Curved motion | Curved measurement |
|---|---|---|
| INS/GNSS navigation (Lesson 14) | attitude integration | satellite pseudoranges, which are distances |
| Robot localization | wheel odometry, the unicycle model | range and bearing to mapped landmarks |
| Phone and drone attitude | gyro integration of rotations | gravity and magnetic field seen from a tilted body |
| EKF-SLAM | the robot's motion | landmarks whose positions are also in the state |
The EKF grew out of NASA navigation work for Apollo in the 1960s. It won because it is cheap, keeps only the current estimate and covariance, and reuses the Kalman filter a team already has. The ROS package robot_localization still ships an EKF node.
Now press Present or Teach and derive it from memory: the models, the tangent, predict, the six slopes of H, one update and the NIS. Then go back to the hero and say why the frozen tangent got lost.
Lesson 7 of 22 in Sensor Fusion: Classical to Modern on Engineermaxxing. The derivations follow Simon (2006) and Thrun, Burgard and Fox (2005). Every toy number on this page carries the word illustrative.