Why numerical analysis?

Part 1 — Numbers on a computer

Numerical analysis for biologists

About this lecture

You already call optim(), uniroot(), integrate(), solve() and ode(). This course opens those boxes. Today sets up the whole course:

  • What a numerical method is: a finite recipe of arithmetic that approximates a mathematical answer.
  • Three ways a computation goes wrong: rounding, truncation and instability, each with a tiny example.
  • Error vs cost: more work buys accuracy, up to a limit.
  • A recap of Taylor polynomials, with the remainder term: the tool behind almost every method in the course.
  • Biology: a growth-curve fit that reports success and returns a doubling time of 1 minute.

A growth curve, a fit, a green light

Bacteria in a plate reader, OD600 every 2 hours for 24 hours. The reader exports time in minutes. Fit the logistic model N(t) = \dfrac{K}{1 + (K/N_0 - 1)\,e^{-rt}}:

t_min <- seq(0, 1440, by = 120)          # minutes
od <- c(0.001, 0.047, 0.139, 0.282, 0.581, 0.859, 1.049,
        1.161, 1.152, 1.217, 1.182, 1.176, 1.185)
logistic <- function(p, t)               # p = (r, K, N0)
  p[2] / (1 + (p[2] / p[3] - 1) * exp(-p[1] * t))
sse <- function(p) sum((od - logistic(p, t_min))^2)
fit <- optim(c(r = 0.5, K = 1, N0 = 0.05), sse)  # "r is about 0.5"
fit$par
#            r            K           N0
# 0.6759128151 0.8357871891 0.0009330162
  • optim minimises the sum of squared errors (SSE). fit$convergence is 0, meaning “converged”. No warning, no error.

Two “converged” fits of the same data

  • Same data, same model, same optim; only the starting value of r differs.
  • Both report convergence = 0. One is right (doubling 79 min), one is nonsense.
  • “Converged” means “stopped improving”, not “found the answer”.

What is a numerical method?

A numerical method is a finite list of arithmetic operations (+,-,\times,\div) that approximates a mathematical answer we cannot write down exactly.

x <- 1                                # first guess for sqrt(2)
for (i in 1:5) {
  x <- (x + 2 / x) / 2                # average of x and 2/x
  print(x, digits = 16)
}
# [1] 1.5
# [1] 1.416666666666667
# [1] 1.41421568627451
# [1] 1.41421356237469
# [1] 1.414213562373095
  • An approximation, an iteration, and a stopping rule. Each one is a place where error enters.
  • Questions for every method: how accurate? how fast? when does it fail?

What is inside the black boxes

R Python Computes Method inside Silent failure Part
solve numpy.linalg.solve A\mathbf x = \mathbf b LU with pivoting ill-conditioned A: digits lost 3
uniroot scipy.optimize.brentq f(x) = 0 Brent: bisection + secant loose default tolerance (R) 2
optim scipy.optimize.minimize minimum of f Nelder–Mead, BFGS stops at a plateau or local minimum 9
integrate scipy.integrate.quad \int_a^b f(x)\,dx adaptive Gauss–Kronrod misses a narrow peak 7
ode (deSolve) scipy.integrate.solve_ivp y' = f(t, y) adaptive Runge–Kutta, LSODA wrong tolerance, stiffness 8
  • Each one is a numerical method with tuning knobs (tolerances, starting values, step sizes) and defaults chosen for a typical problem.
  • Your problem may not be typical. The course teaches you what the knobs do.

Silent failures in two lines

integrate(dnorm, 0, 20000)       # half the area under a normal: 0.5
# 0 with absolute error < 0
integrate(dnorm, 0, Inf)
# 0.5 with absolute error < 4.7e-05

