Nonlinear Least Squares

Three noisy ranges, one robot. From the corner of the room, Gauss-Newton finds the best spot in 4 steps, but its first step climbs uphill. Levenberg-Marquardt takes 5 steps, every one downhill. Plain gradient descent takes 58.

Pick a solver and press Run. Tap the floor to start somewhere else. Then we build, piece by piece, the cost, the Jacobian, the Gauss-Newton step, the damping knob, the robust kernel and the error ellipse.

You need a little algebra, what a vector is and some Python for the code. We build the rest from zero.

A foundation lesson for the estimation and robotics track. It sits between Jacobians and Linearization and the SLAM back ends in Factor Graphs and AA274A SLAM.

Race three solvers to the robot

Illustrative toy. Beacons sit at (0, 0), (10, 0) and (0, 10) m, and the robot at (3, 4). The measured ranges 5.2, 8.0 and 6.9 m carry made-up noise. Darker purple is lower cost. Gradient descent uses a fixed step of 0.1; Levenberg-Marquardt starts with damping 1. Step counts are to within 1 cm of the best spot; NumPy gives the same counts.

Chapter 0

Three Circles That Almost Meet

See why noisy ranges have no exact answer, and name the best one

A small robot sits in a room. Three beacons hang on the walls at known spots. The robot pings each one and turns the echo time into a distance: 5.2 m, 8.0 m and 6.9 m. Where is the robot?

With perfect distances, draw a circle around each beacon. The circles cross at one point, and that point is the robot. This is trilateration: finding a position from distances to known points. GPS does the same with satellites.

Real distances carry noise. An echo bounces off a wall, a clock drifts. So the circles miss each other and leave a small triangle of near misses. You want the one point that disagrees least with all three readings.

Drag your guess to the best spot

Blue circles are the three measured ranges. Pink lines are how far your orange guess misses each circle. Drag the guess and make the total as small as you can.

Illustrative toy: the same room as the hero. The best spot is (3.21, 4.02) m with a total squared miss of 0.0277 m²; NumPy and scipy.optimize.least_squares agree.

The hard part is the shape of the link between position and range. Call the robot's position p = (x, y). Call the position of beacon i (ui, vi). The range the robot would read from p, with no noise, is the predicted range hi(p).

Say it aloud

h-i of p equals the square root of, x minus u-i squared, plus y minus v-i squared.

hi(p)
h-i of p the predicted range from position p to beacon i, in metres.
x, y
x, y the two coordinates of the position p we test, in metres.
ui
u-i the known x coordinate of beacon i.
vi
v-i the known y coordinate of beacon i.
√( )
the square root of Pythagoras: it turns the two side lengths into a straight-line distance.
In plain words

Subtract the beacon's x from your x, and its y from your y. Square both gaps, add them, take the square root. That is h-i.

With numbers

With made-up numbers: test p = (5, 5) against beacon one at (0, 0). The gaps are 5 and 5, so h-1 = √50 = 7.07 m. The beacon reported 5.2 m, so this guess misses by 1.87 m.

The square root bends the link. Move 1 m and the range changes by anything from 0 to 1 m, depending on direction. So you cannot stack three straight equations and solve. You search instead, for the position that makes the total squared miss smallest. That search is nonlinear least squares.

Failure to watch for: the symptom is a "position" that jumps between runs. Measure it by printing the total squared miss at the answer. If it is far above the noise you expect, the search stopped early or a reading is bad. Chapters 5 and 7 fix those two cases.

The road

  1. The straight case: one-shot normal equations.
  2. Residuals and squares: the cost, and why squares.
  3. The Jacobian: how each range answers a nudge.
  4. Gauss-Newton: the hero's fast solver, step by step.
  5. Levenberg-Marquardt: the hero's safe solver and its damping knob.
  6. Sparsity: the same step for 150,000 unknowns.
  7. Robust kernels: outvote a bad reading.
  8. Covariance: how much to trust the answer.
  9. The lab: every knob at once.
  10. Field guide: numbers, code, links.
