Push a 1 m position spread through a range sensor. Far to the side, the straight-line rule predicts a 0.89 m range spread, and the truth is 0.89 m. At the closest point it predicts 0 m. The truth is 0.21 m.
Pick where the drone flies, then widen its spread. Watch the true range spread (teal) and the straight-line guess (warm) agree, then part. Then we build, piece by piece, the tangent line, the gradient, the Jacobian and the chain rule. Last come the check that catches a wrong Jacobian and the H and F of a Kalman filter.
You need the derivative of one variable and a matrix times a vector. We build the rest from zero.
A maths foundation for state estimation. We checked every Jacobian on this page against central finite differences in NumPy, and every spread against sampling.
Exact maths, toy geometry. The dish sits at the origin and the drone flies along the line y = 3 m, so the range is √(x² + 9). The input is a bell curve in x. The teal bars are 4,000 evenly spaced quantiles of that bell, pushed through the true curve.
Chapter 0
See why a Kalman filter cannot use a range sensor as it is, and what the fix looks like
A dish on a roof tracks a drone. It reports one number: the distance to the drone. If the drone sits at (x, y) with the dish at the origin, that range is √(x² + y²).
You want to fuse this reading with a motion model in a Kalman filter, the tool that blends a prediction with a measurement. Its update assumes the measurement is a fixed matrix times the state: z = H x. No fixed H gives √(x² + y²) for every (x, y). A matrix product is flat everywhere. The range curves everywhere.
There is a second problem. Your belief about the drone is a spread, a Gaussian cloud of likely positions. Push that cloud through a curve and it stops being Gaussian. The hero shows it: at the closest point, the range curve is flat, yet the true range still spreads by 0.21 m.
Teal is the true range as the drone moves along x (y fixed at 3 m). Warm is the tangent line at the blue operating point. Move the operating point, then walk away from it.
Exact maths on a toy geometry: range = √(x² + 9).
Work the number at a = 4 m. The range is 5 m and the slope is 4/5 = 0.8. One metre away, at x = 5, the line says 5.80 m and the truth is 5.831 m: a gap of 0.031 m. Two metres the other way, at x = 2, the gap is 0.206 m. Near the operating point the line is almost exact. Far from it, the gap grows fast.
So the fix is local. At each step, freeze the current best guess. Build the flat map that matches the curve at that guess. Run the linear Kalman maths with it. Throw it away and build a new one at the next guess. That flat map is the Jacobian, and the extended Kalman filter rebuilds it every step.
The symptom is a filter that tracks well far from the dish and goes wrong near it. To measure it, push samples through the true sensor and compare their spread with the filter's spread. The fix is to rebuild the line often, and to use a sampling filter where the curve bends hard (Chapter 8).
Chapter 1
Build a tangent line by hand, then measure how fast it drifts from the curve
Take a smooth function f of one input. Pick an operating point a, the point you build the line at. You know two things there: the height f(a), and the slope f′(a). Call the line built from them L, and call the distance you walk from a δ (delta), so δ = x − a.
L of x equals f of a, plus f-prime of a times x minus a.
Start at the known height f(a). Walk the step x − a. Climb f′(a) for each unit you walk.
Take f(x) = √x and a = 4. Then f(4) = 2 and f′(4) = 1/(2 × 2) = 0.25. At x = 5, L = 2 + 0.25 × 1 = 2.25. The true √5 is 2.2361, so the line sits 0.0139 too high.
Left: √x (teal) and its tangent at a = 4 (warm). Right: the gap against the step δ (pink), with the δ² rule dashed. Drag δ.
Exact maths.
Read the plot. Double δ from 1 to 2 and the gap goes from 0.0139 to 0.0505, about four times. That is the mark of a squared term. Call the curvature f″(a) (f-double-prime of a), how fast the slope itself changes at a.
f of x minus L of x is about one half, times f-double-prime of a, times delta squared.
Square the step δ. Multiply by the curvature f″(a). Halve it. That is about the gap.
For √x, f″(4) = −1/32. At δ = 1 the rule gives ½ × (−1/32) × 1 = −0.0156; the measured gap is −0.0139. At δ = 2 it gives −0.0625 against −0.0505. The minus sign means the line sits above the curve.
The rule is close for small steps and drifts for big ones, because higher terms join in. The square is what matters: a line built for a narrow range stays good there and fails fast outside it.
The symptom is a filter that linearizes once, at the start, and diverges after a few steps. To measure it, log how far the state has moved from the operating point. The fix is to rebuild the line at every new estimate.
Chapter 2
Freeze all inputs but one, take the slope, and stack the slopes into a compass
The range sensor has two inputs, x and y. A slope now depends on which way you walk. The fix is the partial derivative: hold every input still except one, and take the ordinary slope in that one. We write the partial of f in x as ∂f/∂x, or fx. It treats y as a constant.
Stack the partials into a vector and you get the gradient, ∇f = (fx, fy). It points the way f rises fastest, and its length is how steep that is. One slope gave a tangent line. Two partials give a tangent plane: the flat sheet that touches the surface at (a, b) and leans the same way.
L of x and y equals f of a b, plus f-sub-x times x minus a, plus f-sub-y times y minus b.
Start at f(a, b). Add fx for each unit you walk in x. Add fy for each unit you walk in y.
Take f = x² + xy at (1, 2). Then f = 3, fx = 2x + y = 4 and fy = x = 1. At (1.1, 2.1): L = 3 + 4 × 0.1 + 1 × 0.1 = 3.50. The truth is 1.21 + 2.31 = 3.52, a gap of 0.02.
Rings are lines of equal height of g(x, y) = x² + 0.5xy + y². The warm arrow is the gradient at the blue point. The grey bar is the flat direction along the ring. Move the point.
Exact maths. We draw the arrow at 0.3 of its length to fit.
At (1.2, −0.8) the partials are gx = 2x + 0.5y = 2.0 and gy = 0.5x + 2y = −1.0. The arrow always meets the ring at a right angle. Along the ring the height does not change, so all the change lies across it.
The symptom is a step along the gradient that overshoots and makes things worse. The gradient is a snapshot at one point and knows nothing about bending. To measure it, compare the predicted change with the real change after the step. The fix is a smaller step, or curvature information from the Hessian.
Chapter 3
Stack the gradients of every output into a matrix, and use it to predict a small step
A lidar reports each hit as a distance r and an angle θ. A map wants (x, y). The map is x = r cosθ, y = r sinθ: two inputs, two outputs. We need the slope of every output with respect to every input.
The Jacobian J of a map with n inputs and m outputs is the m by n matrix of all those partials. Row i is the gradient of output i. Entry Jij answers one question: if input j moves a little, how much does output i move? Call the small step of the inputs δ, a vector of n numbers.
f of a plus delta is about f of a plus J times delta, where J-i-j is the partial of f-i with respect to x-j.
Fill J one entry at a time: freeze all inputs but xj and differentiate fi. To predict the outputs after a step δ, multiply J by δ and add f(a).
The polar map at r = 4 m, θ = 60° gives f(a) = (2, 3.464) and the J below. Take δ = (0.1 m, 0.05 rad). Jδ = (0.05 − 0.173, 0.087 + 0.1) = (−0.123, 0.187). The guess is (1.877, 3.651); the truth is (1.870, 3.649), a gap of 0.007 m.
Fill the polar Jacobian entry by entry with the freeze rule.
| Entry | Freeze, then differentiate | Result |
|---|---|---|
| ∂x/∂r | freeze θ: x = (cosθ) r | cosθ |
| ∂x/∂θ | freeze r: the slope of cos is −sin | −r sinθ |
| ∂y/∂r | freeze θ: y = (sinθ) r | sinθ |
| ∂y/∂θ | freeze r: the slope of sin is cos | r cosθ |
J = cosθ−r sinθsinθr cosθ = 0.500−3.4640.8662.000 at r = 4, θ = 60°
Column 1 says: one more metre of r moves the point along the line from the origin. Column 2 says: one more radian of θ swings it sideways, r times as far, because a longer arm sweeps a longer arc. The determinant, cosθ · r cosθ + r sinθ · sinθ = r, is how much a tiny patch of area grows. Here it is 4.
Left: a blue circle of nearby (r, θ) inputs. Right: its true image (teal) and the Jacobian's ellipse (warm). Grow the circle and watch them part.
Exact maths. The circle radius is in metres for r and radians for θ. The right panel centres on f(a) and scales to fit; the dotted line points back toward the origin.
The symptom is a Jacobian that is right at one point and used far from it. The ellipse stays an ellipse while the true image bends into an arc. To measure it, map a ring of nearby inputs both ways and take the largest gap. The fix is a smaller neighbourhood or a fresh J.
Chapter 4
Linearize a pipeline of maps by multiplying each stage's Jacobian, in the right order, at the right point
A lidar hit goes through a polar-to-Cartesian map, then a turn into the robot frame, then a shift into the world. A neural network is dozens of maps in a row. If you feed x into f, and f's output into g, what is the Jacobian of the whole pipe?
In one variable you know the answer: the slopes multiply. With vectors, the Jacobians multiply. Call the pipe g∘f (g after f). Take each Jacobian at the input its own stage sees.
J of g after f, at x, equals J-g at f of x, times J-f at x.
Run x through f to get u = f(x). Take Jf at x and Jg at u. Multiply them with the last stage on the left.
Stage one is the polar map at (4, 60°), so u = (2, 3.464). Stage two is g(u) = (u1² + u2, u1u2). Its Jacobian at u is Jg = [[2u1, 1], [u2, u1]] = [[4, 1], [3.464, 2]]. The top-left entry of the product is 4 × 0.5 + 1 × 0.866 = 2.866.
The full product is [[2.866, −11.856], [3.464, −8.000]]. A central finite difference on the whole pipe gives the same four numbers to six decimals. Swap the order and you get [[−10, −6.428], [10.392, 4.866]], which is wrong.
A blue circle of inputs passes through f, then g. Teal is the true image; warm is the Jacobian product. Switch to the wrong order and watch the last shape miss.
Exact maths. Each panel centres on its stage's operating point and scales to fit. The input circle has radius 0.03.
This product is the whole of backpropagation. Each layer knows its own local Jacobian. Autograd multiplies them from the loss back to the weights.
The symptom is a pipeline Jacobian with the right shape and wrong numbers. Two causes are common: the factors in the wrong order, or Jg taken at x instead of f(x). To measure it, compare with a finite difference of the whole pipe. The fix is to build the product from the last stage leftward, each at its own input.
Chapter 5
Nudge each input, divide, and compare with your algebra; pick a step that is neither too big nor too small
Every Jacobian so far came from algebra: the analytic route. It is exact when it is right. It is also where EKF code breaks most: a lost minus sign, a missed chain-rule term, a row copied into the wrong place. The filter still runs. It quietly gives wrong answers.
You need a second route that never touches your formula. A finite difference nudges one input by a small step h, runs the real function, and divides. Call the unit step along input j ej.
The partial of f by x-j is about f at x plus h e-j, minus f at x minus h e-j, over two h.
Nudge input j up by h and down by h. Run f both times. Subtract and divide by 2h. Do this for each input to fill each column.
Take f = sin at x = 1, where the true slope is cos 1 = 0.5403023. With h = 10−4 the central difference is off by 9 × 10−10. The one-sided forward difference, [f(x + h) − f(x)]/h, is off by 4.2 × 10−5.
The central form wins because its two nudges cancel the leading error term. Its truncation error shrinks like h²; the forward form's shrinks like h. But h cannot shrink forever. A double keeps about 16 digits. Subtract two nearly equal numbers and most digits vanish; dividing by a tiny h blows up what is left. That is round-off error, and it grows as h shrinks.
Both axes are powers of ten. Yellow is the central difference; purple dashed is the forward difference, both for the slope of sin at 1. Slide h from right to left.
Real double-precision arithmetic, run live in your browser.
The Jacobian check is a unit test. Compute the analytic H or F and a central-difference version at the same point, and assert they agree to about six digits. For the polar map at (4, 60°) both give [[0.5, −3.4641], [0.8660, 2.0]]. Chapter 9 has the code.
The symptom is a check that passes at two digits and misses a real bug. Usually it used the forward difference with a loose tolerance. To measure it, plant a sign error and see if the test fails. The fix is the central difference, h near 10−5, and a tight relative tolerance.
Chapter 6
Linearize a range-and-bearing sensor, read its hidden structure, and find where it blows up
Give the dish a better sensor. It now reports the range and the bearing, the angle from the dish to the drone. The measurement function is h(x, y) = (√(x² + y²), atan2(y, x)). This is Chapter 3's map run backwards: Cartesian to polar. In an EKF its Jacobian is called H, the measurement Jacobian.
Call the range r. The range partials are x/r and y/r. The bearing partials need one more chain-rule step through the arctangent, and come out as −y/r² and x/r².
H is the two by two matrix x over r, y over r, minus y over r squared, x over r squared. Here r is the square root of x squared plus y squared.
Moving toward the dish changes only the range, one metre per metre. Moving sideways changes only the bearing, by 1/r radians per metre.
Drone at (3, 4): r = 5. H = [[0.6, 0.8], [−0.16, 0.12]]. With a position spread of σ = 0.1 m, the range spreads by 0.1 m and the bearing by 0.1/5 = 0.02 rad, which is 1.15°.
The two rows meet at a right angle: 0.6 × (−0.16) + 0.8 × 0.12 = 0. Row 1 has length 1. Row 2 has length 0.2 = 1/r. So H HT = diag(1, 1/r²). A round position spread σ becomes a range spread σ and a bearing spread σ/r.
One more check: H at (3, 4) is the inverse of the polar Jacobian at r = 5, θ = 53.13°. The Jacobian of an inverse map is the inverse matrix.
Left: the dish at the origin and the drone with its range line. Right: the bearing spread σ/r for a 0.1 m position spread. Drag the drone in close.
H at the drone
Exact maths. The position spread is 0.1 m in every direction.
The symptom is a bearing estimate that swings wildly as the drone passes close to the dish. The bearing row grows like 1/r, and the curve bends hardest exactly there, so the line is least valid where its numbers are biggest. To measure it, plot the bearing spread against r. The fix is to gate or down-weight bearing updates below a minimum range.
Chapter 7
Linearize a turning robot's motion and carry its uncertainty one step forward
A ground robot has state (x, y, θ): position and heading. In one time step dt it drives at speed v and turns at rate ω. The motion model is f(x, y, θ) = (x + v cosθ dt, y + v sinθ dt, θ + ω dt). Heading enters through sine and cosine, so f curves in θ.
Its Jacobian is called F, the process Jacobian. It is 3 by 3. Only the θ column is not trivial.
| Column | Freeze, then differentiate | At v = 2 m/s, θ = 30°, dt = 0.1 s |
|---|---|---|
| ∂f/∂x | x appears once, with slope 1 | (1, 0, 0) |
| ∂f/∂y | y appears once, with slope 1 | (0, 1, 0) |
| ∂f/∂θ | (−v sinθ dt, v cosθ dt, 1) | (−0.1, 0.1732, 1) |
The state goes through the true f. Its covariance P, the matrix of spreads and cross-spreads, goes through F. Call the new covariance P′ and the extra noise from wheel slip Q.
P-prime equals F times P times F-transpose, plus Q.
F maps a small state error to its error one step later. Apply F to P from the left and from the right. Add Q.
Start with P = diag(0.04, 0.04, 0.01): 0.2 m in x and y, 0.1 rad in heading, no cross terms. Set Q = 0 to see F alone. P′ has diagonal (0.0401, 0.0403, 0.0100), and the x–heading and y–heading entries become −0.0010 and 0.0017.
The new cross terms are the point. Heading feeds position through sine and cosine, so heading doubt becomes position doubt along the sideways direction. Two million samples pushed through the true f give cross terms of −0.00100 and 0.00172. The line is excellent here, because 0.1 rad is a small heading spread.
The blue circle is the start position spread. Teal dots are samples pushed through the true motion. The warm ellipses are 1σ and 2σ of F P FT. Raise the heading spread and the step length.
Exact maths on 1,500 seeded samples. Start position spread 0.2 m in x and y; Q = 0.
The symptom is a filter that is too sure of its position after a long step with a doubtful heading. The true cloud bends into a banana and the ellipse cannot bend. To measure it, compare the ellipse with sampled spreads, as the device does. The fix is shorter steps, or the sampling of the unscented Kalman filter.
Chapter 8
Drag a drone around the dish and compare the true measurement cloud with the H ellipse
This is the hero's question with the full sensor. On the left, the dish sits at the origin and a cloud of likely drone positions hangs around the operating point. On the right, each sample goes through the true range-and-bearing function h. On top sits the ellipse of H Σ HT, where Σ is the position covariance σ² I.
Drag the blue drone on the left, or pick a preset. Right: true range and bearing of each sample (teal) and the 1σ and 2σ ellipses of HΣHT (warm).
Exact maths on 1,500 seeded samples, so the sampled spreads wobble by about 2%. We unwrap bearings around the drone's bearing.
Start far out. At r = 10 m with σ = 0.5 m the ellipse predicts a bearing spread of 2.86°. Four hundred thousand samples give 2.86°. Now press Close. At r = 1 m the ellipse says 28.6° and the samples say 34.6°. The mean range drifts too: 1.13 m, not 1.00 m, because range can never go negative and the cloud piles up on the far side.
Read the rule from the numbers. The line is good when the spread σ is small next to the distance over which the curve bends, here r. Far out, σ/r = 0.05. Close in, σ/r = 0.5, and the ellipse misses the shape, the width and the centre.
A Kalman gain built on the wrong ellipse trusts the sensor by the wrong amount. That is the EKF's classic failure near a singularity. The unscented Kalman filter avoids it: it pushes a few real sample points through h instead.
Chapter 9
Pick the right derivative object, keep the numbers, and run the check
Four objects appeared in this lesson. Each answers a different question.
| Tool | Shape | Question it answers | Use it for |
|---|---|---|---|
| Gradient | vector, n | Which way does one number rise fastest? | a scalar loss or cost |
| Jacobian | matrix, m by n | How does each output move with each input? | sensor models, motion models, network layers |
| Hessian | matrix, n by n | How does the slope itself bend? | Newton steps, curvature checks |
| Finite difference | an estimate of any of these | What is the slope, without trusting my algebra? | Jacobian checks, black-box functions |
| Term | One line | Number to remember |
|---|---|---|
| Tangent line | L(x) = f(a) + f′(a)(x − a) | √5 by the line at 4: 2.25 vs 2.2361 |
| Linearization gap | about ½ f″(a) δ² | double δ, about 4 times the gap |
| Jacobian | Jij = ∂fi/∂xj; f(a + δ) ≈ f(a) + Jδ | polar at (4, 60°): det J = 4 |
| Chain rule | Jg∘f = Jg(f(x)) Jf(x) | last stage on the left |
| Central difference | [f(x + h) − f(x − h)] / 2h | h ≈ 10−5 in doubles |
| Measurement Jacobian H | range row x/r, y/r; bearing row −y/r², x/r² | bearing spread σ/r |
| Covariance step | P′ = F P FT + Q | trust it while σ is small next to the bend |
pythonimport numpy as np def jacobian_fd(f, x, h=1e-5): # f: (n,) -> (m,); returns (m, n) x = np.asarray(x, dtype=float) cols = [] for j in range(len(x)): e = np.zeros_like(x); e[j] = h cols.append((f(x + e) - f(x - e)) / (2 * h)) # central difference return np.stack(cols, axis=1) def h_meas(p): # (x, y) -> (range, bearing) return np.array([np.hypot(p[0], p[1]), np.arctan2(p[1], p[0])]) def H_analytic(p): x, y = p; r2 = x*x + y*y; r = np.sqrt(r2) return np.array([[x/r, y/r], [-y/r2, x/r2]]) p = np.array([3.0, 4.0]) assert np.allclose(H_analytic(p), jacobian_fd(h_meas, p), rtol=1e-6, atol=1e-9) # the Jacobian check def predict(s, P, Q, v, w, dt): # EKF predict for the unicycle x, y, th = s s_new = np.array([x + v*np.cos(th)*dt, y + v*np.sin(th)*dt, th + w*dt]) # true f F = np.array([[1, 0, -v*np.sin(th)*dt], [0, 1, v*np.cos(th)*dt], [0, 0, 1]]) return s_new, F @ P @ F.T + Q # state through f, covariance through F
Now press Present or Teach and explain from memory why the straight line predicts zero range spread at the closest point. Then go back to the hero, pick each position, and say which chapter explains what you see.