Geometrically: ranges over the column space as varies, so we're asking for the point of closest to — the orthogonal projection . The minimising residual is perpendicular to , i.e. lies in :
If there are infinitely many , but they all give the same projection .
Fitting data by least squares
- 1Write the model with unknown coefficients
Line: . Quadratic: . The unknowns are the , and the model must be linear in the coefficients — is not, directly.
- 2Build by plugging each data point into the model
Row holds the values that multiply each coefficient at ; holds the observed .
- 3Form and , then solve
is small () and symmetric; solve by elimination.
- 4Check the residual is orthogonal to the columns of
For a fit with a constant term, the first column of is all ones, so the residuals must sum to zero. That's a fast free check.
Best-fit line through three points
Least squares via the normal equations
Enter the augmented matrix (A | b) — one row per equation, last column is b. Everything stays exact because AᵀA and Aᵀb are rational.
| 1 | 1 |
| -2 | 3 |
| 2 | -1 |
| 3 |
| 1 |
| 2 |
| 9 | -7 |
| -7 | 11 |
| 5 |
| 4 |
| 83/50 |
| 71/50 |
| 77/25 |
| 47/50 |
| 19/10 |
If the last column of A is a column of x-powers, these are the coefficients of the best-fit polynomial, in the order the columns appear.