Textbooks/Applied Engineering Mathematics/Chapter 2Lite (plain text) version
2Least squares and model fitting
Version 1 · Technically checked (automated checks only) · 4 source lessons · 8 practice items
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.
Explanation
This chapter is built from 4 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.
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 full 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.
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.
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 full 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
Interactive figure (online). Description: 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.
Interactive figure (online). Description: 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
Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.
Simulation OS experiment
Simulation OS: RC charge and discharge
Record the discharge curve, fit ln(V) against time by least squares and compare the fitted time constant with R·C.
Open Simulation OS: RC charge and discharge →Equation Lab exploration
Equation Lab: Functions
Fit linear and exponential families to the same data and decide from the residuals which shape is right.
Open Equation Lab: Functions →
Guided practice
Answers are checked on the server; wrong answers get a hint and another try. Signed in, solved items also count towards the source lesson.
- At the least-squares solution, the residual vector r satisfies…
- r = 0
- Aᵀr = 0
- ‖r‖ = 1
- Which model can be fitted by linear least squares directly?
- y = a·sin(ωt) with unknown ω
- y = a + b·t + c·t²
- y = a·e^{bt} without taking logs
- One reading is wildly wrong. What happens to the least-squares line?
- Nothing: one point cannot matter
- It is pulled noticeably towards the outlier
- The fit fails to compute
- To estimate a drift rate as precisely as possible with 10 measurements over a fixed hour, you should take them…
- 5 at the start and 5 at the end
- All in the middle
- Evenly spaced
- All at the end
- Why divide the residual sum of squares by n − 2 to estimate σ² in a straight-line fit?
- Two parameters were fitted from the data, using up two degrees of freedom
- It is a convention with no reason
- To make the estimate smaller
- Because the first and last points are excluded
- With k = 0.042 per minute, what is the time constant τ, in minutes? (min)
- You assumed Tₐ = 18 °C but the room was really 22 °C. What will the ln(T − Tₐ) plot show?
- A perfect straight line anyway
- A curve that flattens at late times instead of a straight line
- A line with positive slope
- Which is the best evidence that your fitted model is useful?
- Tiny residuals on the fitting data
- Small prediction error on a separate recording
- A very complicated model
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 verified videos. Nothing loads from YouTube until you press play.
- 16. Projection Matrices and Least Squares (MIT OpenCourseWare)
- Linear Regression, Clearly Explained!!! (StatQuest with Josh Starmer)
Chapter 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.
- 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/τ).
- 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.
- Standard deviation
- Standard deviation measures how spread out values are around their mean: the square root of the average squared distance from the mean.
Definitions from the 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
Keep your work in your Engineering Journal; it stays private unless you choose to share it.
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.
Publication record
- Version
- 1
- Status
- Technically checked (automated checks only)
- Technical review
- Automated checks only, last run 2026-11-29. No human, educator or mentor review is claimed.src/content/textbooks/textbooks.test.ts: schema, every lesson, diagram, practice item, video, Field Guide entry, lab and reference resolves; figure numbers recomputed; no practice answers in client payloads.
- Written by
- Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
- Licence
- All rights reserved by the founders unless a licence is approved.
- Corrections
- None recorded yet.Spotted a mistake? Use “Report a problem” on any chapter, or see the corrections page.