Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

19. Numerical error

School of Engineering, Nazarbayev University

Track: advanced  ·  Prerequisites: Chapters 3, 12 and 18

Reading: Bevington & Robinson, Appendix A.3 · Press et al., Numerical Recipes, ch. 1.1 and 5.7 · Higham, Accuracy and Stability of Numerical Algorithms, ch. 1–2

Results today pass through a computer between the measurement and the report, and the computer adds errors of its own. Three kinds matter:

  • rounding error: real numbers are stored with about 16 significant digits, and every operation rounds;

  • truncation or discretisation error: a derivative is replaced by a difference quotient, an integral by a sum, a differential equation by finite time steps;

  • sampling error of Monte Carlo methods, treated in Chapter 10.

Usually all three are negligible, but not always, and unlike measurement errors they are under the analyst’s control. This chapter shows how to recognise them, how to estimate them, and when they belong in the uncertainty budget.

19.1 Floating-point numbers

A double-precision number has a 53-bit significand, so it represents a real number with a relative rounding error of at most u=2−53≈1.1×10−16u = 2^{-53} \approx 1.1\times10^{-16}. The spacing of numbers just above 1 is ε=2−52≈2.2×10−16\varepsilon = 2^{-52} \approx 2.2\times10^{-16}, the machine epsilon (Goldberg 1991). Most decimal fractions are not exact binary fractions, so even entering data rounds them.

machine epsilon: 2.220e-16;  single precision: 1.192e-07
0.1 + 0.2 == 0.3: False;  difference 5.55e-17
1e16 + 1 - 1e16 = 0.0

A relative error of 10-16 in one operation is harmless. Trouble comes when an algorithm amplifies it, and the commonest amplifier is the subtraction of nearly equal numbers.

19.2 Cancellation: computing a variance

The variance of NN readings can be computed as

s2=1N−1[∑xi2−Nxˉ2]ors2=1N−1∑(xi−xˉ)2.s^2 = \frac{1}{N-1}\left[\sum x_i^2 - N\bar x^2\right] \qquad\text{or}\qquad s^2 = \frac{1}{N-1}\sum (x_i - \bar x)^2 .

The two are equal in exact arithmetic. The first needs only one pass through the data and appears in many textbooks and pocket calculators. But if the readings have a large common offset compared with their spread, say lengths of about 1 m measured to 1 µm, the two terms in the bracket agree in nearly all their digits, and their difference is mostly rounding error. The relative error is about u (xˉ/s)2u\,(\bar x/s)^2: with xˉ/s=106\bar x/s = 10^6 only four digits survive, and at 108 none. The two-pass formula avoids the cancellation, and Welford’s algorithm (Welford 1962; Chan, Golub & LeVeque 1983) achieves the same accuracy in one pass, updating the mean and the sum of squared deviations reading by reading.

offset/spread = 1e+03: relative error  textbook 3.3e-10,  two-pass 1.5e-15,  Welford 3.2e-14
offset/spread = 1e+06: relative error  textbook 1.7e-04,  two-pass 8.7e-13,  Welford 4.1e-12
offset/spread = 1e+08: relative error  textbook 1.0e+00,  two-pass 2.8e-10,  Welford 7.0e-10

The textbook formula loses accuracy as the square of the offset and is useless beyond an offset of about 107 times the spread, where it can even return a negative variance. The other two are accurate to the level of the rounding of the data themselves (the stored readings xix_i already carry an absolute rounding error of about u xˉu\,\bar x, which limits any method). A cheap safeguard for any formula: subtract a typical value, such as the first reading, before computing.

19.3 Conditioning

Some problems amplify small changes of their input whatever the algorithm. For a function y=f(x)y = f(x), the condition number