Why can you not solve the three range equations exactly for x and y?

Chapter 1

The Straight Case: Normal Equations

Fit a line to three noisy points in one shot, and see the right angle behind it

Master the straight case first. You calibrate a cheap sensor at three known temperatures, 0, 1 and 2 degrees. It reads 1.0, 2.0 and 2.0 volts. You expect voltage = a + b × temperature. Which intercept a and slope b fit best?

Write one row per reading. Put the unknowns in a vector θ = (a, b). Put the readings in y = (1, 2, 2). The design matrix A has one row per reading: a 1 for the intercept and the temperature for the slope. So A has rows (1, 0), (1, 1), (1, 2).

Three equations, two unknowns: no line passes through all three points. The prediction Aθ always lies on the flat sheet of what A can produce. The best fit is the point on that sheet closest to y. There, the leftover miss stands at a right angle to every column of A. Write that right angle as algebra and you get the normal equations.

Say it aloud

A-transpose A times theta equals A-transpose times y.

A
A the design matrix, 3 rows by 2 columns: (1, 0), (1, 1), (1, 2).
AT
A-transpose A with rows and columns swapped, 2 by 3.
θ
theta the unknowns: intercept a and slope b.
y
y the three readings in volts: 1, 2, 2.
ATy
A-transpose y each column of A dotted with the readings.
In plain words

Dot each column of A with every column of A: that gives a 2 by 2 matrix. Dot each column of A with y: that gives 2 numbers. Solve the 2 by 2 system for theta.

With numbers

A-transpose A = [[3, 3], [3, 5]] and A-transpose y = (5, 6). So 3a + 3b = 5 and 3a + 5b = 6. Subtract: 2b = 1, so b = 0.5 and a = 7/6 = 1.167. The line is volts = 1.167 + 0.5 × temperature.

Turn the line until the misses are smallest

Pink bars are the misses at each point. Move the two sliders and watch the total squared miss. Then press the snap button.

1.00
0.60

Illustrative toy data. The least-squares line is a = 1.167, b = 0.5, with a total squared miss of 0.167 V².

Check the misses, prediction minus reading: +0.167, −0.333, +0.167. They add to zero. That always happens when the model has an intercept, because the first normal equation forces it.

pythonimport numpy as np
A = np.array([[1, 0], [1, 1], [1, 2]], dtype=float)   # [3, 2]
y = np.array([1.0, 2.0, 2.0])                            # [3]
theta = np.linalg.solve(A.T @ A, A.T @ y)                  # [1.1667, 0.5]
theta2, *_ = np.linalg.lstsq(A, y, rcond=None)            # same answer, safer route

Failure: the symptom is a fit that changes wildly when one reading moves a little. Measure the condition number of A-transpose A with np.linalg.cond. Forming A-transpose A squares it, so 104 becomes 108. Fix: use lstsq, which works on A directly.

What does the least-squares solution do to the leftover miss?

Chapter 2

Residuals, and Why We Square Them

Turn three misses into one cost, and see which noise makes squares the right choice

A residual is the signed miss of one reading: the predicted value minus the measured value. One guess gives three residuals. You need one number to rank guesses.

Adding the residuals fails: +3 and −3 cancel to zero, yet both are wrong. Absolute values or squares both fix the sign. Squares win for a reason. Assume each reading has bell-shaped Gaussian noise with the same spread for every beacon. Then the likelihood of the readings falls as the sum of squared residuals grows. So the smallest sum of squares is the maximum likelihood answer: the position that makes the readings most probable.

A check with numbers. Let the noise spread be 0.3 m. A residual of 0.1 m has a bell-curve density of 1.26. A residual of 0.6 m has 0.18. The smaller residual is seven times more likely, and its square, 0.01, is smaller than 0.36. The two rankings always agree.

Now name the cost. Call the measured range from beacon i zi. The residual is ri = hi(p) − zi. The cost F(p) is the sum of the squared residuals.