uniroot(function(x) x^2 - 2, c(0, 2))$root - sqrt(2)
# [1] -2.423776e-07
  • integrate samples 21 points in [0, 20000]; all of them are far out where dnorm is 0. It reports 0, with an error estimate of 0. Why: Numerical integration.
  • uniroot stops when it is within its default tolerance, about 10^{-4}. Fine for a dose, not for a likelihood (Newton and secant methods).

Three ways a computation goes wrong

  1. Rounding error. The computer stores about 16 significant digits. Every operation rounds.
  2. Truncation error. The method stops early: a finite sum for an infinite series, a finite step h instead of a limit h \to 0, a finite number of iterations.
  3. Instability. The algorithm amplifies small errors (from 1 or 2) step after step, until they swamp the answer.

Plus one that is not the computer’s fault: an ill-conditioned problem, where tiny changes in the data change the answer a lot (Error, conditioning and stability).

1. Rounding

0.1 + 0.2 == 0.3
# [1] FALSE
print(0.1 + 0.2, digits = 17)
# [1] 0.30000000000000004
1e16 + 1 - 1e16
# [1] 0
  • 0.1 is stored rounded (it has no exact binary form). Near 10^{16}, stored numbers are 2 apart, so adding 1 is lost.
  • Each rounding error is tiny (relative size \approx 10^{-16}). Trouble starts when many of them add up or one gets amplified.

Full story: How computers store numbers (binary, machine epsilon, overflow, log-likelihoods).

2. Truncation

The slope of e^x at x = 0 is exactly 1. Approximate it with a finite step h:

h <- 0.1
(exp(h) - 1) / h          # slope of the secant from 0 to h
# [1] 1.051709
  • Error 0.0517. Not rounding: the formula itself is only an approximation.
  • Why? e^h = 1 + h + \frac{h^2}{2} + \dots, so \dfrac{e^h - 1}{h} = 1 + \dfrac{h}{2} + \dots The error is about h/2 = 0.05.
  • Make h smaller and the truncation error shrinks, but only up to a point (two slides on).

More: Convergence and cost, and finite differences in Numerical differentiation (Part 7).

3. Instability

Drug clearance C' = -kC, k = 0.8 per hour. Step forward with Euler, C_{n+1} = C_n - hkC_n:

k <- 0.8; h <- 3      # 3-hour steps
C <- numeric(9); C[1] <- 10   # mg/L
for (i in 1:8)
  C[i + 1] <- C[i] - h * k * C[i]
signif(C, 2)
# [1]   10  -14   20  -27   38  -54   75 -110  150

  • Each step multiplies by 1 - hk = -1.4: any error grows by 40 % and flips sign every step.
  • With h = 0.5 the factor is 0.6, and errors die out. Same formula, different stability.

Stability of algorithms: Error, conditioning and stability; of ODE solvers: Initial value problems and Euler’s method and Stiffness and implicit methods (Part 8).

Error vs cost

  • Left: more terms of the series for e (more work) give a smaller truncation error, until it hits the rounding level \approx 10^{-16}.
  • Right: a smaller step helps only down to h \approx 10^{-8}; below that, rounding error grows. Best accuracy: about 8 digits, not 16.

Taylor polynomials: the workhorse

Near a point a, replace a hard function by a polynomial, which needs only + and \times:

P_n(x) = f(a) + f'(a)(x-a) + \frac{f''(a)}{2!}(x-a)^2 + \dots + \frac{f^{(n)}(a)}{n!}(x-a)^n

  • P_n matches f and its first n derivatives at a.
  • Most of the course uses a = 0 or “a point we are already at”, and small steps h = x - a.
  • Two questions: how good is P_n near a? How fast does the error shrink as x \to a?

Example: e^x around 0

Every derivative of e^x is e^x, and e^0 = 1, so

e^x \approx 1 + x + \frac{x^2}{2} + \frac{x^3}{6} + \dots

  • Close to 0 all three are good; far from 0 you need more terms.

With numbers: x = 0.1