κ=∣x f′(x)f(x)∣\kappa = \left|\frac{x\,f'(x)}{f(x)}\right|

is the factor by which a relative change of xx appears as a relative change of yy. It is exactly the elasticity of Section 18.1. A relative rounding error of uu in the input therefore becomes about κu\kappa u in the output; but so does a relative measurement error, so an ill-conditioned problem is sensitive to the data long before it is sensitive to rounding.

For a linear system Ap=yA\mathbf p = \mathbf y, as in a least-squares fit, the condition number of the matrix plays the same role. Solving the normal equations (ATA)p=ATy(A^TA)\mathbf p = A^T\mathbf y squares it, because κ(ATA)=κ(A)2\kappa(A^TA) = \kappa(A)^2. The cell fits a cubic to 21 annual readings, with the year written in three ways.

variable               cond(A)   cond(A^T A)   relative error of the coefficients
                                                normal equations      lstsq
year as is            3.8e+17    1.3e+26         2e+00             1e+00
year - 1900           1.0e+10    1.1e+20         7e-08             1e-11
year - 2010           6.5e+02    4.3e+05         2e-16             8e-16
(year - 2010)/10      7.5e+00    5.6e+01         7e-16             7e-16

The data lie exactly on a cubic, so any error in the coefficients is numerical. With the raw years, the columns of AA (1, tt, t2t^2, t3t^3 with t≈2000t \approx 2000) are almost parallel, κ(A)\kappa(A) exceeds 1/u1/u, and both methods return coefficients with no correct digits. Measured from 1900, the problem is ill-conditioned but solvable: lstsq, which factorises AA without forming ATAA^TA, keeps about eleven digits, while the normal equations, with the squared condition number, keep about seven. (The actual losses are smaller than the bound κu\kappa u suggests, but they grow with κ\kappa as it does.) Centring and scaling the variable brings both condition numbers down to harmless values, which is the numerical side of the advice of Section 13.3. The rule: centre and scale before fitting, and prefer an orthogonal factorisation to the normal equations.

19.4 Numerical derivatives: choosing the step

Linear propagation needs sensitivity coefficients, and ep.jacobian computes them by central differences, f′(x)≈[f(x+h)−f(x−h)]/2hf'(x) \approx [f(x+h) - f(x-h)]/2h. Two errors compete. The truncation error of the formula is h2∣f′′′∣/6h^2 |f'''|/6 and shrinks with hh. The rounding error: f(x±h)f(x\pm h) each carry an error of about u∣f∣u|f|, which the division by 2h2h amplifies to about u∣f∣/hu|f|/h. The total is smallest at

hopt≈(3u∣f∣∣f′′′∣)1/3∼u1/3∣x∣≈5×10−6∣x∣,h_\text{opt} \approx \left(\frac{3u|f|}{|f'''|}\right)^{1/3} \sim u^{1/3}|x| \approx 5\times10^{-6}|x| ,

where the error is about u2/3≈10−11u^{2/3} \approx 10^{-11} relative. The forward difference [f(x+h)−f(x)]/h[f(x+h) - f(x)]/h has a truncation error of order hh, an optimum near u1/2∣x∣≈10−8∣x∣u^{1/2}|x| \approx 10^{-8}|x|, and a best accuracy of only a few times 10-9 (Press et al., ch. 5.7). The cell differentiates f(x)=x exf(x) = x\,e^{x} at x=1x = 1 with steps from 10-14 to 10-1.

central difference: best step 3.2e-06, relative error 1.2e-11;  at h = 1e-5: 3.8e-11
forward difference: best step 1.0e-08, relative error 2.4e-09
ep.jacobian (relative step 1e-5): relative error 3.8e-11

The default relative step 10-5 of ep.jacobian sits at the bottom of the central-difference curve, with an error near 10-11, far below any measurement uncertainty. Too small a step is worse than too large: at h=10−13h = 10^{-13} the derivative has only three or four correct digits. If a model is itself computed numerically, for example by an iterative solver with a tolerance of 10-8, then uu in the formula is replaced by that tolerance, and the optimal step becomes much larger.

19.5 Discretisation error and Richardson extrapolation

A quantity computed with a step hh (a time step, a grid spacing, a number of quadrature points) carries a discretisation error that, for a method of order pp, behaves as E(h)≈ChpE(h) \approx C h^p for small hh. Results with two steps then give an estimate of the error, without knowing the exact answer (Richardson 1911):

fexact≈fh+fh−f2h2p−1,E(h)≈fh−f2h2p−1.f_\text{exact} \approx f_h + \frac{f_h - f_{2h}}{2^p - 1} , \qquad E(h) \approx \frac{f_h - f_{2h}}{2^p - 1} .

With three steps h,2h,4hh, 2h, 4h, the observed order p=log⁡2[(f4h−f2h)/(f2h−fh)]p = \log_2[(f_{4h} - f_{2h})/(f_{2h} - f_h)] checks that hh is small enough for the asymptotic form to hold. This procedure, with a safety factor, is the basis of the grid convergence index used to report discretisation uncertainty in computational engineering (Roache 1998).

The example integrates the equation of a pendulum released from 120°, θ¨=−(g/L)sin⁡θ\ddot\theta = -(g/L)\sin\theta with g/L=1g/L = 1, up to t=10t = 10, with the classical fourth-order Runge–Kutta method (RK4) and with the first-order Euler method, and examines the computed angle at the end. The reference answer comes from RK4 with a very small step.

reference angle at t = 10: 1.2317796575 rad
  RK4:   h        theta(10)       true error    Richardson estimate   observed order
      0.1000   1.2317805945   9.37e-07      2.85e-06            5.75
      0.0500   1.2317798287   1.71e-07      5.11e-08            5.80
      0.0250   1.2317796718   1.42e-08      1.05e-08            2.29
      0.0125   1.2317796585   9.99e-10      8.82e-10            3.57
      0.0063   1.2317796576   6.60e-11      6.22e-11            3.83
      0.0031   1.2317796576   4.36e-12      4.11e-12            3.92
  Euler: h = 0.00020: true error 4.78e-03, Richardson estimate 4.78e-03, observed order 1.00

Once the step is small enough for the observed order to settle near 4, the Richardson estimate agrees with the true error to within about 10 %, so the error of a computation can be estimated from the computation itself. At the coarser steps the observed order is erratic (here because the error of θ(10)\theta(10) passes through zero as hh changes), and then the estimate cannot be trusted. Euler’s method, of order 1, needs a step 500 times smaller than RK4 at h=0.1h = 0.1, and still has an error about 5000 times larger.

19.6 Long integrations: what the error does over time

For long simulations, as in the molecular dynamics of Chapter 23, the size of the error after one step matters less than how it accumulates. The total energy E=12θ˙2−cos⁡θE = \tfrac12\dot\theta^2 - \cos\theta of the pendulum should be constant. The cell follows it over 1000 time units (about 140 periods) with Euler, RK4, and the velocity Verlet method, which is only second order but symplectic: it exactly conserves a slightly perturbed energy, so the error of EE oscillates instead of growing (Hairer, Lubich & Wanner 2006).

Euler        (h = 0.100): energy error after 10, 100, 1000 time units: +5.8e-01, +4.8e+00, +4.8e+01;  largest |error| over the last 100 units 4.8e+01
RK4          (h = 0.100): energy error after 10, 100, 1000 time units: -1.7e-06, -1.1e-05, -1.1e-04;  largest |error| over the last 100 units 1.1e-04
Verlet       (h = 0.100): energy error after 10, 100, 1000 time units: -4.1e-04, +1.9e-04, +8.3e-05;  largest |error| over the last 100 units 2.8e-03
Verlet, h/4  (h = 0.025): energy error after 10, 100, 1000 time units: -2.5e-05, +1.2e-05, +8.7e-06;  largest |error| over the last 100 units 1.8e-04

Euler’s energy error grows without bound; with this step the energy soon exceeds the value needed to swing over the top, so the simulated pendulum rotates instead of oscillating. RK4 is very accurate, but its energy error grows steadily, in proportion to the elapsed time. The Verlet error with the same step is larger at first but does not grow: it oscillates within a fixed band. RK4 evaluates the force four times per step and Verlet once, so the fair comparison is with Verlet at a quarter of the step. Its band is still slightly wider than RK4’s error after 1000 time units, but RK4’s error grows in proportion to time, so it overtakes the band after roughly 1600 units and keeps growing, while the Verlet error never does. Molecular dynamics runs last millions of steps. For long simulations the structure of the error matters more than its order, which is why molecular dynamics codes use Verlet-type integrators, and why a drift of a conserved energy is the standard diagnostic of numerical error in such simulations.

19.7 Numerical error in the uncertainty budget

Numerical errors are treated like any other source of uncertainty (Chapter 18):

  1. Estimate them: by repeating the computation with a halved step (Richardson), a tighter tolerance, higher precision, or a different algorithm, or, for Monte Carlo, from the sampling error (Section 10.4).

  2. If an estimate is below about a tenth of the combined measurement uncertainty, it adds less than 0.5 % in quadrature: state that it was checked and neglect it.

  3. Otherwise, reduce it (it is usually cheap to do so), or include it as a Type B term. A discretisation error estimated by Richardson is a bias of known sign, so correct for it where possible and include the uncertainty of the correction.

A computed result whose numerical error has not been checked is, strictly, a result of unknown uncertainty.

<Figure size 1012x814 with 4 Axes>

(a) Relative error of the sample variance of 1000 readings against the ratio of their common offset to their spread (dotted: the estimate u(xˉ/s)2u(\bar x/s)^2). (b) Error of numerical derivatives of xexx e^x at x=1x = 1; dotted: rounding error u/hu/h; dashed: truncation error of the central difference. (c) Error of a pendulum integration against the time step, with Richardson estimates (crosses). (d) Error of the energy over long integrations with h=0.1h = 0.1, and with Verlet at h=0.025h = 0.025, which costs the same number of force evaluations as RK4 at h=0.1h = 0.1.

Summary

  • Rounding is harmless until an algorithm amplifies it; subtraction of nearly equal numbers is the usual amplifier. Compute variances with a two-pass or Welford algorithm, or after subtracting an offset.

  • The condition number of a problem is the elasticity of its output; it amplifies rounding and measurement errors alike. Centre and scale variables before fitting, and avoid the normal equations when the matrix is ill-conditioned.

  • Central differences with a relative step near 10-5 give derivatives accurate to about 10-11; much smaller steps are worse.

  • Estimate discretisation error by halving the step; check the observed order before trusting the Richardson estimate.

  • Over long integrations, the structure of the error (bounded or drifting) matters more than its order.

  • Numerical error is a term in the budget like any other: estimate it, and neglect it only once it is shown to be small.

References

  • T. F. Chan, G. H. Golub and R. J. LeVeque, “Algorithms for computing the sample variance: analysis and recommendations”, Am. Stat. 37, 242 (1983).

  • D. Goldberg, “What every computer scientist should know about floating-point arithmetic”, ACM Comput. Surv. 23, 5 (1991).

  • E. Hairer, C. Lubich and G. Wanner, Geometric Numerical Integration, 2nd ed. (Springer, 2006).

  • N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed. (SIAM, 2002).

  • W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery, Numerical Recipes, 3rd ed. (Cambridge University Press, 2007).

  • L. F. Richardson, “The approximate arithmetical solution by finite differences of physical problems involving differential equations, with an application to the stresses in a masonry dam”, Phil. Trans. R. Soc. Lond. A 210, 307 (1911).

  • P. J. Roache, Verification and Validation in Computational Science and Engineering (Hermosa, 1998).

  • B. P. Welford, “Note on a method for calculating corrected sums of squares and products”, Technometrics 4, 419 (1962).

Exercises

  1. Repeat the variance comparison in single precision (np.float32). At what offset does the textbook formula fail now?

  2. Show that the condition number of f(x)=x−1f(x) = x - 1 near x=1x = 1 is ∣x/(x−1)∣|x/(x - 1)|, and relate this to the cancellation of Section 19.2.

  3. Derive hopth_\text{opt} for the central difference, and the corresponding result for the forward difference.

  4. Use Richardson extrapolation on the RK4 results to improve θ(10)\theta(10), and estimate the error of the extrapolated value.

  5. In the long integration, halve the time step. By what factor does the energy error of each method change, and does this match its order?