TactivergeOffline

Applied Engineering Mathematics

Linear systems, fitting, stability, Fourier thinking, numerical methods and statistics, used the way engineers use them

Read The Mathematics of Machines first: this book assumes its algebra, calculus, vectors and first matrices. Eight chapters then put that toolkit to work on harder questions. When is a linear solve trustworthy? How do you fit, linearise and test a model? Will a system settle? What is a signal made of? How small a step is small enough? And how sure are you of the answer? Every chapter composes Systems Engineer and Research Engineer lessons, with practice checked on the server.

Version 1 · Technically checked (automated checks only) · 8 chapters · 64 practice questions (questions only)

Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.

1. Linear systems in practice

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

Circuits, trusses and calibration problems all arrive as many linear equations at once. This chapter writes them as A·x = b, treats matrix multiplication as doing one map after another, and asks the practical questions a textbook exercise skips: should you ever form an inverse, and how much can you trust the answer? The condition number is the honest measure. When it is large, a tiny error in the data can move the solution a long way.

Figure 1.1. Two nearly parallel lines (described in words)

Two almost parallel lines, x + y = 2 and x + 1.01y = 2.01, cross at (1, 1). Changing the second right-hand side by only 0.01, to 2.02, moves the crossing all the way to (0, 2). The matrix has a condition number of about 402, so small data errors are greatly amplified.

Explanation

1.1 Writing engineering problems as Ax = b

A resistor network, a loaded frame and a cross-talking sensor pair look nothing alike. Why does one line of code solve all three?

A recipe for modelling
  1. Choose unknowns (loop currents, member tensions, true quantities). 2. Write one equation per physical law: Kirchhoff's voltage law per loop, ΣF = 0 per direction per joint, one sensor model per reading. 3. Collect coefficients into A, knowns into b. 4. Count: as many independent equations as unknowns for a unique answer.
Example: two-loop circuit

A 2 V source drives loop 1 through 2 Ω, and loop 2 contains a 3 V source and 1 Ω. A 1 Ω resistor is shared. KVL in loop 1: 2I₁ + 1(I₁ − I₂) = 2, so 3I₁ − I₂ = 2. Loop 2: 1(I₂ − I₁) + 1·I₂ = 3, so −I₁ + 2I₂ = 3. So A = [[3, −1], [−1, 2]], b = (2, 3), and I = (1.4, 2.2) A.

Always check the residual

Compute r = b − A·x. A tiny residual says you solved the equations you wrote; it does not say they were the right equations. So also sanity-check physics: are currents in a sensible direction, do tensions in a hanging cable come out positive, does the answer change sensibly when you double a source?

Common mix-ups

1.2 Matrix multiplication as composition

Rotate then shear, or shear then rotate: the same two moves, different results. Why does order matter for matrices?

The rule

If A is m×n and B is n×p, then AB is m×p with (AB)ᵢⱼ = Σₖ aᵢₖbₖⱼ: row i of A dotted with column j of B. Inner dimensions must match. Equivalently, column j of AB is A times column j of B.

Composition

(BA)x = B(Ax): first A acts, then B. So BA means 'A then B', read right to left, just like function composition f(g(x)). Associativity, (CB)A = C(BA), lets you pre-multiply a chain of frames into one matrix once.

Order and transposes

In general AB ≠ BA; commuting is the exception (for example two rotations about the same axis, or diagonal matrices). The transpose swaps rows and columns, and reverses products: (AB)ᵀ = BᵀAᵀ. Similarly (AB)⁻¹ = B⁻¹A⁻¹: to undo 'put on socks, then shoes', take off shoes first.

Common mix-ups

1.3 Inverses: undoing a linear map

A sensor matrix turns true forces into readings. Can you always run it backwards to turn readings into forces?

What an inverse is

A⁻¹ is the matrix with A⁻¹A = AA⁻¹ = I. It exists exactly when A is square with det A ≠ 0 (rank n). Then Ax = b has the unique solution x = A⁻¹b. Geometrically, the map must not squash any direction to zero, or it cannot be undone.

Gauss–Jordan for bigger matrices

Write [A | I] and row-reduce all the way to [I | X]: eliminate below and above each pivot and scale pivots to 1. Then X = A⁻¹. If a zero pivot cannot be fixed by swapping, A is singular.

Solve, don't invert

In computation, forming A⁻¹ costs about three times more than an LU solve and is typically less accurate. Libraries offer solve(A, b) for this reason. Inverses remain useful on paper, for small fixed matrices, and when you genuinely need the entries (for example a covariance matrix).

Derivation: The 2×2 inverse formula
  1. Let A = [[a, b], [c, d]]. We want X with AX = I.

  2. Try X = k·[[d, −b], [−c, a]] (swap the diagonal, negate the off-diagonal).

  3. Then AX = k·[[ad − bc, −ab + ba], [cd − dc, −cb + da]] = k·(ad − bc)·I.

  4. Choosing k = 1/(ad − bc) gives AX = I, so A⁻¹ = (1/det A)·[[d, −b], [−c, a]].

  5. This only works if det A = ad − bc ≠ 0; when it is zero there is no inverse.

Common mix-ups

1.4 Conditioning: when small errors become big ones

Your solver is perfect, your sensors are 0.1% accurate, and your answer is 50% wrong. Who is to blame?

A property of the problem

κ(A) ≥ 1 measures how sensitive the solution of Ax = b is to changes in b (and in A). κ ≈ 1 is perfect (rotations, orthogonal matrices); κ = 10⁶ means relative data errors may be magnified up to a million times. It is a property of the problem itself, so no algorithm can beat it.

Determinant is not the test

det(0.01·I) in 10 dimensions is 10⁻²⁰, yet κ = 1: it is perfectly conditioned, just scaled. [[1, 1], [1, 1.0001]] has det 10⁻⁴ and κ ≈ 4×10⁴. Use κ, not det, to judge closeness to singularity.

Problem versus algorithm

Conditioning is about the problem; stability is about the algorithm. Elimination without pivoting on the tiny-pivot example is an unstable algorithm on a well-conditioned problem (κ ≈ 2.6). Pivoting fixes the algorithm. For an ill-conditioned problem, the fix is to change the problem: better sensor placement, rescaling, or more independent measurements.

Derivation: The error-amplification bound
  1. Exact: Ax = b. Perturbed data: A(x + δx) = b + δb. Subtract: A·δx = δb, so δx = A⁻¹δb.

  2. Take norms: ‖δx‖ ≤ ‖A⁻¹‖·‖δb‖. Also ‖b‖ = ‖Ax‖ ≤ ‖A‖·‖x‖, so 1/‖x‖ ≤ ‖A‖/‖b‖.

  3. Multiply: ‖δx‖/‖x‖ ≤ ‖A‖·‖A⁻¹‖·‖δb‖/‖b‖.

  4. Define κ(A) = ‖A‖·‖A⁻¹‖. In the 2-norm this is σmax/σmin, the ratio of the largest to smallest singular value.

  5. Rule of thumb: you can lose about log₁₀ κ significant digits. With double precision (about 16 digits) and κ = 10¹⁰, expect about 6 good digits.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Writing engineering problems as Ax = b: example 1

Two sensors read r₁ = q₁ + 0.5q₂ and r₂ = 0.25q₁ + q₂. Readings are r = (3, 2.5). Find the true quantities q.

Matrix multiplication as composition: example 1

Compute AB for A = [[1, 2], [3, 4]], B = [[0, 1], [1, 0]], and BA.

Inverses: undoing a linear map: example 1

Invert A = [[3, 1], [2, 5]] and check.

Conditioning: when small errors become big ones: example 1

κ(A) = 10⁴ and the measurements in b have 0.01% relative error. What is the worst-case relative error in x?

Interactive figures, in words

Figure 1.2 from “Matrix multiplication as composition”

Load 'Shear' into A and choose 'Then apply B: Rotate 30°'. Note where î and ĵ land. Now load 'Rotate 30°' into A and apply B = 'Shear'. Same two maps, different picture. Check that det(BA) = det(B)·det(A) both times.

The transformation grid shows a grid and unit square mapped by the combined matrix B·A, with î and ĵ drawn as labelled arrows. Text gives the combined matrix entries and det A, det B and det(BA).

Figure 1.3 from “Conditioning: when small errors become big ones”

Set ε = 1 and nudge b₂. Then slide ε down to 10⁻⁴. For each, record κ, the relative change in b and the relative change in x. Does the amplification ever exceed κ?

The condition explorer draws two lines whose intersection is the solution, plus a dashed nudged line and the new intersection. Sliders set ε and the nudge. Text reports κ, both solutions and the relative changes in b and x.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. For the circuit in the lesson (3I₁ − I₂ = 2, −I₁ + 2I₂ = 3), what is I₂ in amperes?

Answer: A

Check it in “Writing engineering problems as Ax = b”

2. Your solver returns x with residual ‖b − Ax‖ ≈ 10⁻¹⁴. What have you shown?

  • That the physical model is correct
  • That x solves the equations you wrote, to rounding error
  • That the answer has 14 correct digits

Check it in “Writing engineering problems as Ax = b”

3. To apply A first and then B to a vector x, you compute…

  • ABx
  • BAx
  • Either: they are equal

Check it in “Matrix multiplication as composition”

4. A is 3×2 and B is 2×4. What size is AB?

  • 2×2
  • 3×4
  • It is undefined

Check it in “Matrix multiplication as composition”

5. A colleague computes x = inv(A) * b for a 5000×5000 system. Best advice?

  • Fine: that is the standard method
  • Use solve(A, b) (LU): cheaper and more accurate
  • Use Cramer's rule

Check it in “Inverses: undoing a linear map”

6. κ = 500, relative error in b is 0.002 (0.2%). What is the worst-case relative error in x?

Answer:

Check it in “Conditioning: when small errors become big ones”

7. Working with about 16 significant digits and κ = 10⁹, roughly how many digits of x can you trust?

Answer:

Check it in “Conditioning: when small errors become big ones”

8. A calibration matrix has κ = 10⁷. What actually helps?

  • Use a more accurate solver
  • Redesign the measurements so the columns are less alike
  • Round the answer to fewer digits

Check it in “Conditioning: when small errors become big ones”

Engineering applications

Circuit simulators

A simulator writes one current-balance equation per node and solves them together. It never forms an inverse: elimination on the system is faster and loses fewer digits.

Calibration fits

A sensor calibrated from readings bunched in a narrow range gives a badly conditioned system. Spreading the calibration points across the whole range is the cheapest fix.

Summary

Glossary

