Objective
You already know that 0.1 + 0.2 != 0.3 and that subtraction cancels digits. This lesson makes that knowledge quantitative. By the end you should be able to bound the rounding error of a computation, say whether a bad answer is the fault of the problem (ill-conditioning) or of the algorithm (instability), and use the inequality that connects them:
The layout of a double
A 64-bit double stores a sign bit , an 11-bit biased exponent and a 52-bit fraction :
| Exponent field | Meaning |
|---|---|
| normal: | |
| zero () or subnormal: | |
| () or NaN () |
Inside one binade there are exactly equally spaced doubles, apart. That spacing is the unit in the last place, . Two constants follow:
- Machine epsilon .
- Unit roundoff , the largest relative error of rounding to nearest. For any real in the normal range, with .
Because positive doubles are ordered like their bit patterns read as integers, the number of ulps between two doubles of the same sign is the difference of those integers. This is the robust way to say "these differ in the last bit".
Worked example
decoding 0.1 and counting ulps
Decode the bits of 0.1 and -2.5, and find how many ulps separate 0.1 + 0.2 from 0.3. What is the spacing of doubles near 100 and near ?
Show solutionHide solution
import math, struct
def fields(x):
bits = struct.unpack(">Q", struct.pack(">d", x))[0]
sign = bits >> 63
exponent = (bits >> 52) & 0x7FF
fraction = bits & (2**52 - 1)
return hex(bits), sign, exponent - 1023, fraction / 2**52
def ulps_apart(a, b): # for finite doubles of the same sign
ia = struct.unpack(">q", struct.pack(">d", a))[0]
ib = struct.unpack(">q", struct.pack(">d", b))[0]
return abs(ia - ib)
print(fields(0.1))
print(fields(-2.5))
print(ulps_apart(0.1 + 0.2, 0.3), math.ulp(100.0), math.ulp(1e8))
# ('0x3fb999999999999a', 0, -4, 0.6000000000000001)
# ('0xc004000000000000', 1, 1, 0.25)
# 1 1.4210854715202004e-14 1.4901161193847656e-08
0.1has biased exponent0x3FB, so the scale is , and the significand is : . The fraction999...9Ais the repeating binary pattern of , rounded up in the last hex digit, which is why the stored value is slightly above .-2.5is : sign bit 1, exponent , fraction , which is exact.0.1 + 0.2and0.3are adjacent doubles: one ulp apart.- , so . , so . A notional of held as a double cannot represent changes below about ; the relative precision is the same everywhere, the absolute precision is not.
The standard model and how errors propagate
IEEE 754 requires and to be correctly rounded: the result is the exact result rounded once. So for these operations
(Library functions such as exp, log and sin are usually within one ulp, but the standard does not require correct rounding for them.)
Now suppose the inputs already carry relative errors: , . To first order in :
- Multiplication and division: . Relative errors add. A product of rounded factors has relative error at most about ; it never blows up.
- Addition and subtraction:
The amplification factor is 1 when the signs agree and enormous when . This is catastrophic cancellation made precise: the subtraction itself is exact or nearly so, but it divides the inherited error by a tiny number.
Chaining the model gives the classic bound for recursive summation :
Note the : the bound is relative to the sum of magnitudes, not to . Pairwise summation (what NumPy's sum does on contiguous float arrays) replaces by .
Condition number: a property of the problem
The relative condition number of evaluating at measures how much a relative change in the input moves the output:
| Ill-conditioned when | ||
|---|---|---|
| never | ||
| large | ||
| (solve) | nearly singular |
Since every input is rounded on entry, even a perfect algorithm suffers a relative error of about . You lose roughly significant digits, and no algorithm can get them back without changing the problem (more precision, or a reformulation such as passing instead of to a logarithm, which is what log1p does).
Backward error: a property of the algorithm
An algorithm returns instead of . Its forward error is . Its backward error is the smallest relative perturbation of the input that explains the output exactly:
An algorithm is backward stable if for every input: it gives the exact answer to a slightly wrong question. Combining the definitions,
A large forward error therefore has two possible causes, and you diagnose which by computing the backward error (for a linear system, the relative residual ). Backward stable in practice: summation, dot products, Gaussian elimination with partial pivoting, Householder QR, the SVD. Not backward stable: forming the normal equations for least squares, which squares the condition number () before solving anything; QR on itself avoids that.
Worked example
a well-conditioned problem, an unstable algorithm
Compute by summing its Taylor series until the terms are negligible. The condition number of at is only 20, so roughly 14 digits should be attainable. How many do you get, why, and what is the fix?
Show solutionHide solution
import math
def exp_taylor(x):
term, total, n = 1.0, 1.0, 0
while abs(term) > 1e-17 * abs(total):
n += 1
term *= x / n
total += term
return total
for x in (-1.0, -10.0, -20.0):
naive = exp_taylor(x)
stable = 1 / exp_taylor(-x)
rel = lambda v: abs(v - math.exp(x)) / math.exp(x)
print(f"x={x:5.0f} naive rel err {rel(naive):.1e} 1/exp_taylor(-x) rel err {rel(stable):.1e}")
# x= -1 naive rel err 3.0e-16 1/exp_taylor(-x) rel err 1.5e-16
# x= -10 naive rel err 2.0e-09 1/exp_taylor(-x) rel err 0.0e+00
# x= -20 naive rel err 2.0e+00 1/exp_taylor(-x) rel err 4.0e-16
Zero correct digits at : the naive sum is off by 200%.
Why. The terms alternate in sign and the largest are . By the summation bound, the absolute error is of order in the worst case, and of order from the largest terms alone. The answer is , so the relative error is of order 1, exactly as observed. At the same estimate gives , matching the observed .
The problem is fine (); the algorithm has a huge backward error because it computes a tiny number as the difference of huge ones. This is the amplification factor at work, here about in the worst case.
Fix. Sum the series for , whose terms are all positive (amplification factor 1, relative error about ), and take the reciprocal, which is a single correctly rounded division. Relative error . The general lesson: a mathematically equivalent formula can be numerically very different, and the difference shows up in the backward error, not in the condition number.
Worked example
a stable algorithm, an ill-conditioned problem
Solve where is the Hilbert matrix, , and , so the true solution is all ones. Use numpy.linalg.solve (LU with partial pivoting) for . Report the condition number, the forward error and the backward error, and check the inequality between them.
Show solutionHide solution
import numpy as np
for n in (6, 10, 12):
H = np.array([[1.0 / (i + j + 1) for j in range(n)] for i in range(n)])
x_true = np.ones(n)
b = H @ x_true
x = np.linalg.solve(H, b)
fwd = np.linalg.norm(x - x_true, np.inf) / np.linalg.norm(x_true, np.inf)
bwd = np.linalg.norm(b - H @ x, np.inf) / (np.linalg.norm(H, np.inf) * np.linalg.norm(x, np.inf))
print(n, f"cond={np.linalg.cond(H, np.inf):.2e}", f"forward={fwd:.2e}", f"backward={bwd:.2e}")
# 6 cond=2.91e+07 forward=2.29e-10 backward=4.53e-17
# 10 cond=3.54e+13 forward=7.44e-04 backward=1.52e-16
# 12 cond=3.85e+16 forward=2.20e-01 backward=1.20e-16
The backward error is at the level of in every case: the solver is doing its job, returning the exact solution of a system within rounding of the one given. The forward error grows with : at , and the bound comfortably covers the observed . At , and essentially no digits survive.
Rewriting the solver cannot help here; only better data can, such as a better-conditioned basis. That is exactly what happens in regression with nearly collinear regressors, or a polynomial fit in the monomial basis on , whose Gram matrix is a Hilbert matrix.
Knowledge check
What is the relative condition number of at , and what does it imply?
Knowledge check
A linear solver returns x with relative residual 1e-16, but x is wrong in the third digit. What is the most accurate diagnosis?
Knowledge check
How many doubles lie in the interval [1, 2)?
Key takeaways
- A normal double is ; within each binade there are doubles spaced apart. , .
- Basic operations obey , . Relative errors add under and ; under they are amplified by .
- belongs to the problem: you lose about digits whatever you do.
- Backward error belongs to the algorithm; backward stable means . Forward error backward error.
- Diagnose a bad answer by computing both: large means reformulate the problem, large backward error means change the algorithm.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).