Say it aloud

F of p equals the sum over i of, h-i of p minus z-i, squared.

F(p)
F of p the cost of guess p, in square metres. Lower is better.
Σi
the sum over i one term per beacon, here 3.
hi(p)
h-i of p the predicted range to beacon i, from Chapter 0.
zi
z-i the measured range from beacon i: 5.2, 8.0 or 6.9 m.
In plain words

For each beacon, subtract the measured range z-i from the predicted range h-i. Square that residual. Add the squares. The total is F.

With numbers

At p = (5, 5) the residuals are 1.871, −0.929 and 0.171 m. F = 3.501 + 0.863 + 0.029 = 4.393 m². At the best spot F falls to 0.028.

Grow one residual and compare the penalties

Pink is the squared cost, grey the absolute cost. Drag the residual and watch the gap open.

3.0 m

Pure arithmetic: the squared cost is r times r, the absolute cost is the size of r.

Squares punish big misses hard: a residual twice as large costs four times as much. That is right for Gaussian noise. It is wrong for a reading that is broken. Failure: the symptom is one residual far larger than the rest at the answer. Measure each residual divided by the noise spread; above 3 is suspect. The fix is Chapter 7.

Under what noise does the smallest sum of squared residuals give the maximum likelihood answer?

Chapter 3

The Jacobian: How Each Range Answers a Nudge

Replace the curved range by a straight slope at the current guess, and check how good that is

Zoom in far enough on any smooth curve and it looks straight. Near a guess p, each range changes almost in proportion to a small move. The numbers of that proportion form the Jacobian J: one row per beacon, one column per unknown. Row i says how fast h-i grows when you nudge x or y. Jacobians and Linearization builds the idea in full; here we need one row.

Say it aloud

J-i equals the pair: x minus u-i over h-i, and y minus v-i over h-i.

Ji
J-i row i of the Jacobian: metres of range per metre of move, in x and in y.
x − ui
x minus u-i how far the guess sits east of beacon i.
y − vi
y minus v-i how far the guess sits north of beacon i.
hi
h-i the predicted range at the guess. Dividing by it makes a unit vector.
/
over divided by.
In plain words

Draw the arrow from beacon i to the guess. Shrink it to length 1. Its two parts are row J-i. Moving along the arrow changes the range at full rate; moving across it changes the range hardly at all.

With numbers

At p = (5, 5), beacon two sits at (10, 0) and h-2 = 7.071. J-2 = (−5/7.071, 5/7.071) = (−0.707, 0.707). Nudge 0.5 m east: the row predicts a change of −0.354 m. The true change is −0.344 m.

Nudge the guess and test the straight-line guess

Orange arrows are the three Jacobian rows at the guess; the thick plain arrow is the nudge. Turn its direction and size. Drag the guess to move the test point.

0°
0.5 m

Illustrative toy room. Predicted change is the row dotted with the nudge; true change is the new range minus the old one.

Stack the three rows and you get J, 3 by 2. Near the guess, the change in all three residuals is J times the move. That straight model is what the next chapter solves.

Failure: the symptom is a step that lands worse than it started. Measure it as above: compare the predicted change with the true one. A big nudge or a guess near a beacon breaks the straight model. The fix is a shorter step, which is Chapter 5.

Row i of the range Jacobian at a guess is:

Chapter 4

Gauss-Newton: Linearize, Solve, Repeat

Solve the straight model with the normal equations, step, and rebuild it at the new guess

Chapter 1 solved a straight problem in one shot. Chapter 3 made the curved problem straight near a guess. Gauss-Newton joins them in a loop:

  1. At the guess p, compute the residuals r and the Jacobian J.
  2. Solve the normal equations for the step Δ.
  3. Move: p becomes p + Δ.
  4. Repeat until the step is tiny.

Call the step Δ (delta), a 2-vector in metres. The straight model says the new residuals are r + JΔ. Make their squares smallest, exactly as in Chapter 1.

Say it aloud