x <- 0.1
P <- c(1 + x, 1 + x + x^2/2, 1 + x + x^2/2 + x^3/6)
P
# [1] 1.100000 1.105000 1.105167
exp(x) - P
# [1] 5.170918e-03 1.709181e-04 4.251409e-06
P_1 P_2 P_3
error 5.2\times10^{-3} 1.7\times10^{-4} 4.3\times10^{-6}
next term \frac{x^{n+1}}{(n+1)!} 5.0\times10^{-3} 1.67\times10^{-4} 4.2\times10^{-6}
  • Each extra term gains about 1.5 digits at x = 0.1. The error is close to the first term we left out.

The remainder term

Taylor’s theorem: for some \xi (unknown) between a and x,

f(x) = P_n(x) + R_n(x), \qquad R_n(x) = \frac{f^{(n+1)}(\xi)}{(n+1)!}(x-a)^{n+1}

For e^x, n = 2, x = 0.1: R_2 = \dfrac{e^{\xi}}{6}\,(0.1)^3 with 0 < \xi < 0.1, so

\frac{1}{6}(0.001) = 1.667\times10^{-4} \;\le\; R_2 \;\le\; \frac{e^{0.1}}{6}(0.001) = 1.842\times10^{-4}

  • The actual error, 1.709\times10^{-4}, is inside the bound. We bounded the error without knowing the answer.

How fast the error shrinks: order

From the remainder, the error of P_n is about C\,x^{n+1} for small x. Halve x:

x <- c(0.1, 0.05, 0.025)
err1 <- exp(x) - (1 + x)              # P1
err1[1:2] / err1[2:3]                 # ratio when x is halved
# [1] 4.068077 4.033683
err2 <- exp(x) - (1 + x + x^2/2)      # P2
err2[1:2] / err2[2:3]
# [1] 8.101774 8.050441
  • P_1: halving x divides the error by 4 = 2^2. P_2: by 8 = 2^3.
  • Notation: error = O(x^{n+1}), read “of order x^{n+1}”: it shrinks at least like x^{n+1}. The same halving test works for any method with a step size.

On log–log axes, order is a slope

  • If error \approx C x^{p}, then \log(\text{error}) = \log C + p \log x: a straight line with slope p.
  • Slope 2, 3, 4 for P_1, P_2, P_3. Every method in the course gets a plot like this.

Try it: Taylor error, order and the rounding floor

A second expansion: \log(1+x)

A population grows by a fraction x per hour. The continuous rate is r = \log(1+x). For small x:

\log(1+x) = x - \frac{x^2}{2} + \frac{x^3}{3} - \dots