Matrix multiplication
Multiplying matrices combines rows of the first with columns of the second: each entry of the result is a dot product of a row and a column.
Kirchhoff's current law (KCL)
At any junction in a circuit, the total current flowing in equals the total current flowing out.
Floating-point rounding and comparison
Most decimal fractions cannot be stored exactly in binary floating point, so tiny rounding errors appear and == between floats is unreliable.
Absolute and relative uncertainty
Absolute uncertainty is the ± range in the same units as the measurement; relative uncertainty is that range divided by the measurement, often as a percentage.

Project: How fragile is my network?

Pick a small resistor network or a two-member truss. Write it as A·x = b, solve it, then repeat with each input changed by 1 %. Estimate the condition number and say whether the measured sensitivity matches it.

Deliverables

  • The system written as A·x = b with units
  • The solution and the perturbed solutions
  • A condition-number estimate with a one-paragraph interpretation

References

2. Least squares and model fitting

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

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

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
  1. 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.

  2. Residual vector r = y − A·p. Minimise S(p) = ‖r‖² = Σ (yᵢ − m xᵢ − c)².

  3. ∂S/∂m = −2 Σ xᵢ(yᵢ − m xᵢ − c) = 0 and ∂S/∂c = −2 Σ (yᵢ − m xᵢ − c) = 0.

  4. So m Σxᵢ² + c Σxᵢ = Σxᵢyᵢ and m Σxᵢ + c·n = Σyᵢ. In matrix form: AᵀA·p = Aᵀy.

  5. 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.

  6. Caution: κ(AᵀA) = κ(A)², so for ill-conditioned fits, libraries solve via QR instead of forming AᵀA.

Common mix-ups

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
  1. S(m, c) = Σ(yᵢ − mxᵢ − c)².

  2. ∂S/∂c = −2Σ(yᵢ − mxᵢ − c) = 0 ⇒ c = ȳ − m x̄.

  3. Substitute: S = Σ((yᵢ − ȳ) − m(xᵢ − x̄))².

  4. ∂S/∂m = −2Σ(xᵢ − x̄)((yᵢ − ȳ) − m(xᵢ − x̄)) = 0.

  5. So m̂ = Σ(xᵢ − x̄)(yᵢ − ȳ) / Σ(xᵢ − x̄)², which equals (nΣxy − ΣxΣy)/(nΣx² − (Σx)²).

Common mix-ups

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

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
  1. Underdamped solution: x(t) = A₀ e^{−ζω_n t} cos(ω_d t + φ). Peaks occur about every 2π/ω_d with heights Aₖ ≈ A₀ e^{−ζω_n tₖ}.

  2. Take logs: ln Aₖ = ln A₀ − (ζω_n) tₖ. This is linear in the unknowns (ln A₀, ζω_n).

  3. Fit yₖ = ln Aₖ against tₖ by least squares (week 5): slope m = −ζω_n, intercept c = ln A₀.

  4. With ω_d measured from the peak spacing, ω_n = √(ω_d² + (ζω_n)²), so ζ = (ζω_n)/ω_n.

  5. 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

Examples to try

Worked solutions are in the interactive chapter online.

Least squares and the normal equations: example 1