J-transpose J times delta equals minus J-transpose r.

JTJ
J-transpose J a 2 by 2 matrix: how curved the cost bowl is near the guess.
Δ
delta the step to take, in metres east and north.
JTr
J-transpose r half the slope of the cost F at the guess; minus it points downhill.
In plain words

Build J-transpose J and J-transpose r from the rows and residuals. Solve the 2 by 2 system for delta. Add delta to the guess.

With numbers

At (5, 5): J-transpose J = [[1.5, −0.5], [−0.5, 1.5]] and J-transpose r = (2.101, 0.545). The determinant is 2.0, so delta = (−1.712, −0.934). The new guess is (3.288, 4.066), and F drops from 4.393 to 0.038.

Step Gauss-Newton by hand

Pick a start, then press Step. The table shows each guess, its cost and its step. Red marks a step that raised the cost.

Illustrative toy room. Every number matches a NumPy run of the same loop.

From (5, 5) the steps are 1.95 m, 0.093 m, then 0.002 m. The guess settles at (3.205, 4.019), 0.21 m from the true robot, because the readings are noisy. Near the answer each step cuts the remaining error about 40 times, because the residuals there are small.

Failure: pick Start (12, 0). The symptom: the first step jumps to (11.6, 13.1) and F rises from 158 to 206. Measure it by printing F after every step. The straight model was poor that far out. Gauss-Newton has no brake; the fix is damping.

What does Gauss-Newton do at every iteration?

Chapter 5

Levenberg-Marquardt: The Damping Knob

Add one number to the diagonal and slide between a bold step and a careful one

Gauss-Newton trusts its straight model fully. Far from the answer, that trust sends it uphill. Levenberg-Marquardt adds a damping number λ (lambda) to the diagonal before it solves. Think of λ as a trust knob. I is the 2 by 2 identity matrix.

Say it aloud

J-transpose J plus lambda I, times delta, equals minus J-transpose r.

JTJ
J-transpose J the curvature of the straight model, as in Chapter 4.
λ
lambda the damping, 0 or more. 0 is Gauss-Newton; large is gradient descent.
I
I the identity matrix: 1 on the diagonal, 0 elsewhere.
Δ
delta the step.
−JTr
minus J-transpose r the downhill direction of the cost.
In plain words

Add lambda to both diagonal entries of J-transpose J. Solve for delta. A large lambda makes delta short and points it straight downhill.

With numbers

At (5, 5) with lambda = 5: the matrix is [[6.5, −0.5], [−0.5, 6.5]], determinant 42. Delta = (−0.332, −0.109), length 0.35 m. The Gauss-Newton step was 1.95 m.

Turn the trust knob

The faint arrow is the Gauss-Newton step, the yellow dashes point straight downhill, and the orange arrow is the damped step. Green means the step lowers the cost; red means it raises it.

0

Illustrative toy room. The slider is on a log scale from 0 to 100.

λStep from (5, 5)LengthAngle off downhill
0 (Gauss-Newton)(−1.712, −0.934)1.95 m14.1°
5(−0.332, −0.109)0.35 m3.7°
20(−0.098, −0.028)0.10 m1.2°

The solver turns the knob itself. If a step lowers F, accept it and divide λ by 3. If it raises F, reject it and multiply λ by 3. From (12, 0) with λ = 1, the first step lands at (10.4, 3.4) and F falls from 158 to 83. Five accepted steps reach the answer.

Failure: the symptom is a solver that stalls far from the answer with λ huge. Measure by logging λ and F each step. A wrong Jacobian makes every step fail, so λ climbs forever. Fix: check J against finite differences.

What happens to the Levenberg-Marquardt step as lambda grows large?

Chapter 6

Sparsity and the Schur Complement

Solve the same step for thousands of cameras and points by skipping the zeros

A drone maps a building site. It estimates 200 camera poses, 6 numbers each, and 50,000 landmark points, 3 numbers each. That is 151,200 unknowns. Fitting all of them to the pixel measurements is bundle adjustment: the same least-squares step, at scale. A dense J-transpose J would hold 23 billion entries.

