Lite / Textbooks / Applied Engineering Mathematics / Chapter 2
2. Least squares and model fitting
Introduction
Real data never lies exactly on a model, so engineers choose the parameters that make the squared misfit as small as possible. This chapter derives the normal equations, shows that least squares is also the best estimator when noise is normal, and turns fitting into evidence: residuals that look like random scatter, parameters with standard errors, and a model tested on data it has never seen.
Figure 2.1. A line through scattered points (described in words)
Five illustrative points at x = 0 to 4 with y = 1.1, 2.9, 5.2, 6.8 and 9.0. The least-squares line is y = 1.97x + 1.06. Dashed vertical residuals of 0.04, −0.13, 0.2, −0.17 and 0.06 sum to zero, with a sum of squares of 0.091.
Explanation
Built from 4 School lessons. Each part is the lesson's own explanation.
2.1 Least squares and the normal equations
Seven measurements, two unknowns, no exact solution. What is the most honest 'best' answer?
Over-determined systems
More equations than unknowns, with noise, means no exact solution. Least squares chooses p to minimise ‖y − Ap‖²: the total squared vertical miss. The answer always exists, and it is unique when A's columns are independent (for a line: at least two distinct x values).
Reading residuals
Plot residuals against x. Random scatter around zero suggests the model is adequate. A curve suggests the wrong model (try a quadratic or a transformation). A funnel suggests noise growing with x. One huge residual suggests an outlier, and squaring gives it a lot of influence.
Linear in the parameters
'Linear' least squares means linear in p, not in x. y = a + bx + cx² is still linear least squares (three columns 1, x, x²). Exponential decays can be fitted by taking logs: ln(peak) = ln A₀ − ζω t, a straight line in t. You will use this in week 8.
Derivation: Normal equations for a straight line
Model yᵢ ≈ m·xᵢ + c. Stack all points: A·p ≈ y with A = [[x₁, 1], …, [xₙ, 1]] and p = (m, c). With n > 2 points there is usually no exact solution.
Residual vector r = y − A·p. Minimise S(p) = ‖r‖² = Σ (yᵢ − m xᵢ − c)².
∂S/∂m = −2 Σ xᵢ(yᵢ − m xᵢ − c) = 0 and ∂S/∂c = −2 Σ (yᵢ − m xᵢ − c) = 0.
So m Σxᵢ² + c Σxᵢ = Σxᵢyᵢ and m Σxᵢ + c·n = Σyᵢ. In matrix form: AᵀA·p = Aᵀy.
Solve: m = (nΣxy − ΣxΣy)/(nΣx² − (Σx)²), c = (Σy − mΣx)/n. Geometrically, Aᵀr = 0: the residual is perpendicular to every column of A.
Caution: κ(AᵀA) = κ(A)², so for ill-conditioned fits, libraries solve via QR instead of forming AᵀA.
Common mix-ups
Least squares only fits straight lines.
✓ It fits any model linear in its parameters, including polynomials and transformed models.A high R² proves the model is right.
✓ Check the residual pattern; a curved model can fit a straight line well and still be wrong.
Open the Lite lesson: Least squares and the normal equations
2.2 Least squares as an estimator
A rover logs its position every second. Fitting a line gives its speed. How sure can you be of that speed?
The model and the criterion
Model: yᵢ = m·xᵢ + c + εᵢ. Least squares picks m, c to minimise S = Σ(yᵢ − mxᵢ − c)². Setting ∂S/∂m = ∂S/∂c = 0 gives the normal equations; their solution is m̂ = Σ(xᵢ − x̄)(yᵢ − ȳ) / Σ(xᵢ − x̄)² and ĉ = ȳ − m̂x̄.
Matrix form
Stack the data as y = Aθ + ε with A's rows [xᵢ, 1] and θ = [m, c]ᵀ. The estimate is θ̂ = (AᵀA)⁻¹Aᵀy, the same formula for any linear-in-parameters model (polynomials, sensor calibration curves). With noise variance σ², Cov(θ̂) = σ²(AᵀA)⁻¹.
How certain is the slope?
From that covariance, SE(m̂) = σ/√Σ(xᵢ − x̄)². Spreading the x-values out, or taking more points, shrinks it. If σ is unknown, estimate it from the residuals: s² = Σ rᵢ²/(n − 2), dividing by n − 2 because two parameters were fitted.
Derivation: The least-squares slope
S(m, c) = Σ(yᵢ − mxᵢ − c)².
∂S/∂c = −2Σ(yᵢ − mxᵢ − c) = 0 ⇒ c = ȳ − m x̄.
Substitute: S = Σ((yᵢ − ȳ) − m(xᵢ − x̄))².
∂S/∂m = −2Σ(xᵢ − x̄)((yᵢ − ȳ) − m(xᵢ − x̄)) = 0.
So m̂ = Σ(xᵢ − x̄)(yᵢ − ȳ) / Σ(xᵢ − x̄)², which equals (nΣxy − ΣxΣy)/(nΣx² − (Σx)²).
Common mix-ups
More points always help equally wherever they go.
✓ Points far from x̄ constrain the slope much more than points near the middle.A good-looking fit means a precise slope.
✓ Report SE(m̂). A line through 3 tightly clustered points can look perfect and still be very uncertain.
Open the Lite lesson: Least squares as an estimator
2.3 Fitting a cooling model to data
You have a column of temperatures from a cooling mug and one unknown number, k. How do you pull k out of noisy data, and how sure can you be?
Linearise, then fit a line
Subtract the room temperature, take natural logs, plot against t. The slope of the best straight line is −k, the intercept ln(T₀ − Tₐ). A least-squares line through all points uses every reading, so it is far less sensitive to one bad reading than a two-point estimate.
Two-point estimate
From readings at t₁ and t₂: k = ln[(T₁ − Tₐ)/(T₂ − Tₐ)]/(t₂ − t₁). Quick and useful as a sanity check, but it rests entirely on two noisy numbers. Example: 86 °C at 0 min and 63.7 °C at 10 min in a 21 °C room give k = ln(65/42.7)/10 ≈ 0.042 per minute.
What distorts the fit
Noise near Tₐ: when T − Tₐ is small, a 0.5 °C error is a large fraction, so late points scatter wildly in the log view. Weight them less or stop the fit early. Wrong Tₐ: guessing the room 2 °C too low makes the log plot curve. Early evaporation from a hot drink cools it faster at first than the model allows.
Common mix-ups
The two-point estimate is as good as a fit through all the data.
✓ It rests on two noisy numbers. A least-squares fit uses every reading.A good fit proves the model is right.
✓ It shows the model can describe this data. Testing on data not used for fitting (next lesson) is the real check.
Open the Lite lesson: Fitting a cooling model to data
2.4 Fitting and validating a model against data
A recorded decay gives you seven peaks. How do you get the damping out of them, and how do you know the model deserved to be fitted?
Question → method → evidence
Question: what is the damping, and does linear damping describe this system? Method: extract peaks, fit ln(peak) against t, then predict a second recording. Evidence: the fitted slope with its uncertainty, residual plot, and prediction error on the held-out recording.
A worked fit
For the diagram's decay data (peaks at t = 0…6 s), least squares gives slope −0.304 per second and intercept 0.012. So ζω_n ≈ 0.30 s⁻¹ and A₀ ≈ e^{0.012} ≈ 1.01. If the peak spacing gives ω_d = 2.0 rad/s, then ω_n ≈ 2.02 rad/s and ζ ≈ 0.15.
Validation, not just fitting
A model can always be fitted to the data it was fitted to. Validation uses different data: a second run, another amplitude, a different day. Report the prediction error there. Patterned residuals (for example a curve in ln(peak)) suggest a wrong assumption, such as friction that does not scale with speed.
Derivation: Turning a decay into a straight-line fit
Underdamped solution: x(t) = A₀ e^{−ζω_n t} cos(ω_d t + φ). Peaks occur about every 2π/ω_d with heights Aₖ ≈ A₀ e^{−ζω_n tₖ}.
Take logs: ln Aₖ = ln A₀ − (ζω_n) tₖ. This is linear in the unknowns (ln A₀, ζω_n).
Fit yₖ = ln Aₖ against tₖ by least squares (week 5): slope m = −ζω_n, intercept c = ln A₀.
With ω_d measured from the peak spacing, ω_n = √(ω_d² + (ζω_n)²), so ζ = (ζω_n)/ω_n.
Caution: taking logs changes the noise. Small peaks have large relative noise, so ln weights them oddly; with good data this is a small effect, but it should be stated.
Common mix-ups
A good fit proves the model.
✓ It shows consistency with that data. Validation on new data and residual checks are needed.Taking logs is harmless.
✓ It changes how noise is weighted; say so, and check with a direct nonlinear fit if precision matters.
Open the Lite lesson: Fitting and validating a model against data
Worked examples
Least squares and the normal equations: example 1
Fit a line to (0, 1), (1, 3), (2, 4), (3, 6).
Solution
n = 4, Σx = 6, Σy = 14, Σx² = 14, Σxy = 0 + 3 + 8 + 18 = 29. m = (4·29 − 6·14)/(4·14 − 36) = (116 − 84)/20 = 1.6. c = (14 − 1.6·6)/4 = 1.1. Residuals: −0.1, 0.3, −0.3, 0.1, which sum to 0 ✓.
Least squares as an estimator: example 1
Points (0, 2.1), (1, 3.4), (2, 5.2), (3, 6.4), (4, 8.1). Find the slope.
Solution
x̄ = 2, ȳ = 5.04. Σ(x − x̄)(y − ȳ) = (−2)(−2.94) + (−1)(−1.64) + 0 + (1)(1.36) + (2)(3.06) = 5.88 + 1.64 + 1.36 + 6.12 = 15.0. Σ(x − x̄)² = 10. m̂ = 1.50.
Fitting a cooling model to data: example 1
Readings: 86 °C at t = 0, 63.7 °C at t = 10 min, room 21 °C. Estimate k and τ.
Solution
k = ln(65/42.7)/10 = ln(1.522)/10 = 0.420/10 = 0.042 per minute. τ = 1/k ≈ 23.8 min; half-life ≈ 16.5 min.
Fitting and validating a model against data: example 1
Peaks: 1.00, 0.74, 0.55, 0.41 at t = 0, 1, 2, 3 s. Estimate ζω_n.
Solution
ln peaks: 0, −0.301, −0.598, −0.892. These fall by about 0.297 per second; the least-squares slope is −0.297, so ζω_n ≈ 0.30 s⁻¹.
Interactive figures, in words
Figure 2.2 from Least squares and the normal equations
On 'Spring calibration', drag your slope and intercept to make Σr² as small as you can. Then reveal the least-squares line. Switch to the outlier set and see how far one bad reading drags the line.
The least-squares diagram plots data points, your adjustable line and vertical residual segments. Sliders set slope and intercept; text gives your sum of squared residuals, and a button reveals the optimal line and its sum.
Figure 2.3 from Fitting a cooling model to data
Choose the mug of tea. Adjust k by eye until the curve runs through the points, and note your RMS error. Switch on the log view: are the points straight? Press Best fit and compare its k with yours. Which points scatter most in the log view, and why?
The decay-fit lab shows synthetic cooling data: 16 readings from 86 °C towards a 21 °C room over 60 minutes. A model curve with the chosen k is drawn through them. In log view, ln(T − 21) against time is close to a straight line with slope −k; late points scatter more. The least-squares fit gives k close to 0.042 per minute.
Laboratory
These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.
- Simulation OS: RC charge and discharge (Simulation OS experiment)
Record the discharge curve, fit ln(V) against time by least squares and compare the fitted time constant with R·C.
Open on the full site - Equation Lab: Functions (Equation Lab exploration)
Fit linear and exponential families to the same data and decide from the residuals which shape is right.
Open on the full site
Practice
Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.
- At the least-squares solution, the residual vector r satisfies…
Answer it in “Least squares and the normal equations” - Which model can be fitted by linear least squares directly?
Answer it in “Least squares and the normal equations” - One reading is wildly wrong. What happens to the least-squares line?
Answer it in “Least squares and the normal equations” - To estimate a drift rate as precisely as possible with 10 measurements over a fixed hour, you should take them…
Answer it in “Least squares as an estimator” - Why divide the residual sum of squares by n − 2 to estimate σ² in a straight-line fit?
Answer it in “Least squares as an estimator” - With k = 0.042 per minute, what is the time constant τ, in minutes?
Answer it in “Fitting a cooling model to data” - You assumed Tₐ = 18 °C but the room was really 22 °C. What will the ln(T − Tₐ) plot show?
Answer it in “Fitting a cooling model to data” - Which is the best evidence that your fitted model is useful?
Answer it in “Fitting and validating a model against data”
Engineering applications
Identifying a plant
Before tuning a controller, engineers fit a simple model to a step test. A least-squares fit of gain and time constant, with residuals checked, is usually enough to start.
Drift rates
A slowly drifting sensor is characterised by fitting a straight line to a long log. Readings spread over a long time give a far more precise slope than many readings taken close together.
Watch (optional)
Streaming video uses a lot of data. Everything you need is in the text.
- “16. Projection Matrices and Least Squares” by MIT OpenCourseWare
- “Linear Regression, Clearly Explained!!!” by StatQuest with Josh Starmer
Summary
- Least squares picks the parameters that minimise the sum of squared residuals.
- At the solution the residual is perpendicular to every column of A: the normal equations AᵀA·x = Aᵀb.
- Models linear in their parameters can be fitted directly; others can often be transformed, such as taking logs of an exponential.
- A fit is evidence only when residuals look random and the model predicts held-out data.
Glossary
- Gradient of a straight line
- The gradient of a straight line is the change in y divided by the change in x between any two points on it; in y = mx + c it is m, and c is where the line crosses the y-axis. Field Guide
- Exponential growth and decay
- A quantity decays exponentially when its rate of decrease is proportional to how much is left, giving y = y0 × e^(−t/τ). Field Guide
- Outliers and honest data
- An outlier is a reading far from the rest. It may be a genuine effect or a fault; either way it must be investigated and reported, and any exclusion rule decided before seeing the results. Field Guide
- Standard deviation
- Standard deviation measures how spread out values are around their mean: the square root of the average squared distance from the mean. Field Guide
Project: Fit, then try to break the fit
Choose a data set from a School simulation (for example RC discharge or cooling). Fit a model by least squares on half the data, plot the residuals, then predict the other half. Report the parameters with standard errors and the worst prediction error.
Deliverables
- The fitted model with parameter uncertainties
- A residual plot and what it shows
- Held-out prediction errors and a verdict on the model
Write it up on paper or in your own notes. Lite never stores what you write.
References
- Gilbert Strang (2016). Introduction to Linear Algebra, 5th edition. Wellesley-Cambridge Press.
- Douglas C. Montgomery and George C. Runger (2014). Applied Statistics and Probability for Engineers, 6th edition. Wiley.
- Erwin Kreyszig (2011). Advanced Engineering Mathematics, 10th edition. Wiley.