Fit a line to (0, 1), (1, 3), (2, 4), (3, 6).

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.

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 τ.

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.

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 (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. At the least-squares solution, the residual vector r satisfies…

  • r = 0
  • Aᵀr = 0
  • ‖r‖ = 1

Check it in “Least squares and the normal equations”

2. 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

Check it in “Least squares and the normal equations”

3. 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

Check it in “Least squares and the normal equations”

4. 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

Check it in “Least squares as an estimator”

5. 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

Check it in “Least squares as an estimator”

6. With k = 0.042 per minute, what is the time constant τ, in minutes?

Answer: min

Check it in “Fitting a cooling model to data”

7. 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

Check it in “Fitting a cooling model to data”

8. 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

Check 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.

Summary

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.

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

References

3. Linearisation, Jacobians and Newton's method

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

Most real systems are nonlinear, but near any operating point they behave almost linearly. This chapter turns that idea into tools: a matrix as a linear map, the Jacobian as the best linear map at a point, linearised models whose eigenvalues reveal local behaviour, and Newton's method, which solves nonlinear equations by repeatedly solving the linear approximation.

Figure 3.1. Riding the tangent to √2 (described in words)

The curve f(x) = x² − 2 with tangent lines. Starting at x0 = 2, the first tangent meets the axis at x1 = 1.5, the next at x2 = 1.41667 and then x3 = 1.41422, already within 0.00002 of √2 = 1.41421. The number of correct digits roughly doubles each step.

Explanation

3.1 Rotation, shear, stretch and projection

Every 2×2 matrix is a picture. Can you guess what [[1, 1], [0, 1]] does to a square before you calculate anything?

Columns are images of the basis

A·(x, y) = x·A(î) + y·A(ĵ). So column 1 is A(î) and column 2 is A(ĵ). Linear maps keep the origin fixed, keep lines straight and keep evenly spaced grid lines evenly spaced.

A catalogue

Rotation by θ: [[cos θ, −sin θ], [sin θ, cos θ]], det 1. Shear: [[1, k], [0, 1]], det 1. Stretch: [[s₁, 0], [0, s₂]], det s₁s₂. Reflection in the x-axis: [[1, 0], [0, −1]], det −1. Projection onto the x-axis: [[1, 0], [0, 0]], det 0.

Projections

A projection P drops each vector onto a subspace. Doing it twice changes nothing more, so P² = P. It squashes a direction to zero, so det P = 0 and there is no inverse: from the shadow you cannot recover the object. Projection onto a unit vector u is P = uuᵀ, which reappears in least squares.

Common mix-ups

3.2 Module check: the Jacobian as a linear map

Near any pose, a robot arm behaves like a matrix. What can that matrix tell you about where the arm can and cannot move?

Question → method → evidence

Question: at a given pose, which hand motions are possible and how much joint motion do they need? Method: linearise to J, then treat Δp = J·Δθ as a linear system. Evidence: solve for Δθ, compare the predicted hand motion with the exact forward kinematics, and examine det J and the columns of J.

Columns tell the story

Column 1 of J is the hand velocity from turning joint 1 alone; column 2 from joint 2 alone. Their span is the set of achievable hand velocities. If the columns become parallel, the span collapses to a line, exactly as in week 1's column picture.

Near-singular is already bad

Close to a singularity, det J is small and J⁻¹ has huge entries: a modest hand step demands enormous joint speeds, and sensor noise in θ is amplified. Controllers use damped least squares or avoid such poses. This links straight to conditioning in week 5.

Derivation: The two-link Jacobian
  1. Hand position: x = L₁cos θ₁ + L₂cos(θ₁ + θ₂), y = L₁sin θ₁ + L₂sin(θ₁ + θ₂).

  2. Small changes: Δx ≈ (∂x/∂θ₁)Δθ₁ + (∂x/∂θ₂)Δθ₂, and the same for y. In matrix form Δp ≈ J·Δθ.

  3. J = [[−L₁sin θ₁ − L₂sin(θ₁ + θ₂), −L₂sin(θ₁ + θ₂)], [L₁cos θ₁ + L₂cos(θ₁ + θ₂), L₂cos(θ₁ + θ₂)]].

  4. det J = L₁L₂[sin(θ₁ + θ₂)cos θ₁ − cos(θ₁ + θ₂)sin θ₁] = L₁L₂ sin θ₂.

  5. Where det J ≠ 0, Δθ = J⁻¹Δp gives the joint step for a desired hand step. Where det J = 0, J has rank 1 and some Δp cannot be produced.

Common mix-ups

3.3 Linearising nonlinear models

A pendulum hanging down is stable; balanced upright it falls. One Jacobian matrix explains both. How?

The method
  1. Find equilibria by solving f(x*) = 0. 2. Compute the Jacobian J = ∂f/∂x. 3. Evaluate it at each equilibrium. 4. Classify with the eigenvalues (week 6). If no eigenvalue has zero real part, the nonlinear system behaves like its linearisation close to that point (the Hartman–Grobman theorem).
Validity

The linear model is accurate only for small deviations. For the pendulum, sin θ ≈ θ is within 1% for |θ| below about 14°. A centre in the linearisation (zero real parts) is inconclusive: the nonlinear terms decide. Always state the range over which you trust the linear model.

Why controllers love it

Linearise a balancing robot about upright, design a controller that moves the saddle's unstable eigenvalue into the left half-plane, then test the controller on the full nonlinear model to see how big a push it survives.

Derivation: Linearising the pendulum
  1. States θ and ω = θ′: θ′ = ω, ω′ = −(g/L) sin θ − bω. This is x′ = f(x), nonlinear because of sin θ.

  2. Equilibria: f = 0 needs ω = 0 and sin θ = 0, so θ = 0 (hanging) or θ = π (upright).

  3. Near an equilibrium x, write x = x + δ. Taylor: δ′ ≈ J(x*)·δ with J the Jacobian, Jᵢⱼ = ∂fᵢ/∂xⱼ.

  4. Here J = [[0, 1], [−(g/L) cos θ, −b]].

  5. θ = 0: J = [[0, 1], [−g/L, −b]], tr = −b < 0, det = g/L > 0: a stable spiral (for small b). θ = π: J = [[0, 1], [g/L, −b]], det = −g/L < 0: a saddle, unstable.

Common mix-ups

3.4 Newton's method: ride the tangent

Bisection needs about 20 steps for six decimal places. Newton's method often needs four. What's the catch?

Fast when close

From a good starting guess, Newton's method converges quadratically: the number of correct digits roughly doubles each step. For x² − 2 from 1, four steps give about 12 correct digits, where bisection on [0, 2] would need about 40.

It needs the derivative

You must supply f′(x), worked out by hand or estimated numerically. If f′(x_k) = 0 the tangent is flat and never crosses zero: the method can't continue. Guard against it and cap the number of steps.

It can run away

If the start is far from the root, or the function flattens out, the tangent can throw the next guess further away. arctan x from x₀ = 1.5 diverges. Engineers often bracket first with bisection, then switch to Newton once close, or reject any Newton step that leaves the bracket.

Derivation: Where the Newton update comes from
  1. Near a guess x_k, replace the curve by its tangent line: y ≈ f(x_k) + f′(x_k)·(x − x_k).

  2. Find where that line crosses zero: 0 = f(x_k) + f′(x_k)·(x − x_k).

  3. Solve for x: x_{k+1} = x_k − f(x_k)/f′(x_k). This needs f′(x_k) ≠ 0.

  4. For f(x) = x² − c, f′(x) = 2x, so x_{k+1} = x_k − (x_k² − c)/(2x_k) = (x_k + c/x_k)/2: average the guess with c divided by the guess.

  5. Near a simple root the error obeys e_{k+1} ≈ C·e_k², so an error of 10⁻³ becomes about 10⁻⁶, then 10⁻¹². That's quadratic convergence.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Rotation, shear, stretch and projection: example 1

Write the matrix that rotates by 90° anticlockwise and check it sends (1, 0) to (0, 1).

Rotation, shear, stretch and projection: example 2

Find the matrix projecting onto the line through u = (1, 1)/√2.

Module check: the Jacobian as a linear map: example 1

L₁ = L₂ = 1, θ₁ = 0, θ₂ = 90°. Find J and the joint step for Δp = (0, 0.01).

Linearising nonlinear models: example 1

Find and classify the equilibria of x′ = y, y′ = x − x³.

Newton's method: ride the tangent: example 1

Newton's method with a step limit and a flat-slope guard, compared with the true root.

Interactive figures, in words

Figure 3.2 from “Linearising nonlinear models”

In 'Any 2×2 matrix' mode, enter the hanging-down linearisation [[0, 1], [−4, −0.5]], then the upright one [[0, 1], [4, −0.5]] (g/L = 4, b = 0.5). Compare the portraits and the classification.

In general mode the phase portrait is set to the pendulum's linearised matrices. Text reports trace, determinant, eigenvalues and the equilibrium type: stable spiral for hanging, saddle for upright.

Figure 3.3 from “Newton's method: ride the tangent”

Choose x² − 2 and Newton. Step four times and compare the error column with bisection's. Then choose arctan x (Newton trap): start at 1.0, then at 1.5. What does the tangent do from 1.5?

The stepper shows Newton's method on x² − 2 from 1: the orange tangent at each guess meets the axis at the next guess, 1.5, 1.41667, 1.4142157, with the error column shrinking from 10⁻¹ to 10⁻³ to 10⁻⁶ to 10⁻¹². For arctan x from 1.5, each tangent lands further away and the readout reports divergence.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. A sends î to (2, 0) and ĵ to (0, 3). What is A?

  • [[2, 0], [0, 3]]
  • [[2, 3], [0, 0]]
  • [[0, 2], [3, 0]]

Check it in “Rotation, shear, stretch and projection”

2. P projects onto a line. What is P³?

  • 0
  • P
  • I

Check it in “Rotation, shear, stretch and projection”

3. At θ₂ = 180° (folded back), the rank of J is…

  • 2
  • 1
  • 0

Check it in “Module check: the Jacobian as a linear map”

4. Why do controllers avoid poses where det J is small but not zero?

  • The arm becomes heavier
  • J⁻¹ has huge entries, so small hand moves need huge joint speeds
  • The forward kinematics stops working

Check it in “Module check: the Jacobian as a linear map”

5. Hanging pendulum, linearised: J = [[0, 1], [−9, −0.6]]. Classify.

  • Stable spiral
  • Saddle
  • Unstable node

Check it in “Linearising nonlinear models”

6. For which angle is sin θ ≈ θ least trustworthy?

  • 5°
  • 10°
  • 45°

Check it in “Linearising nonlinear models”

7. Newton's method on f(x) = x² − 4 starts at x₀ = 0. What happens?

  • It converges to 2
  • It converges to −2
  • It fails: f′(0) = 0, so the update divides by zero
  • It converges slowly

Check it in “Newton's method: ride the tangent”

8. Which statement compares bisection and Newton fairly?

  • Newton is always better
  • Bisection is guaranteed given a sign change but slow; Newton is much faster near a root but can fail from a poor start
  • Bisection needs the derivative
  • They converge at the same rate

Check it in “Newton's method: ride the tangent”

Engineering applications

Robot arm control

The Jacobian maps small joint movements to small tip movements. Controllers invert it to steer the tip, and avoid poses where its determinant is near zero because joint speeds would blow up.

Circuit operating points

Simulators find the operating point of circuits with diodes and transistors by Newton's method: linearise each device, solve the linear network, repeat until the voltages stop changing.

Summary

Glossary

Derivative (rate of change)
The derivative of a quantity is its instantaneous rate of change: the gradient of its graph at a point.
2D rotation matrix
A 2D rotation by angle θ anticlockwise maps (x, y) to (x cos θ − y sin θ, x sin θ + y cos θ), written as a 2×2 matrix.
Forward kinematics (two-link arm)
Forward kinematics computes where the end-effector is from the joint angles and link lengths.
Inverse kinematics
Inverse kinematics finds joint angles that place the end-effector at a desired position. There may be several solutions, one, or none.

Project: A Newton solver with guard rails

Write a Newton solver for one nonlinear engineering equation (a diode in series with a resistor works well). Add a fall-back to bisection when the step leaves a safe bracket. Show the convergence table and one start where plain Newton fails.

Deliverables

  • The equation, its derivative and the bracket
  • A table of iterates for a good start and a bad start
  • A note on when the fall-back triggers

References

4. Differential equations and stability

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

A second-order equation for a mass on a spring becomes two first-order equations, x′ = A·x, once you choose position and velocity as the state. Then a single matrix answers the big question: will the system settle? Its eigenvalues are the poles. Negative real parts mean decay, imaginary parts mean oscillation, and the slowest pole sets how long you wait. Power iteration shows how the dominant eigenvalue can be found by repetition alone.

Figure 4.1. Poles in the complex plane (described in words)

The complex plane with the stable left half shaded. The overdamped matrix [[0, 1], [−4, −5]] has real poles at −1 and −4. The underdamped matrix [[0, 1], [−10, −2]] has poles at −1 + 3i and −1 − 3i: it oscillates while its envelope decays like e^(−t).

Explanation

4.1 From one second-order equation to two first-order ones

Computers can only take small steps forward. How do you step forward an equation that talks about acceleration?

Any order, first-order steps

An nth-order equation needs n initial conditions, so it has n states. Define x₁ = y, x₂ = ẏ, …, xₙ = y⁽ⁿ⁻¹⁾. Each state's derivative is the next state, except the last, which comes from the original equation.

The A and B matrices

For linear systems the right-hand sides are weighted sums, so they fit in matrices: dx/dt = A·x + B·u. A says how the states push on each other; B says how the input pushes on each state. The same code steps any system once you supply A and B.

Eigenvalues preview

Each eigenvalue λ of A gives a mode that behaves like e^(λt). Negative real part: decays. Positive: grows. Imaginary part: oscillates. You will use this in week 15; for now, notice that the phase-plane readout's eigenvalues change exactly when the picture changes shape.

Derivation: Mass–spring–damper in state-space form
  1. Start from Newton's second law for a mass on a spring with a damper: m·ẍ = F − c·ẋ − k·x.

  2. Choose states x₁ = x (position) and x₂ = ẋ (velocity). Then ẋ₁ = x₂ by definition.

  3. Divide Newton's law by m: ẋ₂ = ẍ = −(k/m)·x₁ − (c/m)·x₂ + F/m.

  4. Stack them: d/dt [x₁; x₂] = [[0, 1], [−k/m, −c/m]]·[x₁; x₂] + [0; 1/m]·F. That is dx/dt = A·x + B·u with u = F.

  5. The eigenvalues of A solve λ² + (c/m)·λ + k/m = 0, the same characteristic equation as the original ODE: λ = −ζωn ± ωn√(ζ² − 1).

Common mix-ups

4.2 Stable means bounded

A pencil balanced on its tip and a pencil lying flat both sit still. Only one of them is stable. What test tells them apart?

BIBO stability

A system is BIBO stable if every bounded input produces a bounded output. For linear systems this is the same as every natural mode decaying. A response that grows without limit after a small push, however slowly, is unstable.

Poles tell you

Each pole p of a linear system contributes e^(pt) to the response. Write p = σ + jω. If σ < 0 the mode decays, if σ > 0 it grows, and ω ≠ 0 makes it oscillate. So the test is simple: every pole in the left half-plane means stable.

Marginal cases

A pole exactly on the imaginary axis (σ = 0) neither grows nor decays: an undamped spring oscillates forever; a pure integrator holds its value. These are marginally stable: a bounded input at the right frequency can still make the output grow, so engineers treat them as not good enough.

Common mix-ups

4.3 Eigenvalues: stability from the A matrix

You have the A matrix of a robot joint but no time to simulate it. Can two numbers tell you whether it will settle?

Eigenvalues of a 2×2

For A = [[a, b], [c, d]] the eigenvalues solve λ² − (trace)·λ + det = 0, with trace = a + d and det = ad − bc. So λ = trace/2 ± √(trace²/4 − det). Complex when det > trace²/4.

Reading the result

Real part negative: that mode decays like e^(Re λ·t). Positive: grows. Imaginary part ω: oscillation at ω rad/s. For a 2×2 system, both real parts are negative exactly when trace < 0 and det > 0: a two-second stability check.

Linking back to ζ and ωn

For a mass–spring–damper, det = k/m = ωn² and trace = −c/m = −2ζωn. So the eigenvalues are −ζωn ± ωn√(ζ² − 1): the same poles as before. State-space and second-order thinking are one idea seen two ways.

Common mix-ups

4.4 Power iteration: eigenvalues by repetition

Multiply a random vector by a matrix again and again. Why does it always end up pointing the same way?

The algorithm

Start with x₀ (not perpendicular to the dominant eigenvector). Repeat: y = A·xₖ, xₖ₊₁ = y/‖y‖. Estimate λ with the Rayleigh quotient r = xᵀAx / xᵀx. Normalising stops the numbers overflowing or underflowing; it does not change the direction.

Why it works and how fast

Write x₀ = c₁v₁ + c₂v₂ with |λ₁| > |λ₂|. Then Aᵏx₀ = λ₁ᵏ(c₁v₁ + c₂(λ₂/λ₁)ᵏv₂). The v₂ part dies like |λ₂/λ₁|ᵏ. For symmetric A, the Rayleigh quotient error dies even faster, like |λ₂/λ₁|²ᵏ.

Variations

If |λ₁| = |λ₂| (for example eigenvalues 2 and −2, or a complex pair), the direction never settles. Inverse iteration (apply A⁻¹, by solving with LU) finds the smallest eigenvalue; shifted inverse iteration with (A − σI)⁻¹ finds the one nearest σ. Production libraries use the QR algorithm, which is a sophisticated relative.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

From one second-order equation to two first-order ones: example 1

Write L·di/dt + R·i + q/C = V(t) with q the capacitor charge (i = dq/dt) in state-space form.

Stable means bounded: example 1

Poles at −2, −0.5 ± 4j. Stable? Which mode lasts longest?

Eigenvalues: stability from the A matrix: example 1

m = 1, c = 2, k = 5. Find the eigenvalues, ζ and ωn.

Power iteration: eigenvalues by repetition: example 1

One step of power iteration on A = [[2, 1], [1, 2]] from x₀ = (1, 0). Find the new estimate.

Interactive figures, in words

Figure 4.2 from “From one second-order equation to two first-order ones”

Set c = 0 and k = 4 and check the eigenvalues read 0 ± 2j. Now raise c slowly. Find the value of c where the eigenvalues stop having an imaginary part, and check it against c = 2√(km).

With damping c = 0 and stiffness 4, the phase-plane path is a closed ellipse and the eigenvalues are 0 ± 2j. As c increases the path becomes an inward spiral and the eigenvalues get a negative real part. At c = 4 (twice the square root of k times m) the imaginary part vanishes and the path slides into the origin without circling.

Figure 4.3 from “Stable means bounded”

Move σ from −3 to +1 with ω = 3. Note the σ where the response stops dying away. Then set ω = 0 and repeat. Describe in one sentence what σ controls and what ω controls.

The pole locator shows an s-plane with the right half shaded as unstable and a plot of e^(σt)·cos(ωt). With σ negative the oscillation dies away; at σ = 0 it keeps a constant size; with σ positive it grows. Raising ω makes the oscillation faster without changing whether it grows.

Figure 4.4 from “Power iteration: eigenvalues by repetition”

Step through [[2, 1], [1, 2]] and then the 'close eigenvalues' matrix. Count how many steps each needs before the estimate stops changing in the third digit, and compare with |λ₂/λ₁| in the readout.

The power-iteration animator steps a unit vector through repeated multiplication by A, plotting previous iterates as dots and the dominant eigen-line as a band. A table lists the estimate at each step; a step button works without animation, and Play is disabled under reduced motion.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. In A = [[0, 1], [−k/m, −c/m]], what does the entry −c/m in the bottom-right mean?

  • How position affects velocity's rate
  • How velocity affects its own rate of change: damping
  • The input gain
  • The spring stiffness

Check it in “From one second-order equation to two first-order ones”

2. How many states does d³y/dt³ + 2ÿ + 3ẏ + y = u need?

  • 1
  • 2
  • 3
  • 4

Check it in “From one second-order equation to two first-order ones”

3. Which set of poles gives a stable system?

  • −1, +0.5
  • −2 ± 3j
  • 0 ± 2j
  • +1 ± j

Check it in “Stable means bounded”

4. Poles at −10 and −0.2. Which dominates the long-term response?

  • −10, because it is bigger
  • −0.2, because it decays more slowly
  • Both equally
  • Neither

Check it in “Stable means bounded”

5. A has trace −3 and determinant 2. Stable?

  • Yes
  • No
  • Marginal
  • Can't tell

Check it in “Eigenvalues: stability from the A matrix”

6. A = [[0, 1], [−10, −2]]. What is the size of the imaginary part of its eigenvalues (rad/s)?

Answer: rad/s

Check it in “Eigenvalues: stability from the A matrix”

7. With |λ₂/λ₁| = 0.5, about how many steps reduce the unwanted component by a factor of 10⁶? (Nearest whole step.)

Answer:

Check it in “Power iteration: eigenvalues by repetition”

8. To find the smallest-magnitude eigenvalue, you…

  • Run power iteration on A for longer
  • Run power iteration on A⁻¹ (solving with LU each step)
  • Use the trace

Check it in “Power iteration: eigenvalues by repetition”

Engineering applications

Suspension and mounts

A machine mount is designed by placing its poles: far enough left to settle quickly, with imaginary parts small enough that the ringing dies before the next disturbance.

Large structural models

Finite-element models of bridges have thousands of states. Engineers never factor the whole characteristic polynomial; iterative methods related to power iteration find the few modes that matter.

Summary

Glossary

Damping ratio
The damping ratio ζ describes how quickly oscillations die out in a second-order system: below 1 it oscillates, exactly 1 is critically damped, above 1 it creeps to the target without overshoot.
First-order system and time constant
A first-order system responds to a step by approaching its new value exponentially; its time constant τ is the time to cover 63.2 % of the change.
Overshoot
Overshoot is how far a response goes past its final value, usually given as a percentage of the step size.
Settling time and rise time
Settling time is how long a response takes to enter and stay within a band, often 2 %, of its final value. Rise time is how long it takes to go from 10 % to 90 % of the step.

Project: Place the poles of a mount

A 2 kg instrument sits on a spring mount. Choose stiffness and damping so that it settles within 0.5 s and overshoots by no more than 10 %. Show the A matrix, the eigenvalues and a simulated step response.

Deliverables

  • The state-space model with units
  • Eigenvalues and the stability argument
  • A step response plot checked against the specification

References

5. Fourier and transform thinking

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

Sometimes the best way to answer a question about a signal is to ask a different question: not 'what is its value now?' but 'how much of each frequency does it contain?'. This chapter builds signals from sinusoids, rebuilds a square wave from its odd harmonics, measures frequency content with the discrete Fourier transform, and sees filtering in time as multiplication in frequency.

Figure 5.1. A square wave from three sinusoids (described in words)

A square wave of height ±1 over one period, with the sum of its first three odd harmonics drawn over it. A bar chart shows the harmonic amplitudes 4/(nπ): 1.273 for n = 1, 0.424 for n = 3 and 0.255 for n = 5. Even harmonics are zero.

Explanation

5.1 Seeing a signal's ingredients

A chord played on a piano is one wobbly line on an oscilloscope. How can a tuner app name every note in it?

Two views of one signal

The time domain shows value against time. The frequency domain shows how much of each frequency is present. A magnitude spectrum draws a bar of height Aᵢ at each fᵢ. The same information, arranged differently, like a recipe versus the cake.

Phase hides in the time view

Shifting a component's phase reshapes the waveform (peaks can line up or cancel) but leaves its bar the same. That is why two signals that look different can sound identical: your ear cares mostly about magnitudes. A full description keeps the phase too, so the time signal can be rebuilt.

Power adds across frequencies

Sinusoids of different frequencies average to zero when multiplied together, so the cross terms vanish and P = Σ Aᵢ²/2. That is Parseval's theorem in miniature: power computed in time equals power computed from the spectrum. Components at the same frequency are different: they combine as phasors first.

Common mix-ups

5.2 A square wave made of curves

A square wave has perfectly sharp corners. Sine waves have none. Yet enough sine waves add up to a square. How many, and what's left over?

The series

A square wave swinging between +A and −A is x(t) = (4A/π)·[sin ωt + sin 3ωt/3 + sin 5ωt/5 + …]. Harmonic n has amplitude bₙ = 4A/(nπ) for odd n and 0 for even n. The fundamental is 4/π ≈ 1.27 times taller than the square itself.

Power is concentrated low

The square has power A². The fundamental alone carries (4A/π)²/2 = 8A²/π² ≈ 81 % of it; adding the 3rd and 5th reaches about 93 %. So a square wave through a low-pass filter quickly looks like a sine: that is how some cheap sine-wave inverters work.

Gibbs: the overshoot that won't go away

Near each jump the partial sum overshoots by about 9 % of the jump, however many terms you add. More terms make the overshoot narrower, not lower. In practice, ringing near edges in a band-limited system is the same effect: a sharp edge truly needs infinitely high frequencies.

Common mix-ups

5.3 The DFT: asking 'how much of this wave?'

A computer only has eight numbers from a sensor. How can it say there is a strong 250 Hz component in them?

Correlation with probes

X[k] = Σ x[n]·cos(2πkn/N) − j·Σ x[n]·sin(2πkn/N). Each bin multiplies the signal by a probe wave with k cycles in the window and adds up. If the signal contains that wave, products are mostly positive and the sum is big; otherwise positives and negatives cancel. The cosine and sine sums together catch the component whatever its phase.

Bins and frequencies

With N samples at rate fs, bin k corresponds to f = k·fs/N. Resolution is fs/N: to tell close frequencies apart, record for longer. For a real signal, bins above N/2 mirror those below (they are the negative frequencies). A pure cosine of amplitude A exactly on bin k gives |X[k]| = A·N/2.

Small enough to do by hand

For N = 4 the probes take only the values 1, 0 and −1, so X[0] = x0 + x1 + x2 + x3, X[2] = x0 − x1 + x2 − x3, and X[1] = (x0 − x2) − j(x1 − x3). For x = [1, 0, −1, 0], X[1] = 2: one cycle of a cosine, amplitude 1, times N/2 = 2.

Common mix-ups

5.4 The moving average, seen in frequency

Averaging the last four readings smooths a sensor beautifully. So why does it completely erase one particular frequency?

One line of code

y[n] = (x[n] + x[n−1] + … + x[n−M+1])/M. It is a finite impulse response (FIR) filter: an impulse affects exactly M outputs, then is forgotten. Random noise of standard deviation σ comes out with σ/√M, because independent errors partly cancel.

Nulls and side lobes

Its gain is 1 at DC and falls to exactly zero at fs/M, 2fs/M, …, with bumps (side lobes) in between: the first is about 0.22 for large M. Great for removing a known interference, like 50 Hz mains when fs/M = 50 Hz, but a mediocre general low-pass because the side lobes leak.

The price: lag

The output is centred (M − 1)/2 samples in the past. With M = 9 at 100 Hz that is 40 ms: fine for a thermometer, dangerous inside a fast control loop where delay erodes stability. Doubling M halves the noise power again but doubles the lag.

Derivation: The moving-average frequency response
  1. Input x[n] = e^{jωn} with ω = 2πf/fs. Output y[n] = (1/M)·Σ_{k=0}^{M−1} e^{jω(n−k)} = e^{jωn}·H, with H = (1/M)·Σ e^{−jωk}.

  2. That is a geometric series: H = (1/M)·(1 − e^{−jωM})/(1 − e^{−jω}).

  3. Factor out half-angles: (1 − e^{−jθ}) = e^{−jθ/2}·2j·sin(θ/2).

  4. So |H| = |sin(ωM/2) / (M·sin(ω/2))| = |sin(πMf/fs)/(M·sin(πf/fs))|, with a pure delay of (M − 1)/2 samples.

  5. It is 1 at f = 0 and 0 whenever Mf/fs is a whole number (other than multiples of M): nulls at f = fs/M, 2fs/M, …

Common mix-ups

5.5 Transforms: why engineers change the question

Filtering is a messy running sum in time but a simple multiplication in frequency. What other hard problems become easy when you transform them?

Filtering = multiplying spectra

In time, a filter output is a weighted running sum of the input (a convolution). In frequency, the same operation is just Y(f) = H(f)·X(f): each component is scaled by the gain at its frequency and shifted by the phase. That is why a frequency response is the most useful single description of a filter.

Low-pass, high-pass, and the rest

Low-pass keeps slow changes (smoothing, anti-aliasing). High-pass keeps fast changes and removes offsets and drift (AC coupling, removing gyro bias). A band-pass keeps a range (radio tuning), and a notch removes one frequency (mains hum). High-pass can be built as 1 − low-pass.

The Laplace transform, conceptually

The Fourier transform describes a signal with steady sinusoids. The Laplace transform uses e^{st} with complex s = σ + jω: sinusoids that can also grow or decay. Differentiation becomes multiplication by s, so a circuit's differential equation becomes algebra, e.g. an RC low-pass has H(s) = 1/(1 + sRC). Where H(s) blows up (its poles) tells you whether a system is stable.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Seeing a signal's ingredients: example 1

Sketch the spectrum of 3 + 2·cos(2π·10t) + sin(2π·30t).

A square wave made of curves: example 1

A ±5 V, 1 kHz square wave drives a speaker. What is the amplitude of the 3 kHz component?

The DFT: asking 'how much of this wave?': example 1

Compute all four DFT bins of x = [2, 1, 0, 1].

The moving average, seen in frequency: example 1

A 5-point moving average filters x = [2, 4, 6, 8, 10, 12]. Find y[4] and y[5].

Transforms: why engineers change the question: example 1

A sensor reading is 2.5 V of steady offset plus a 5 Hz vibration plus 200 Hz noise, sampled at 1 kHz. Which filter keeps just the vibration?

Interactive figures, in words

Figure 5.2 from “Seeing a signal's ingredients”

Load 'Three tones'. Read the spectrum bars, then change each phase and watch the time plot. Next put two components at the same frequency and vary one phase: what happens to that bar now?

With three tones at 2, 5 and 8 Hz the spectrum shows three bars of heights 1, 0.6 and 0.3. Changing phases changes the waveform's shape but not the bars. Putting two components at the same frequency makes one bar whose height depends on their phase difference (from the sum to the difference of the amplitudes).

Figure 5.3 from “A square wave made of curves”

Start with 1 harmonic, then add them one by one up to 25. Watch the power captured and the peak of the sum. Does the overshoot near the jump get smaller, or only narrower?

With 1 harmonic the builder draws a sine of peak 1.27 over the square. Adding odd harmonics (3, 5, 7…) fills in the corners; captured power rises from 81 % to about 98 % with 13 terms; the peak near each jump stays about 1.18, a 9 % overshoot of the jump of 2.

Figure 5.4 from “The DFT: asking 'how much of this wave?'”

Pick 'cos 2 + ½·sin 3'. Step the probe k from 0 to 7, watching the products column. Which k give big sums, and why do the cosine part and the sine part show up in different columns?

For the signal cos(2·2πn/8) + ½·sin(3·2πn/8), the probe shows |X[k]| = 4 at k = 2 and 6 (cosine part, through the Σx·cos column) and 2 at k = 3 and 5 (sine part, through the Σx·sin column); every other bin is zero.

Figure 5.5 from “The moving average, seen in frequency”

Choose 'Moving average', low-pass. Set M = 4 and slide the test frequency to find the null. Change M to 8 and 2: where do the nulls go? Watch the step response: how many samples does it take to reach the top?

In the explorer, the 4-point moving average has gain 1 at 0, falls to about 0.77 at f/fs = 0.1, and reaches 0 at f/fs = 0.25 (a null), with a small bump after it. With M = 8 the first null moves to 0.125. The step response climbs in M equal steps to 1.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. x(t) = 2·sin(2π·50t) + 1·sin(2π·150t). What is its average power?

Answer:

Check it in “Seeing a signal's ingredients”

2. Where does a constant offset appear in a spectrum?

  • At the highest frequency
  • Nowhere
  • At 0 Hz
  • Spread evenly over all frequencies

Check it in “Seeing a signal's ingredients”

3. What is the amplitude of the fundamental of a ±1 square wave (3 decimal places)?

Answer:

Check it in “A square wave made of curves”

4. You add more and more harmonics. What happens to the overshoot near each jump?

  • It shrinks to zero
  • It stays about 9 % of the jump but gets narrower
  • It grows without limit
  • It moves to the middle of the flat parts

Check it in “A square wave made of curves”

5. A 1024-point DFT is taken of a signal sampled at 8 kHz. What frequency, in Hz, does bin k = 64 represent?

Answer: Hz

Check it in “The DFT: asking 'how much of this wave?'”

6. You need to tell 100 Hz and 102 Hz apart. What helps most?

  • A higher sample rate with the same N
  • A longer recording (larger N at the same fs)
  • Fewer bits
  • Taking the DFT twice

Check it in “The DFT: asking 'how much of this wave?'”

7. A moving average with M = 10 runs at fs = 500 Hz. What is the lowest frequency it removes completely, in Hz?

Answer: Hz

Check it in “The moving average, seen in frequency”

8. Filtering in time corresponds to what in frequency?

  • Adding the filter's response
  • Multiplying the spectrum by the filter's response
  • Dividing by the sample rate
  • Nothing simple

Check it in “Transforms: why engineers change the question”

Engineering applications

Machine condition monitoring

A failing bearing adds energy at frequencies set by its geometry and shaft speed. A spectrum of a vibration sensor shows the fault long before it can be heard.

Choosing a filter

Knowing that a motor's switching noise sits at 20 kHz while the signal stays below 100 Hz tells you what filter to design. In frequency, the job becomes obvious.

Summary

Glossary

Frequency and period
Frequency is how many cycles happen per second; the period is the time for one cycle. Each is the reciprocal of the other.
Sampling and aliasing
Sampling measures a signal at regular intervals. Any frequency above half the sample rate, the Nyquist frequency, is indistinguishable from a lower 'alias' frequency.
Low-pass filter (moving average and EMA)
A low-pass filter lets slow changes through and attenuates fast ones. In firmware the simplest are the moving average and the exponential moving average.
Logarithms and decibels
A logarithm answers 'what power gives this number?'. Decibels use logarithms to express ratios: 10 log10 for power ratios and 20 log10 for amplitude ratios.

Project: What is in that hum?

Generate or record a signal that mixes a 50 Hz hum, its third harmonic and noise. Compute its DFT, identify each component and its amplitude, then design a moving-average or first-order filter and show its effect on the spectrum.

Deliverables

  • The signal definition and sample rate
  • A labelled spectrum before and after filtering
  • A justification of the filter choice in frequency terms

References

6. Numerical methods and their errors

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

A computer only ever approximates an integral or a differential equation, so the engineer's job is to know how good the approximation is. This chapter measures error properly: the trapezoid rule's predictable error, local and global error and the observed order of a method, stability limits that make explicit methods explode on stiff problems, and convergence studies that turn 'it looks fine' into evidence.

Figure 6.1. Error against step size (described in words)

A log-log plot of the global error at t = 1 for y′ = −y against step sizes 0.5, 0.25, 0.125 and 0.0625. Euler's error falls by about half each time, an observed order of 1.04; RK4's error falls about sixteen-fold, an observed order of 4.08.

Explanation

6.1 The trapezoid rule and its error

Replace rectangles with sloped tops and the error drops by a factor of four every time you halve the step. Why four, and when does it overshoot?

The rule

Join neighbouring samples with straight lines and add the trapezoids: T = h·(y₀/2 + y₁ + y₂ + … + yₙ₋₁ + yₙ/2). End samples count half, inner samples fully. It is the average of the left and right sums.

Error and concavity

Error ≈ (b − a)·h²·f″/12. For a curve that bends upwards (f″ > 0, convex) the straight tops lie above it: the trapezoid overestimates. For a curve bending down it underestimates. For a straight line it is exact.

Choosing a sample rate

If you know roughly how sharply a signal bends (f″), the formula tells you the step needed for a target accuracy before you log anything. If you do not, integrate with h and with h/2: the difference is about three-quarters of the error of the coarser estimate, a check you can run on any data.

Derivation: Where the h² error comes from
  1. Take one strip of f(x) = x² on [0, h] (any smooth curve looks like a parabola up close).

  2. Trapezoid: h × (f(0) + f(h))/2 = h × (0 + h²)/2 = h³/2.

  3. Exact: ∫₀ʰ x² dx = h³/3. Error per strip: h³/2 − h³/3 = h³/6.

  4. For a general curve the per-strip error is about (h³/12)·f″; here f″ = 2, giving h³/6 as found.

  5. An interval of length L has n = L/h strips, so the total error ≈ (L/h)·(h³/12)·f″ = L·h²·f″/12.

  6. Halve h: the error falls to a quarter. Check: v = 0.5t² + 1 (f″ = 1) on [0, 4] with h = 1 gives 4 × 1 × 1/12 = 0.333 m; the trapezoid sum is 15 m against 14.667 m exact.

Common mix-ups

6.2 Local and global error, and the convergence study

Halve the step and RK4's error drops about sixteen times. How can you prove that from your own code, not from a textbook?

Question → method → evidence

Question: is my integrator correct, and is my step size small enough? Method: solve a problem with a known answer at h, h/2, h/4 (and smaller), measure the error at a fixed time, compute ratios. Evidence: ratios close to 2ᵖ confirm the order; a final error below your tolerance justifies the step.

When there is no exact answer

Use the finest run as a reference, or use differences between successive runs: E(h) ≈ |y_h − y_{h/2}|·2ᵖ/(2ᵖ − 1). Richardson extrapolation combines two runs, (2ᵖ y_{h/2} − y_h)/(2ᵖ − 1), to cancel the leading error term.

Limits of the study

Very small h eventually hits round-off error, which grows as steps multiply, so the error curve flattens or turns up. Very large h may be outside the asymptotic range or even unstable. Report the range of h where the ratio is steady, and plot error against h on log–log axes: the slope is the order.

Derivation: Evidence for RK4's fourth order
  1. Local error: if a method matches the exact Taylor series through the hᵖ term, one step from exact data is off by about C hᵖ⁺¹.

  2. Global error: reaching a fixed time T takes N = T/h steps. Roughly adding the local errors gives N·C hᵖ⁺¹ = C T hᵖ, so global order is p.

  3. Euler matches up to h¹ (p = 1). RK4 matches up to h⁴ (p = 4): its local error is O(h⁵), global O(h⁴).

  4. Test: with E(h) ≈ C hᵖ, E(h)/E(h/2) ≈ 2ᵖ, so p ≈ log₂(E(h)/E(h/2)).

  5. Evidence from this term's code (x″ = −x, x(0) = 1, error in x at t = 10): RK4 with 100, 200, 400 steps gives errors about 3.9×10⁻⁶, 2.6×10⁻⁷, 1.7×10⁻⁸. Ratios 14.9 and 15.5 give p ≈ 3.9 and 3.95, approaching 4.

  6. Explicit Euler on the same test gives 0.57, 0.24, 0.11: ratios 2.3 and 2.2, approaching 2¹ = 2 as h shrinks. The pre-asymptotic ratios are a reminder to test at small enough h.

Common mix-ups

6.3 Stability regions and stiffness

The fast part of your model died out in a millisecond, yet your simulation still crawls along in microsecond steps. Why?

Stability regions

For a system x′ = Ax, each eigenvalue λ of A gives a test equation. An explicit method is stable only if hλ lies inside its stability region for every eigenvalue. So the fastest-decaying mode (largest |λ|) sets the maximum step, even if that mode is physically irrelevant after a moment.

What stiffness means

A problem is stiff when it has decaying modes on very different time scales, and you want to follow the slow one. Example: eigenvalues −1 and −1000. Accuracy for the slow mode would allow h ≈ 0.1, but explicit Euler stability needs h ≤ 0.002: fifty times more steps, purely to avoid blowing up.

The remedy

Implicit methods (backward Euler, the trapezoidal rule, BDF methods) solve an equation each step, often a linear system with (I − hA) via LU from week 2, but stay stable with large steps. Library solvers flagged for stiff problems (such as 'BDF' or 'Radau' options) do this automatically.

Derivation: Amplification factors and stability limits
  1. Test equation: y′ = λy, exact yₙ₊₁ = e^{hλ}yₙ. Let z = hλ.

  2. Explicit Euler: yₙ₊₁ = yₙ + hλyₙ = (1 + z)yₙ, so R(z) = 1 + z.

  3. Stable (no growth) iff |1 + z| ≤ 1. For real λ < 0: −2 ≤ z ≤ 0, so h ≤ 2/|λ|.

  4. RK4 on the test equation gives R(z) = 1 + z + z²/2 + z³/6 + z⁴/24 (the Taylor series of e^z to z⁴). On the negative real axis |R| ≤ 1 for z ≥ about −2.79.

  5. Implicit (backward) Euler: yₙ₊₁ = yₙ + hλyₙ₊₁, so R(z) = 1/(1 − z), with |R| < 1 for every z < 0: stable for any step on decaying problems.

Common mix-ups

6.4 Convergence and sensitivity studies

Your simulated frequency is 1.0007 rad/s. Is the 7 from the physics, the step size or a parameter you guessed?

Convergence first

Run the simulation at several steps and compute the metric each time. Check that the differences shrink by about 2ᵖ per halving. Choose a step where the numerical error is at least ten times smaller than any effect you want to report. Record that choice and the evidence in the report.

Then sensitivity

Change one parameter at a time by a stated amount (for example ±10%) and record the change in each output: a one-at-a-time study. Report relative sensitivities (percentage change in output per percentage change in input). Compare with analytic derivatives where you have them, as in the derivation above.

Separating error sources

A result has numerical error (step size, round-off), parameter uncertainty (k_c known to ±10%) and model error (are springs really linear?). Convergence studies bound the first, sensitivity studies the second; only experiments address the third. Say clearly which you have quantified.

Derivation: Sensitivity of the frequencies to the coupling spring
  1. Equal masses m, outer springs k, coupling k_c: ω₁ = √(k/m), ω₂ = √((k + 2k_c)/m).

  2. ∂ω₁/∂k_c = 0: the in-phase mode never stretches the coupling spring.

  3. ∂ω₂/∂k_c = (1/2)(k + 2k_c)^{−1/2} · 2/√m = 1/(m ω₂).

  4. Relative sensitivity: (k_c/ω₂)(∂ω₂/∂k_c) = k_c/(m ω₂²) = k_c/(k + 2k_c), which is small when k_c ≪ k.

  5. Beat period T_b = 2π/(ω₂ − ω₁). For small k_c, ω₂ − ω₁ ≈ k_c/(m ω₁), so T_b ≈ 2π m ω₁ / k_c: a 10% change in k_c gives about a 10% change in T_b.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

The trapezoid rule and its error: example 1

Trapezoid rule for v = 0.5t² + 1 on [0, 4] with h = 1.

Local and global error, and the convergence study: example 1

Errors at t = 5 are 2.0×10⁻³ (h = 0.1) and 2.6×10⁻⁴ (h = 0.05). What is the observed order?

Stability regions and stiffness: example 1

x′ = Ax with eigenvalues −2 and −500. Largest stable explicit Euler step?

Convergence and sensitivity studies: example 1

m = 1 kg, k = 1 N/m, k_c = 0.1 N/m. Compute ω₁, ω₂ and T_b, then T_b with k_c = 0.11.

Interactive figures, in words

Figure 6.2 from “The trapezoid rule and its error”

Choose the drone climb rate and the trapezoid rule. Step n through 1, 2, 4, 8, 16 and watch the error ratio in the readout settle near 4. Is the trapezoid estimate above or below the exact value? Look at the curve's shape to explain it.

With the trapezoid rule on the drone climb rate, the estimate is 15 m at n = 4 against an exact 14.667 m, and each doubling of n divides the error by about 4. The estimate is always slightly high because the curve bends upwards.

Figure 6.3 from “Local and global error, and the convergence study”

Read the convergence table below the energy plot. For each method, divide the h error by the h/2 error and the h/2 error by the h/4 error. Change h and see which ratios settle near 2 and which near 16.

Below the energy plot, a table lists for each method the error in x at t = 10 for steps h, h/2 and h/4, and the observed order computed from the last two. Changing h updates the table.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. Predict the trapezoid error for the same integral with h = 0.5 s, in metres, using (b − a)h²f″/12 (f″ = 1).

Answer: m

Check it in “The trapezoid rule and its error”

2. The trapezoid rule is applied to a curve that bends upwards (convex). The estimate is…

  • too high
  • too low
  • exact

Check it in “The trapezoid rule and its error”

3. E(h) = 0.032 and E(h/2) = 0.0021. What is the observed order p = log₂(E(h)/E(h/2))? (2 d.p.)

Answer:

Check it in “Local and global error, and the convergence study”

4. A method's local error is O(h³). Its global error is…

  • O(h³)
  • O(h²)
  • O(h⁴)

Check it in “Local and global error, and the convergence study”

5. Your 'RK4' shows observed order 1.0 on a smooth test. Most likely?

  • RK4 is first order
  • A bug in the stages, e.g. a wrong time or state in k₂–k₄
  • The step is too small

Check it in “Local and global error, and the convergence study”

6. Euler on y′ = −50y with h = 0.05. What is R = 1 + hλ?

Answer:

Check it in “Stability regions and stiffness”

7. Why can backward Euler take large steps on y′ = −1000y?

  • It is fourth order
  • R(z) = 1/(1 − z) has |R| < 1 for all z < 0
  • It skips the fast mode

Check it in “Stability regions and stiffness”

8. Which should you do first?

  • Sensitivity study, then convergence
  • Convergence study, then sensitivity
  • Either: they measure the same thing

Check it in “Convergence and sensitivity studies”

Engineering applications

Trusting a simulator

Before a simulation result goes in a report, run it again at half the step. If the answer changes by more than the tolerance you care about, the first run was not converged.

Stiff circuits and chemistry

A circuit with a fast parasitic capacitor and a slow thermal mode forces an explicit method to tiny steps. Implicit methods take steps sized for the slow behaviour you actually want.

Summary

Glossary

Integral as accumulated area
An integral adds up a rate over time: the area under a rate graph gives the total accumulated amount.
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/τ).
Floating-point rounding and comparison
Most decimal fractions cannot be stored exactly in binary floating point, so tiny rounding errors appear and == between floats is unreliable.
Significant figures and rounding
Significant figures are the digits in a number that carry meaningful information, from the first non-zero digit to the last digit you are sure of. Round results so they do not claim more precision than the inputs.