x <- 0.01                             # 1 % per hour
log(1 + x) - c(x, x - x^2/2)          # errors of P1 and P2
# [1] -4.966915e-05  3.308532e-07
  • So r \approx x for small growth, with error about x^2/2 = 5\times10^{-5}.
  • Remainder of P_2: f'''(\xi) = 2/(1+\xi)^3, so R_2 = \dfrac{x^3}{3(1+\xi)^3}, between 3.24\times10^{-7} and 3.33\times10^{-7}. Actual: 3.31\times10^{-7}.
  • For very small x, computing log(1 + x) loses digits; R’s log1p uses this expansion instead (How computers store numbers).

Where Taylor comes back

Unit / Part Taylor statement Gives
Newton (Part 2) f(x+h) \approx f(x) + f'(x)\,h set to 0, solve for h
Conditioning (unit 3) f(x + \delta) - f(x) \approx f'(x)\,\delta how errors in data propagate
Finite differences (Part 7) \dfrac{f(x+h) - f(x)}{h} = f'(x) + \dfrac{h}{2}f''(\xi) derivative, error O(h)
Euler / Runge–Kutta (Part 8) y(t+h) \approx y(t) + h\,y'(t) one ODE step
Optimisation (Part 10) f(x+h) \approx f(x) + f'(x)h + \tfrac12 f''(x)h^2 minimise the parabola
  • Every time: replace the function by its Taylor polynomial, solve the easy problem, use the remainder to bound the error.

Back to the growth curve: why did optim stop?

  • With r = 0.5 per minute, the curve reaches K within minutes. Changing r a bit changes nothing: the SSE is flat.
  • The optimiser sees no slope, makes no progress, and stops. “Converged.”

Checks that would have caught it

for (r0 in c(0.001, 0.01, 0.1, 1)) {        # several starting values
  f <- optim(c(r = r0, K = 1, N0 = 0.05), sse)
  cat("start r =", r0, " SSE =", signif(f$value, 3),
      " r =", signif(f$par["r"], 3), "\n")
}
# start r = 0.001  SSE = 2.23  r = 0.333
# start r = 0.01  SSE = 0.003  r = 0.00874
# start r = 0.1  SSE = 2.23  r = 0.237
# start r = 1  SSE = 2.23  r = 1.18
  • Plot the fit over the data, and try several starts: keep the lowest SSE; different answers mean a hard problem.
  • Check units and scale: is a 1-minute doubling time plausible? Use units where parameters are near 1 (hours, not minutes).
  • convergence == 0 is necessary, not sufficient. Fitting in depth: Gradient descent, Newton and quasi-Newton (scaling, this fit) and Nonlinear least squares and ODE fitting (multistart), Part 10.

The course map

  1. Numbers on a computer: floating point, error, conditioning, stability, cost (this Part).
  2. Nonlinear equations: bisection, fixed points, Newton. Steady states, EC50.
  3. Linear systems: LU, pivoting, sparse matrices. Spectral unmixing, count matrices.
  4. Least squares: QR, SVD, regularisation. Calibration curves, deconvolution.
  5. Eigenvalues: power iteration, QR algorithm, Lanczos. Leslie matrices, PCA.
  6. Interpolation: polynomials, splines, FFT. Smoothing time courses, circadian rhythms.
  7. Differentiation and integration: finite differences, quadrature, Monte Carlo. Growth rates, AUC.
  8. ODEs: Euler to Runge–Kutta, stiffness, Gillespie. Epidemics, gene circuits.
  9. SDEs: Brownian motion, Euler–Maruyama. Particle tracking, noisy growth.
  10. Optimisation and fitting: gradient methods, nonlinear least squares, identifiability. Today’s growth curve.
  11. Diffusion and heat: finite-difference PDEs in microfluidic chips, iterative solvers.
  12. Finite elements and flow: meshes beyond rectangles, flow solvers.

Next in Part 1

  • How computers store numbers: how a double is stored, machine epsilon, overflow and underflow, why 0.1 + 0.2 != 0.3. A likelihood over 10 000 alignment sites underflows to 0: log-likelihoods and log-sum-exp.
  • Error, conditioning and stability: absolute and relative error, catastrophic cancellation, the condition number, stable vs unstable algorithms. A variance formula that loses all its digits; a dose read off a response near the plateau.
  • Convergence and cost: truncation vs rounding, order of accuracy on log–log plots, big-O operation counts, timing code. Growth rate from an OD curve; from 100 genes to 20 000 genes × 100 000 cells.

Each unit: lecture, quiz, exercise with by-hand problems and code (R and Python).

Summary

  • A numerical method approximates an answer with finitely many arithmetic steps: approximation, iteration, stopping rule.
  • Three ways it goes wrong: rounding (16 digits), truncation (stopping early), instability (errors amplified). Plus ill-conditioned problems.
  • Error vs cost: more work buys accuracy, down to the rounding floor.
  • Taylor: f(x) = P_n(x) + R_n(x), R_n = \frac{f^{(n+1)}(\xi)}{(n+1)!}(x-a)^{n+1}. The error is O(h^{n+1}): a slope n+1 on a log–log plot.
  • Library routines fail silently. Plot the result, try several starts, check units, and do not trust convergence = 0 alone.