Most entries are zero. One pixel measurement involves one camera and one landmark.

So call the step matrix H = J-transpose J and split it into blocks. Hcc joins cameras with cameras. Hll joins landmarks with landmarks, and it is block diagonal, because two landmarks never share a measurement. Hcl joins each camera to the landmarks it saw. Eliminate the landmarks first. What is left is the Schur complement S, a system over the cameras only.

Say it aloud

S equals H-c-c minus H-c-l times H-l-l inverse times H-l-c.

S
S the reduced camera system: one row and column per camera unknown.
Hcc
H-c-c the camera-with-camera block of H.
Hcl
H-c-l the camera-with-landmark block; H-l-c is its transpose.
Hll−1
H-l-l inverse the landmark block inverted. It is block diagonal, so you invert one 3 by 3 block per landmark.
Hlc
H-l-c the landmark-with-camera block.
In plain words

For each landmark, invert its small block. Use it to remove that landmark's pull from the cameras. Solve S for the camera steps. Then solve each landmark's step on its own.

With numbers

With made-up numbers: one camera unknown, two landmark unknowns. H-c-c = 4, H-c-l = (1, 2), H-l-l = diag(2, 3). S = 4 − (1 × 1/2 + 2 × 2/3) = 2.167. With right side (1, 2, 3), the camera step is −2/2.167 = −0.923. The landmark steps are 1.462 and 1.615, the same as a full solve.

See which blocks are not zero

Each filled cell is a block that is not zero. Slide the counts. Toggle the Schur view to see the small camera system that remains.

4
10

Illustrative toy: 2 or 3 nearby cameras see each landmark. The drone counts are a made-up example.

Cost of a dense solve grows as n cubed. For 151,200 unknowns that is about 3.5 × 1015 operations. The camera system has 1,200 unknowns, about 1.7 × 109, plus 50,000 tiny 3 by 3 solves. That is two million times less work in the expensive part.

Failure: the symptom is a solver that runs out of memory or takes hours. Measure the fraction of nonzero blocks. If a dense solver meets a sparse matrix, switch to a Schur or sparse Cholesky solver; Ceres, g2o and GTSAM do this.

Why eliminate the landmarks first, not the cameras?

Chapter 7

Robust Kernels: Outvote the Bad Reading

Give each reading a weight that falls as its residual grows, and watch one echo lose its grip

Add a fourth beacon at (10, 10). Its true range is 9.22 m, but an echo off a metal cabinet makes it read 13.22 m: 4 m too long. Squares give that one reading a huge say. Plain least squares lands 1.78 m from the robot.

A robust kernel keeps the square for small residuals and grows slower for large ones. The Huber kernel is the square up to a threshold δ (delta), then a straight line. At a residual of 10 with δ = 1, half the square is 50; Huber is 9.5. The Cauchy kernel grows only as a logarithm.

Solvers apply a kernel by iteratively reweighted least squares (IRLS). Each step gives reading i a weight wi. It scales that reading's share of J-transpose J and J-transpose r by the weight, then solves as before.

Say it aloud

w-i equals 1 if the size of r-i is at most delta; otherwise delta over the size of r-i.

wi
w-i the Huber weight of reading i, from 0 to 1.
|ri|
the size of r-i the residual of reading i without its sign, in metres.
δ
delta the threshold where trust starts to fall, here 1 m, about three noise spreads.
≤
at most less than or equal to.
/
over divided by.
In plain words

If reading i misses by less than delta, give it full weight 1. If it misses by more, give it delta over the miss. The worse the miss, the smaller its vote.

With numbers

With delta = 1 m: a residual of 4 m gets weight 0.25. At the Huber answer the echo's residual is 3.30 m, so its weight is 0.30. The answer lands 0.70 m from the robot instead of 1.78 m.

Make one beacon lie, then outvote it

Beacon four (red when it lies) reads too long. Pick a kernel and drag the echo error. Bars show each beacon's weight.