Project: A convergence study you could defend

Pick one School model (cooling, a falling object with drag or a mass on a spring). Simulate it with two methods at a sequence of step sizes, compute observed orders and choose the largest step that meets a stated tolerance.

Deliverables

  • The model and the quantity of interest
  • An error table and log-log plot for both methods
  • The chosen step with its justification

References

7. Statistics for engineering evidence

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

A single number from a test is not evidence until you know how much it would wobble if you ran the test again. This chapter describes distributions honestly (including the one strange run), turns spread into a standard error and a confidence interval, propagates uncertainty by simulation when formulas get awkward, and compares two designs by the difference between them rather than by two separate averages.

Figure 7.1. Intervals shrink with the square root of n (described in words)

Three approximate 95 % intervals, mean ± 1.96·s/√n with s = 1. For n = 4 the half-width is 0.98, for n = 16 it is 0.49 and for n = 64 it is 0.245. Each fourfold increase in runs halves the width of the interval.

Explanation

7.1 Distributions, spread and the one weird run

Nineteen runs take about 48 ms. One takes 110 ms. Is your code slow, or is your summary lying to you?

Centre: mean or median?

The mean uses every value, so it is efficient for well-behaved data and sensitive to extremes. The median is the middle of the sorted list: robust to a few wild values, but it throws information away. For timings, which often have a long right tail (occasional slow runs from caches, interrupts or garbage collection), report both, or report the median with the interquartile range.

