Skip to content
LeetQuant
E04 Numerical Methods

E04 · Numerical Methods · Lesson 1 of 4

Floating Point

The IEEE 754 double bit by bit, ulps and the standard model of rounding, how relative errors propagate through each operation, and the split between a problem's condition number and an algorithm's backward stability.

18 min

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:

forward error  ≲  κ×backward error.\text{forward error} \;\lesssim\; \kappa \times \text{backward error}.

The layout of a double

A 64-bit double stores a sign bit ss, an 11-bit biased exponent ee and a 52-bit fraction ff:

Exponent field eeMeaning
1≤e≤20461 \le e \le 2046normal: (−1)s×(1+f/252)×2e−1023(-1)^s \times (1 + f/2^{52}) \times 2^{e - 1023}
e=0e = 0zero (f=0f = 0) or subnormal: (−1)s×(f/252)×2−1022(-1)^s \times (f/2^{52}) \times 2^{-1022}
e=2047e = 2047±∞\pm\infty (f=0f = 0) or NaN (f≠0f \ne 0)

Inside one binade [2k,2k+1)[2^k, 2^{k+1}) there are exactly 2522^{52} equally spaced doubles, 2k−522^{k-52} apart. That spacing is the unit in the last place, ulp⁡(x)\operatorname{ulp}(x). Two constants follow:

  • Machine epsilon ε=ulp⁡(1)=2−52≈2.22×10−16\varepsilon = \operatorname{ulp}(1) = 2^{-52} \approx 2.22 \times 10^{-16}.
  • Unit roundoff u=ε/2=2−53≈1.11×10−16u = \varepsilon/2 = 2^{-53} \approx 1.11 \times 10^{-16}, the largest relative error of rounding to nearest. For any real xx in the normal range, fl⁡(x)=x(1+δ)\operatorname{fl}(x) = x(1 + \delta) with ∣δ∣≤u|\delta| \le u.

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 10810^8?

Show 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.1 has biased exponent 0x3FB =1019= 1019, so the scale is 2−42^{-4}, and the significand is 1.6000…1.6000\ldots: 0.1=1.6×2−40.1 = 1.6 \times 2^{-4}. The fraction 999...9A is the repeating binary pattern of 0.60.6, rounded up in the last hex digit, which is why the stored value is slightly above 0.10.1.
  • -2.5 is −1.25×21-1.25 \times 2^{1}: sign bit 1, exponent 10241024, fraction 0.250.25, which is exact.
  • 0.1 + 0.2 and 0.3 are adjacent doubles: one ulp apart.
  • 100∈[26,27)100 \in [2^6, 2^7), so ulp⁡(100)=26−52=2−46≈1.42×10−14\operatorname{ulp}(100) = 2^{6 - 52} = 2^{-46} \approx 1.42 \times 10^{-14}. 108∈[226,227)10^8 \in [2^{26}, 2^{27}), so ulp⁡(108)=2−26≈1.49×10−8\operatorname{ulp}(10^8) = 2^{-26} \approx 1.49 \times 10^{-8}. A notional of 10810^8 held as a double cannot represent changes below about 1.5×10−81.5 \times 10^{-8}; the relative precision is the same everywhere, the absolute precision is not.

The standard model and how errors propagate

IEEE 754 requires +,−,×,÷+, -, \times, \div and  \sqrt{\ } to be correctly rounded: the result is the exact result rounded once. So for these operations

fl⁡(x∘y)=(x∘y)(1+δ),∣δ∣≤u.\operatorname{fl}(x \circ y) = (x \circ y)(1 + \delta), \qquad |\delta| \le u .