4.0 m

Illustrative toy. With a 4 m echo, scipy.optimize.least_squares lands 1.78 m off with plain squares. It lands 0.70 m off with loss="huber" and 0.13 m with loss="cauchy", both with f_scale=1.

KernelEcho weight at the answerDistance from robot
Plain squares11.78 m
Huber, δ = 10.300.70 m
Cauchy, c = 1 (weight 1/(1 + r²))0.060.13 m

Failure: a kernel can bury a good reading if the start is poor, because every residual looks large. The symptom is an answer that ignores a beacon you trust. Measure the final weights. Fix: start from a plain fit or a good prior, and pick δ near three noise spreads.

With Huber delta = 1 m, what weight does a residual of 4 m get?

Chapter 8

Covariance: How Much to Trust the Answer

Invert the curvature you already built and draw the ellipse of likely positions

An answer without an error bar is risky. A planner should act one way when the robot is sure to 3 cm and another when it is sure to 60 cm. The matrix J-transpose J holds that answer. A steep bowl pins the answer down; a flat bowl lets it wander.

Call the noise spread of one range σ (sigma), in metres. Evaluate J at the answer. The covariance C of the estimate is the 2 by 2 matrix of how far the answer would scatter if you repeated the readings.

Say it aloud

C equals sigma squared times the inverse of J-transpose J.

C
C the covariance of the estimate, 2 by 2, in square metres.
σ2
sigma squared the noise variance of one range, here 0.3 × 0.3 = 0.09 m².
JTJ
J-transpose J the curvature, built from the Jacobian at the answer.
−1
inverse the matrix that undoes it: steep becomes small, flat becomes large.
In plain words

Build J-transpose J at the answer. Invert it. Multiply by sigma squared. The square roots of its diagonal are the error bars in x and y.

With numbers

At (3.205, 4.019): J-transpose J = [[1.353, −0.367], [−0.367, 1.647]], its inverse is [[0.787, 0.175], [0.175, 0.646]]. Times 0.09 and take roots: 0.27 m in x and 0.24 m in y.

Move the beacons and reshape the ellipse

The purple ellipse holds the likely positions, drawn 5 times larger so you can see it. Drag any beacon, or pick a layout.

Illustrative toy with sigma = 0.3 m. The ellipse is one standard deviation along each axis, evaluated at the true position (3, 4).

Geometry matters as much as noise. Put the three beacons at (0, 0), (2, 0) and (0, 2), all on one side. The long axis grows from 0.29 m to 0.59 m with the same sensor. GPS calls this dilution of precision.

Failure: the symptom is an ellipse that looks tight around a wrong answer. Measure the residuals against σ: if they are far larger, the model is wrong and C is too small. Fix: correct the model, or scale C by the cost per degree of freedom, F/(m − n). Here m is the number of readings and n the number of unknowns.

Why does the ellipse stretch when all beacons sit on one side?

Chapter 9

The Trilateration Lab

Run every piece at once, and break it on purpose

The lab has four beacons, a robot and a start. Drag any of them. The shading is the cost F over the floor. The solver walks from the start toward the darkest spot and leaves a trail.

Solve, then break it

Drag beacons (blue), the robot (teal) and the start (orange). Step or run the solver. Turn on the echo and a kernel.

0.30 m

Illustrative toy. Noise is a fixed pseudo-random draw scaled by the slider, so a run repeats. The echo adds 4 m to beacon four. We draw the ellipse 5 times larger.

Try these in order:

  1. Run Levenberg-Marquardt with the defaults. It lands near the robot in a few steps.
  2. Drag the start to a far corner and switch to Gauss-Newton. Watch for a red step that climbs.
  3. Drag three beacons into a tight group. The dark valley stretches and the ellipse grows.
  4. Turn on the echo. The dark spot slides away from the robot. Switch to Cauchy and run again.