Spread: variance and standard deviation

Sample variance s² = Σ(xᵢ − x̄)² / (n − 1); the standard deviation s is its square root and has the data's units. Dividing by n − 1 rather than n corrects a bias: deviations are measured from x̄, which was fitted to the same data, so they come out slightly too small. With n = 5 the correction is 25%; with n = 100 it is 1%.

Shape matters

Two data sets can share a mean and SD yet look completely different: one symmetric bell, one skewed with a long tail, one with two humps (perhaps two machines mixed together). Always plot the data (dot plot or histogram) before trusting a summary. A bimodal timing histogram usually means two different code paths, not noise.

Outliers: flag, investigate, report

A z-score z = (x − x̄)/s counts standard deviations from the mean; |z| > 3 is a common flag for roughly normal data. A flag is a question, not a verdict. Was the laptop throttling? Did a backup start? If you exclude a point, say so, give the rule you set before looking, and show the result both ways. Silently deleting inconvenient data is falsification.

Common mix-ups

7.2 What a 95% confidence interval really promises

Your interval is 47.2 to 49.0 ms. Is there a 95% chance the true mean is in there?

The recipe
  1. Compute x̄ and s from n independent measurements. 2. SE = s/√n. 3. Half-width h = z·SE. 4. Report x̄ ± h with the confidence level, n and the method. Example: 48.1 ± 0.9 ms (95% CI, n = 30, normal approximation).