(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: x^=x(1+α)\hat x = x(1 + \alpha), y^=y(1+β)\hat y = y(1 + \beta). To first order in α,β,δ\alpha, \beta, \delta:

  • Multiplication and division: x^y^(1+δ)=xy(1+α+β+δ)\hat x \hat y (1 + \delta) = xy(1 + \alpha + \beta + \delta). Relative errors add. A product of nn rounded factors has relative error at most about nun u; it never blows up.
  • Addition and subtraction:
x^+y^=(x+y)(1+xα+yβx+y),∣xα+yβx+y∣≤∣x∣+∣y∣∣x+y∣max⁡(∣α∣,∣β∣).\hat x + \hat y = (x + y)\left(1 + \frac{x\alpha + y\beta}{x + y}\right), \qquad \left|\frac{x\alpha + y\beta}{x + y}\right| \le \frac{|x| + |y|}{|x + y|}\max(|\alpha|, |\beta|) .

The amplification factor (∣x∣+∣y∣)/∣x+y∣(|x| + |y|)/|x + y| is 1 when the signs agree and enormous when x≈−yx \approx -y. 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 s=∑i=1nxis = \sum_{i=1}^{n} x_i:

∣s^−s∣≤γn−1∑i=1n∣xi∣,γk=ku1−ku≈ku.|\hat s - s| \le \gamma_{n-1} \sum_{i=1}^{n} |x_i|, \qquad \gamma_k = \frac{k u}{1 - k u} \approx k u .

Note the ∑∣xi∣\sum |x_i|: the bound is relative to the sum of magnitudes, not to ∣s∣|s|. Pairwise summation (what NumPy's sum does on contiguous float arrays) replaces γn−1\gamma_{n-1} by γ⌈log⁡2n⌉\gamma_{\lceil \log_2 n \rceil}.

Condition number: a property of the problem

The relative condition number of evaluating ff at xx measures how much a relative change in the input moves the output:

κf(x)=lim⁡Δ→0∣f(x+Δ)−f(x)∣/∣f(x)∣∣Δ∣/∣x∣=∣xf′(x)f(x)∣.\kappa_f(x) = \lim_{\Delta \to 0} \frac{|f(x + \Delta) - f(x)|/|f(x)|}{|\Delta|/|x|} = \left|\frac{x f'(x)}{f(x)}\right| .
f(x)f(x)κf(x)\kappa_f(x)Ill-conditioned when
x\sqrt x1/21/2never
exe^x∣x∣\lvert x \rvert∣x∣\lvert x \rvert large
ln⁡x\ln x1/∣ln⁡x∣1/\lvert \ln x \rvertx≈1x \approx 1
x−ax - a∣x∣/∣x−a∣\lvert x \rvert / \lvert x - a \rvertx≈ax \approx a
Ax=bAx = b (solve)κ(A)=∥A∥∥A−1∥\kappa(A) = \lVert A \rVert \lVert A^{-1} \rVertAA nearly singular

Since every input is rounded on entry, even a perfect algorithm suffers a relative error of about κu\kappa u. You lose roughly log⁡10κ\log_{10}\kappa significant digits, and no algorithm can get them back without changing the problem (more precision, or a reformulation such as passing x−1x - 1 instead of xx to a logarithm, which is what log1p does).

Backward error: a property of the algorithm

An algorithm returns y^\hat y instead of y=f(x)y = f(x). Its forward error is ∣y^−y∣/∣y∣|\hat y - y|/|y|. Its backward error is the smallest relative perturbation of the input that explains the output exactly:

η=min⁡{∣Δx∣∣x∣:y^=f(x+Δx)}.\eta = \min\left\{ \frac{|\Delta x|}{|x|} : \hat y = f(x + \Delta x) \right\} .

An algorithm is backward stable if η=O(u)\eta = O(u) for every input: it gives the exact answer to a slightly wrong question. Combining the definitions,

∣y^−y∣∣y∣≲κf(x) η.\frac{|\hat y - y|}{|y|} \lesssim \kappa_f(x)\, \eta .

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 ∥b−Ax^∥/(∥A∥∥x^∥)\lVert b - A\hat x \rVert / (\lVert A \rVert \lVert \hat x \rVert)). Backward stable in practice: summation, dot products, Gaussian elimination with partial pivoting, Householder QR, the SVD. Not backward stable: forming the normal equations X⊤Xβ=X⊤yX^\top X \beta = X^\top y for least squares, which squares the condition number (κ2(X⊤X)=κ2(X)2\kappa_2(X^\top X) = \kappa_2(X)^2) before solving anything; QR on XX itself avoids that.

Worked example

a well-conditioned problem, an unstable algorithm

Compute e−20e^{-20} by summing its Taylor series ∑n(−20)n/n!\sum_n (-20)^n/n! until the terms are negligible. The condition number of exe^x at x=−20x = -20 is only 20, so roughly 14 digits should be attainable. How many do you get, why, and what is the fix?

Show 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 x=−20x = -20: the naive sum is off by 200%.

Why. The terms alternate in sign and the largest are 2019/19!=2020/20!≈4.3×10720^{19}/19! = 20^{20}/20! \approx 4.3 \times 10^{7}. By the summation bound, the absolute error is of order u∑∣xi∣≈1.1×10−16×e20≈5×10−8u \sum |x_i| \approx 1.1 \times 10^{-16} \times e^{20} \approx 5 \times 10^{-8} in the worst case, and of order u×4.3×107≈5×10−9u \times 4.3 \times 10^{7} \approx 5 \times 10^{-9} from the largest terms alone. The answer is e−20≈2.06×10−9e^{-20} \approx 2.06 \times 10^{-9}, so the relative error is of order 1, exactly as observed. At x=−10x = -10 the same estimate gives u×2756/4.54×10−5≈7×10−9u \times 2756 / 4.54 \times 10^{-5} \approx 7 \times 10^{-9}, matching the observed 2×10−92 \times 10^{-9}.

The problem is fine (κ=20\kappa = 20); the algorithm has a huge backward error because it computes a tiny number as the difference of huge ones. This is the amplification factor (∣x∣+∣y∣)/∣x+y∣(|x| + |y|)/|x + y| at work, here about e20/e−20=e40e^{20}/e^{-20} = e^{40} in the worst case.

Fix. Sum the series for e+20e^{+20}, whose terms are all positive (amplification factor 1, relative error about nunu), and take the reciprocal, which is a single correctly rounded division. Relative error 4×10−164 \times 10^{-16}. 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 Hnx=bH_n x = b where HnH_n is the Hilbert matrix, (Hn)ij=1/(i+j−1)(H_n)_{ij} = 1/(i + j - 1), and b=Hn1b = H_n \mathbf 1, so the true solution is all ones. Use numpy.linalg.solve (LU with partial pivoting) for n=6,10,12n = 6, 10, 12. Report the condition number, the forward error and the backward error, and check the inequality between them.

Show 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 uu 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 κ\kappa: at n=10n = 10, κ≈3.5×1013\kappa \approx 3.5 \times 10^{13} and the bound κ η≈3.5×1013×1.5×10−16≈5×10−3\kappa\,\eta \approx 3.5 \times 10^{13} \times 1.5 \times 10^{-16} \approx 5 \times 10^{-3} comfortably covers the observed 7.4×10−47.4 \times 10^{-4}. At n=12n = 12, κ≈4×1016>1/u\kappa \approx 4 \times 10^{16} > 1/u 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 1,x,x2,…1, x, x^2, \ldots on [0,1][0, 1], whose Gram matrix is a Hilbert matrix.

Knowledge check

What is the relative condition number of f(x)=ln⁡xf(x) = \ln x at x=1.0001x = 1.0001, 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 (1+f/252)×2e−1023(1 + f/2^{52}) \times 2^{e - 1023}; within each binade there are 2522^{52} doubles spaced ulp⁡(x)=2k−52\operatorname{ulp}(x) = 2^{k - 52} apart. ε=2−52\varepsilon = 2^{-52}, u=2−53u = 2^{-53}.
  • Basic operations obey fl⁡(x∘y)=(x∘y)(1+δ)\operatorname{fl}(x \circ y) = (x \circ y)(1 + \delta), ∣δ∣≤u|\delta| \le u. Relative errors add under ×\times and ÷\div; under ±\pm they are amplified by (∣x∣+∣y∣)/∣x+y∣(|x| + |y|)/|x + y|.
  • κf(x)=∣xf′(x)/f(x)∣\kappa_f(x) = |x f'(x)/f(x)| belongs to the problem: you lose about log⁡10κ\log_{10}\kappa digits whatever you do.
  • Backward error belongs to the algorithm; backward stable means O(u)O(u). Forward error ≲κ×\lesssim \kappa \times backward error.
  • Diagnose a bad answer by computing both: large κ\kappa means reformulate the problem, large backward error means change the algorithm.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).