Failure on purpose: push the noise to 1 m and cluster all four beacons. The bowl turns flat and wide. No solver can recover information the readings never held; an honest solver reports a big ellipse instead of a confident wrong answer.

You turn on the echo and the dark spot moves away from the robot. What brings it back?

Chapter 10

Field Guide

Keep the terms, the numbers, the loop and the next steps in one place

Nonlinear least squares finds the parameters that make the sum of squared residuals smallest. Gauss-Newton linearizes and solves the normal equations. Levenberg-Marquardt damps that step. Sparsity makes it scale, kernels make it robust, and the inverse curvature says how far to trust it.

TermWhat it isNumber in this lesson
Residual r-iPredicted minus measured1.871 m for beacon one at (5, 5)
Cost FSum of squared residuals4.393 at (5, 5); 0.0277 at the answer
Jacobian row J-iUnit vector from beacon to guess(−0.707, 0.707) for beacon two at (5, 5)
Gauss-Newton stepSolve J-transpose J delta = minus J-transpose r(−1.712, −0.934) from (5, 5)
Damping lambdaTrust knob added to the diagonallambda 5 shortens the step to 0.35 m
Schur complement SCamera-only system after removing landmarks1,200 of 151,200 unknowns
Huber weight1 inside delta, delta over the miss outside0.25 for a 4 m miss
Covariance Csigma squared times (J-transpose J) inverse0.27 m in x, 0.24 m in y

Which tool when

SituationReach for
Model is linear in the unknownsNormal equations or lstsq, one shot
Curved model, good startGauss-Newton
Curved model, rough startLevenberg-Marquardt (the usual default)
Thousands of unknowns in small groupsSparse solver with the Schur complement
Some readings are wrongHuber or Cauchy kernel through IRLS
A consumer needs an error barsigma squared times (J-transpose J) inverse at the answer

Checklist

  1. Check the Jacobian against finite differences before anything else.
  2. Print the cost every step. It must fall, or the solver must reject the step.
  3. Look at the final residuals divided by sigma. Above 3 means a suspect reading.
  4. Report the covariance at the answer, scaled by sigma squared.
  5. If the ellipse is long, fix the geometry, not the solver.

The whole loop

pythonimport numpy as np
from scipy.optimize import least_squares

B = np.array([[0, 0], [10, 0], [0, 10]], dtype=float)   # beacons [3, 2]
z = np.array([5.2, 8.0, 6.9])                            # measured ranges [3]

def residuals(p):  return np.linalg.norm(p - B, axis=1) - z     # [3]
def jacobian(p):   d = p - B; return d / np.linalg.norm(d, axis=1)[:, None]   # [3, 2]

def lm(p, lam=1.0, iters=50):
    cost = sum(residuals(p)**2)
    for _ in range(iters):
        J, r = jacobian(p), residuals(p)
        step = np.linalg.solve(J.T @ J + lam * np.eye(2), -J.T @ r)
        new = sum(residuals(p + step)**2)
        if new < cost: p, cost, lam = p + step, new, lam / 3   # accept, trust more
        else:          lam = lam * 3                           # reject, trust less
    J = jacobian(p)
    return p, 0.3**2 * np.linalg.inv(J.T @ J)                 # answer, covariance

p, C = lm(np.array([12.0, 0.0]))                             # [3.2052, 4.0187]
sol = least_squares(residuals, [12, 0], jac=jacobian, method="lm")   # same answer
rob = least_squares(residuals, [5, 5], loss="huber", f_scale=1.0)    # robust version

Where to use it next

The takeaway. Guess, linearize, solve a small linear system, step only if the cost falls, and read the error bar off the same matrix.

Now press Present or Teach. Explain from memory the cost, one Jacobian row, the Gauss-Newton step, lambda and the error ellipse. Then go back to the hero and race the three solvers from the corner again. Say why Gauss-Newton climbs first.

Nonlinear Least Squares: Gauss-Newton, Levenberg-Marquardt and Bundle Adjustment
Jacobians and Linearization · Factor Graphs · Back to Gleams