The correct interpretation

If you repeated the whole experiment many times, about 95% of the intervals built this way would contain the true mean. Once your interval is computed, μ either is in it or isn't; you just don't know which. Saying 'there is a 95% probability μ lies between 47.2 and 49.0' is a common shortcut, but strictly it is a different (Bayesian) statement.

When the approximation breaks

The z-interval assumes independent data, a roughly normal sampling distribution and enough data to trust s. It under-covers for small n (use t), for strongly skewed data with small n (use more data, a transformation, or the bootstrap), and badly for correlated data such as drifting benchmarks. Systematic error is never captured: a mis-calibrated timer shifts every interval.

Width, level and effort

Higher confidence widens the interval (99% is about 31% wider than 95%). Quadrupling n halves it. Choose the level before you look at the data, and plan n from the half-width you need: n ≈ (z·σ/h)².

Derivation: Building the interval from the sampling distribution
  1. For large n, the sample mean is approximately normal: x̄ ~ N(μ, σ²/n).

  2. Standardise: Z = (x̄ − μ)/(σ/√n) ~ N(0, 1). For a standard normal, P(−1.96 ≤ Z ≤ 1.96) = 0.95.

  3. Substitute: P(−1.96 ≤ (x̄ − μ)/(σ/√n) ≤ 1.96) = 0.95.

  4. Rearrange the inequality for μ: P(x̄ − 1.96·σ/√n ≤ μ ≤ x̄ + 1.96·σ/√n) = 0.95. The random quantity is x̄, so this is a statement about the interval, not about μ.

  5. σ is unknown, so replace it with s. For small n this extra uncertainty matters: use Student's t value (for example t = 2.26 instead of 1.96 when n = 10) or the interval will be too narrow.

  6. Result (normal approximation): x̄ ± z·s/√n, with z = 1.645 (90%), 1.96 (95%) or 2.576 (99%).

Common mix-ups

7.3 Monte Carlo: propagate by simulation

Your model has six uncertain inputs and a square root, an exponential and an if-statement. Is there a formula for its uncertainty? You don't need one.

The algorithm
  1. Describe each uncertain input with a distribution (normal with its standard uncertainty is the default; uniform for a resolution limit). 2. Draw one value of every input. 3. Run the model. 4. Repeat N times. 5. Summarise the outputs: mean, SD, percentiles (the 2.5th and 97.5th give a 95% interval without assuming normality).
How big should N be?

The Monte Carlo estimate of a mean has standard error s_out/√N; estimates of an SD or of tail percentiles need more samples than estimates of a mean. A practical check: run with two different seeds. If the results differ in a digit you intend to report, increase N. For a 95% interval from percentiles, N ≥ 10,000 is a sensible start.

Correlated inputs

If two inputs share a cause (the same reference voltage, the same temperature), sample that shared cause once per trial and derive both from it. Sampling them independently would understate or overstate the output's uncertainty. This is far easier to get right in Monte Carlo than in a formula.

Reproducible randomness

Use a seeded pseudo-random generator and record the seed, the distributions, their parameters and N. Then anyone can regenerate your histogram exactly. Every simulator and practice generator on this site is seeded for exactly this reason: the server can recompute your result from the seed to check it.

Common mix-ups

7.4 Is the difference real? Effect sizes and correlation

Greenhouse readings rise with the heater power, and also with the sunshine. Which one is warming the plants?

The difference and its uncertainty

For independent conditions A and B, the difference of means d = x̄_B − x̄_A has standard error SE_d = √(SE_A² + SE_B²). A rough 95% interval is d ± 1.96·SE_d. If that interval comfortably excludes zero, the data support a real difference; if it straddles zero, you can't tell the sign yet.

Effect size: how big, not just whether

Cohen's d = (x̄_B − x̄_A)/s_pooled expresses the difference in units of run-to-run spread. d ≈ 0.2 is small, 0.8 large. With enough data even a trivially small effect becomes 'significant'; the effect size tells you whether anyone should care. Engineers usually prefer the raw difference in real units (ms, W, mm) plus its interval.

Correlation is a number, not a mechanism

Pearson's r runs from −1 to +1 and measures how well a straight line describes the relationship. r = 0.9 between heater power and temperature does not prove the heater warms the greenhouse: sunshine might raise both (the controller turns the heater down when it's sunny, which could even make r negative). Correlation also misses curved relationships entirely.

Control the confounders

A confounder affects both the thing you change and the thing you measure. Defeat it by design: change one variable at a time, randomise or interleave the order of conditions, and run both conditions under the same environment. In simulation you can hold the weather fixed exactly, which is one reason engineers simulate before field trials.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Distributions, spread and the one weird run: example 1

Runs (ms): 47, 49, 48, 50, 46. Find the mean and sample SD.

Distributions, spread and the one weird run: example 2

Add a sixth run of 70 ms. What happens to the mean, the median and the z-score of 70 measured against the first five?

What a 95% confidence interval really promises: example 1

n = 36 runs, x̄ = 52.4 ms, s = 4.8 ms. Give the 95% CI.

What a 95% confidence interval really promises: example 2

How many runs would give a half-width of 0.5 ms with the same s?

Monte Carlo: propagate by simulation: example 1

A Monte Carlo run gives SD(P) = 0.92 W with N = 1,000, and 0.89 W with a different seed. You want to report SD to two significant figures. Is N enough?

Is the difference real? Effect sizes and correlation: example 1

A: mean 40.0 ms, SE 0.6. B: mean 38.2 ms, SE 0.8. Give the difference with a 95% interval.

Interactive figures, in words

Figure 7.2 from “Distributions, spread and the one weird run”

Drag the orange run from 49 ms to 120 ms. Watch the mean line, the median line and the SD. Find the value where the run first gets flagged (|z| > 3), then compare 'Keep all' with 'Exclude and report'.

The interactive shows 19 run times clustered around 48 ms with an SD near 3 ms, plus one run you move from 40 to 120 ms. Moving it to 110 ms raises the mean by about 3 ms, raises the SD several-fold, leaves the median almost unchanged, and gives a z-score far above 3, so the run is flagged. Choosing 'Exclude and report' recomputes the summaries without it and reminds you to report the exclusion.

Figure 7.3 from “What a 95% confidence interval really promises”

Keep 95% and n = 30. Press 'Draw 20 more experiments' ten times and watch the running tally approach 95%. Then set n = 3 and reset: the tally falls short. Finally switch to 99% and watch the bars lengthen.

The simulator draws 20 experiments of n readings from a normal distribution with true mean 50 and builds a confidence interval from each, drawn as a horizontal bar. Bars that miss the true mean are marked 'miss'. Over many batches, about 95% of 95% intervals contain 50 when n is 30; with n = 3 coverage drops to roughly 80%, because z = 1.96 is too small when σ is estimated from so few points.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. Your benchmark times have a long right tail from occasional background tasks. Which centre is least affected by those rare slow runs?

  • Mean
  • Median
  • Maximum
  • Range

Check it in “Distributions, spread and the one weird run”

2. A run is flagged with z = 4.2. What is the most defensible action?

  • Delete it: it is obviously wrong
  • Investigate the cause, apply a rule fixed in advance, and report results with and without it
  • Keep it but don't mention it
  • Re-run until the outlier goes away, then report only the new runs

Check it in “Distributions, spread and the one weird run”

3. Which statement correctly interprets a 95% confidence interval?

  • 95% of the data lie inside it
  • If the experiment were repeated many times, about 95% of intervals built this way would contain the true mean
  • The true mean changes 5% of the time
  • There is a 95% chance the next measurement will fall inside it

Check it in “What a 95% confidence interval really promises”

4. With n = 4 runs, you build x̄ ± 1.96·s/√n. What is the main risk?

  • The interval is too wide
  • The interval is too narrow: with so few runs s is unreliable, and the t value (3.18) should replace 1.96
  • There is no risk
  • The mean will be biased

Check it in “What a 95% confidence interval really promises”

5. When is Monte Carlo clearly preferable to the quadrature formula?

  • When all inputs have tiny uncertainties and the model is a simple product
  • When the model has thresholds or strong curvature, or inputs are correlated
  • Never: formulas are always more accurate
  • Only when you have no computer

Check it in “Monte Carlo: propagate by simulation”

6. Which detail is essential so that someone else can reproduce your Monte Carlo result exactly?

  • The colour of the histogram
  • The random seed, the input distributions and N
  • How long it took to run
  • The name of your laptop

Check it in “Monte Carlo: propagate by simulation”

7. SE_A = 0.3 W and SE_B = 0.4 W for two independent conditions. What is the SE of the difference of means, in W?

Answer: W

Check it in “Is the difference real? Effect sizes and correlation”

8. A team tests firmware v2 on Monday morning and v1 on Friday afternoon, when the lab is warmer. v2 uses less power. What is the main problem?

  • The sample is too large
  • Temperature is a confounder: it changed along with the firmware
  • Power can't be measured accurately
  • Nothing: the result is clear

Check it in “Is the difference real? Effect sizes and correlation”

Engineering applications

Acceptance testing

A supplier claims a motor delivers 2.0 N·m. Ten units averaging 1.95 N·m with an interval of ±0.08 N·m cannot reject the claim; the same average from fifty units could.

Tolerance analysis by simulation

When a part's performance depends on several toleranced dimensions through a nonlinear formula, sampling thousands of random builds gives the spread of performance without any calculus.

Summary

Glossary

Mean and median
The mean is the sum of the values divided by how many there are; the median is the middle value once the values are sorted.
Standard deviation
Standard deviation measures how spread out values are around their mean: the square root of the average squared distance from the mean.
Standard error of the mean
The standard error of the mean estimates how much a sample mean would vary between repeated experiments: the sample standard deviation divided by the square root of the number of readings.
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.
Confounding variable
A confounding variable affects both the thing you changed and the thing you measured, creating an apparent link that is not a cause.

Project: Is version B really faster?

Use a School simulation with a random element to compare two settings. Run each enough times to estimate the difference with an interval, write the decision rule first, and report the difference, its interval and the decision.

Deliverables

  • The decision rule, written before the runs
  • The difference with its 95 % interval
  • A note on possible confounders and how you controlled them

References

8. Estimation and error budgets

Chapter version 1 · Technically checked (automated checks only) · Interactive chapter

An estimator is a recipe for turning data into a number, and recipes can be compared: some are biased, some are noisy, and the best trade the two. This chapter treats estimation as engineering. Maximum likelihood chooses parameters that make the data most probable; propagation carries uncertainty through formulas; and an error budget shows which source dominates, so effort goes where it actually reduces the total.

Figure 8.1. Where the uncertainty comes from (described in words)

An error budget with independent terms of 3, 4 and 12 combined by root-sum-square to a total of 13. The terms carry 5.3 %, 9.5 % and 85.2 % of the variance, so halving the largest term would cut the total to about 7.81, while removing the smallest barely helps.

Explanation

8.1 Estimators: bias, variance and error

Two ways to locate a landmark: one is always 20 cm off but rock-steady, the other is right on average but scatters by a metre. Which is better?

The estimator is random

An estimator θ̂ = g(X₁, …, Xₙ) is a random variable, because the data are. Imagine repeating the whole experiment many times: each repeat gives a dart on the board. We judge the estimator by the cloud of darts, not by one throw.

Bias and variance

Bias = E[θ̂] − θ: how far the cloud's centre is from the truth. Variance = E[(θ̂ − E[θ̂])²]: how scattered the cloud is. The sample mean is unbiased with variance σ²/n. Using only the first reading is also unbiased, but its variance is σ²: n times worse.

Mean squared error

MSE = E[(θ̂ − θ)²] = bias² + variance. RMSE = √MSE is in the units of θ. A slightly biased estimator can have lower MSE than an unbiased one if it cuts variance enough. That is why filters sometimes deliberately smooth (accepting lag, a bias) to reduce noise.

Common mix-ups

8.2 Maximum likelihood

A probe's detector counted 12 dust impacts in 4 hours. What impact rate makes that observation least surprising?

Likelihood

Given a model P(data | θ), the likelihood L(θ) is that same expression read as a function of θ, with the data fixed. It is not a probability distribution over θ (it need not integrate to 1). The MLE θ̂ maximises L, or equivalently the log-likelihood ℓ = ln L, which turns products into sums.

Two classic results

Binomial: ℓ(p) = k ln p + (n − k) ln(1 − p) + c; dℓ/dp = 0 gives p̂ = k/n. Poisson with rate λ over time T: ℓ(λ) = k ln(λT) − λT + c; dℓ/dλ = k/λ − T = 0 gives λ̂ = k/T. The MLE is usually the 'obvious' estimate, now with a justification.

Gaussian noise gives least squares

If yᵢ = f(xᵢ; θ) + εᵢ with εᵢ ~ N(0, σ²) independent, then ℓ(θ) = −Σ(yᵢ − f(xᵢ; θ))²/(2σ²) + c. Maximising ℓ is minimising the sum of squared residuals. Least squares is the MLE when the noise is Gaussian, and only then is it guaranteed optimal in this sense.

Derivation: The MLE of a Poisson rate
  1. k events in time T, rate λ: P(k | λ) = e^(−λT)(λT)ᵏ / k!.

  2. Log-likelihood: ℓ(λ) = −λT + k ln λ + k ln T − ln k!.

  3. Differentiate: dℓ/dλ = −T + k/λ.

  4. Set to zero: λ̂ = k/T. Second derivative −k/λ² < 0, so it is a maximum.

  5. Example: 12 impacts in 4 h gives λ̂ = 3 per hour.

Common mix-ups

8.3 Propagating uncertainty: linearisation and Monte Carlo

You know the wheel's circumference to 1% and the turn count to 2%. How well do you know the distance? And what if the formula is not so simple?

First-order propagation

For y = f(x₁, …, xₙ) with independent inputs, σ_y² ≈ Σ (∂f/∂xᵢ)² σᵢ². This is a Taylor expansion to first order: it treats f as a plane near the measured point. It is exact for linear functions and good when σᵢ is small compared with the scale on which f bends.

Handy rules

Sums and differences: absolute uncertainties add in quadrature. Products and quotients: relative uncertainties add in quadrature. Powers: y = xⁿ gives σ_y/y = |n|·σ_x/x. Correlated inputs need the covariance term 2(∂f/∂x)(∂f/∂y)Cov(x, y).

Monte Carlo propagation

Draw many input samples from their distributions, push each through f, and look at the outputs. No derivatives needed, nonlinearity and correlation handled automatically, and you get the whole output distribution. The cost is computation and the need for honest input distributions.

Common mix-ups

8.4 Error budgets: where does the uncertainty come from?

A landing has six independent sources of position error. Halving the smallest one saves almost nothing. Halving the biggest saves a lot. How do you know which is which?

Root-sum-square

If contributions eᵢ are independent with standard deviations σᵢ, the total σ = √(Σσᵢ²). Squares make the big terms dominate: a term half the size of the largest contributes only a quarter as much variance.

Sensitivity and payoff

∂σ/∂σᵢ = σᵢ/σ. Improving the largest term pays most. A good budget lists each term, its source, how it was estimated (test, analysis, data sheet) and its share of total variance σᵢ²/σ².

Allocation and margin

Work backwards from a requirement: if the landing must be within 10 km (3σ), the total 1σ must be ≤ 3.3 km. Allocate that among subsystems so the RSS fits, keeping margin for errors not yet understood. Correlated terms must be combined with their covariance, or added linearly as a conservative bound.

Common mix-ups

Examples to try

Worked solutions are in the interactive chapter online.

Estimators: bias, variance and error: example 1

An estimator has bias 0.3 m and standard deviation 0.4 m. What is its RMSE?

Estimators: bias, variance and error: example 2

Mean of 16 readings with σ = 2 m versus a single reading: compare RMSE (both unbiased).

Maximum likelihood: example 1

12 micrometeoroid impacts are recorded in 4 hours. MLE of the rate and its approximate standard error?

Propagating uncertainty: linearisation and Monte Carlo: example 1

Speed v = d/t with d = 100.0 ± 0.5 m and t = 20.0 ± 0.2 s (independent). Find v ± σ_v.

Error budgets: where does the uncertainty come from?: example 1

Contributions 2, 6, 5 and 1.5 km. Total, and the share of variance from the 6 km term?

Interactive figures, in words

Figure 8.2 from “Estimators: bias, variance and error”

With no systematic offset, compare 'average of all n', 'first reading only' and '0.7 × average' at n = 5. Record bias, spread and RMSE for each. Then add a 0.5 m sensor offset and see which numbers move.

Each dot on the dartboard is one repeated experiment's estimate; the cross marks their centre. The readout gives observed and theoretical bias, spread and RMSE, so the comparison can be made from the numbers alone.

Figure 8.3 from “Maximum likelihood”

Keep the flat prior. Add 7 successes and 3 failures. With a flat prior the posterior is just the normalised likelihood, so its peak is the MLE: check it sits at 0.7. Add more data in the same ratio and watch the peak stay put while it narrows.

With a flat prior, the grid's posterior bars are the normalised likelihood; the readout states the peak value and k/n, which match. All values appear in the text readout.

Laboratory (online)

These run in a browser on the full site. Simulations are simplified educational models.

Practice questions

Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.

1. An estimator has bias 1.2 cm and standard deviation 0.5 cm. What is its RMSE, in cm?

Answer: cm

Check it in “Estimators: bias, variance and error”

2. Estimator A: bias 0, σ = 2. Estimator B: bias 0.5, σ = 1. Which has lower MSE?

  • A
  • B
  • They are equal
  • Cannot tell without more data

Check it in “Estimators: bias, variance and error”

3. A gripper succeeds 18 times in 24 attempts. What is the maximum-likelihood estimate of its success probability?

Answer:

Check it in “Maximum likelihood”

4. Least squares is the maximum-likelihood fit when the measurement noise is…

  • Independent Gaussian with equal variance
  • Uniform
  • Poisson
  • Any distribution with mean zero

Check it in “Maximum likelihood”

5. A position is the sum of two independent legs: 40.0 ± 0.3 m and 25.0 ± 0.4 m. What is the standard uncertainty of the total, in m?

Answer: m

Check it in “Propagating uncertainty: linearisation and Monte Carlo”

6. Kinetic energy ½mv² with mass known exactly and v uncertain by 3%. What is the relative uncertainty of the energy, in %?

Answer: %

Check it in “Propagating uncertainty: linearisation and Monte Carlo”

7. Terms of 3, 4 and 12 m (1σ). What percentage of total variance comes from the 12 m term?

Answer: %

Check it in “Error budgets: where does the uncertainty come from?”

8. A budget has terms 1, 2 and 8 m. You can halve any one term. Which gives the biggest improvement?

  • Halve the 8 m term
  • Halve the 1 m term
  • Halve the 2 m term
  • All give the same improvement

Check it in “Error budgets: where does the uncertainty come from?”

Engineering applications

Navigation accuracy

A rover's position error combines wheel slip, heading drift and map error. A budget shows which term dominates over a given drive, and therefore which sensor upgrade is worth its mass.

Measurement systems

A force rig's uncertainty combines the load cell, the amplifier and the fixture alignment. Engineers buy a better load cell only when the budget says it is the largest term.

Summary

Glossary

Error propagation
Error propagation works out the uncertainty of a calculated result from the uncertainties of its inputs. For independent errors, sums add absolute uncertainties in quadrature and products add relative uncertainties in quadrature.
Random and systematic error
Random errors scatter readings unpredictably above and below the true value; systematic errors shift every reading the same way.
Absolute and relative uncertainty
Absolute uncertainty is the ± range in the same units as the measurement; relative uncertainty is that range divided by the measurement, often as a percentage.
Accuracy, precision and resolution
Accuracy is how close a measurement is to the true value; precision is how close repeated measurements are to each other; resolution is the smallest change an instrument can show.

Project: An error budget for a measurement

Choose a measurement you can model, such as a distance from a range sensor on a tilting mount. List every error source with a stated 1σ value and its basis, combine them, and recommend the single improvement that most reduces the total.

Deliverables

  • The budget table with sources and their basis
  • The combined uncertainty with the method used
  • A recommendation backed by each term's share

References

Known limitations