2.4. One computation, three perspectives#
In Lecture 1 we built the “pyramid of trust”: numerical experiment, symbolic computation, computation with a certificate, and formal proof (§1.4). Now we will apply this yardstick to floating-point arithmetic and take a single computation through three perspectives:
computation in
float: fast, but with no information whatsoever about the error;verification in exact arithmetic: every
floatnumber is rational, so the same expression for the same data can be computed with fractions, and the error can be measured exactly;guarantee: a theorem bounding the error, proved once for all data, or interval arithmetic, which for specific data gives an interval that is guaranteed to contain the result.
Our example is the polynomial \(p(x) = (x - 1)^7\), written in the expanded form \(x^7 - 7x^6 + 21x^5 - 35x^4 + 35x^3 - 21x^2 + 7x - 1\) and evaluated by Horner’s scheme near the root \(x = 1\). We ask the simplest possible question: what is the sign of \(p(x)\)? We know the answer in advance, \(\operatorname{sgn} p(x) = \operatorname{sgn}(x - 1)\), so it is easy to assess each of the perspectives. The same question about the sign of an expression was behind Rump’s example and Richardson’s theorem in Lecture 1.
For all three perspectives, Fraction numbers, NumPy, Matplotlib, and mpmath with its iv module
(interval arithmetic) are enough:
from fractions import Fraction
import numpy as np
import matplotlib.pyplot as plt
import mpmath
from mpmath import iv
2.4.1. Computation: Horner’s scheme in float#
Horner’s scheme computes \(a_n x^{n} + \dots + a_1 x + a_0\) as \((\dots((a_n x + a_{n-1})x + a_{n-2})\dots)x + a_0\), that is, with \(n\) multiplications and \(n\) additions. With it we compute \(p(x)\) at \(801\) equally spaced points of the interval \([0.98, 1.02]\):
COEFFS = [1, -7, 21, -35, 35, -21, 7, -1] # (x - 1)**7, highest power first
def horner(coeffs, x):
w = 0 * x # zero of the same type as x
for a in coeffs:
w = w * x + a
return w
xs = [float(t) for t in np.linspace(0.98, 1.02, 801)]
p_float = [horner(COEFFS, x) for x in xs]
wrong_sign = sum((w > 0) != (x > 1) for w, x in zip(p_float, xs) if x != 1)
print("points with a wrong sign of p(x) in float:", wrong_sign, "of", len(xs))
points with a wrong sign of p(x) in float: 156 of 801
At one point in five, the computed sign is wrong, and the program gives no warning at all. The plot shows what is going on:
exact_curve = [(x - 1)**7 for x in xs] # in float, only for the plot
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3))
for ax, (lo, hi) in ((ax1, (0.98, 1.02)), (ax2, (0.99, 1.01))):
ax.plot(xs, p_float, ".", ms=2.5, color="#d97706", label="Horner in float")
ax.plot(xs, exact_curve, color="#4f46e5", lw=1.5, label=r"$(x-1)^7$")
ax.set_xlim(lo, hi)
ax.set_xlabel("$x$")
ax.grid(alpha=0.3)
ax2.set_ylim(-2e-14, 2e-14)
ax1.legend(fontsize=8)
fig.tight_layout()
plt.show()
In the left plot, far from one, the float values lie on the curve \((x-1)^7\). The right plot is
a close-up: near the root the true values are smaller than \(10^{-14}\), while the computed ones form
a cloud of noise a few times \(10^{-15}\) wide. The noise comes from cancellation: the terms
\(a_i x^{i}\) are of order \(35\), and their sum is close to zero.
2.4.2. Verification: the same computation with fractions#
Every float number is a rational number, and Fraction(x) returns it without any rounding. The
function horner with an argument of type Fraction therefore computes the exact value of
\(p(x)\) at the same point at which float computed it. We can measure the error of each
computation, not just estimate it:
p_exact = [horner(COEFFS, Fraction(x)) for x in xs]
assert all(q == (Fraction(x) - 1)**7 for q, x in zip(p_exact, xs))
errors = [abs(Fraction(w) - q) for w, q in zip(p_float, p_exact)]
print("largest error of the float computation:", float(max(errors)))
print("exact signs agree with sgn(x - 1):",
all((q > 0) == (x > 1) for q, x in zip(p_exact, xs) if x != 1))
q = p_exact[3]
print("size of one exact value: numerator",
q.numerator.bit_length(), "bits, denominator", q.denominator.bit_length())
largest error of the float computation: 5.489891252315439e-15
exact signs agree with sgn(x - 1): True
size of one exact value: numerator 332 bits, denominator 372
The verification confirms that the computation with fractions gives exactly \((x-1)^7\), and it
measures the largest error of the computation in float: about \(5.5\cdot10^{-15}\). This is
complete knowledge about these \(801\) points. It has two limitations, however. First, cost: a single
value is a fraction whose numerator and denominator are several hundred bits long, and in longer
computations the fractions grow further. Second, reach: rational arithmetic covers only the four
operations. We cannot compute values such as \(\sqrt2\), \(e^{x}\), or \(\sin x\) exactly with
fractions.
2.4.3. Guarantee 1: an error bound as a theorem#
The lemma on the product of factors \((1 + \delta_i)\) from the previous section is enough to bound the error of Horner’s scheme for all polynomials and all data at once.
Theorem (error of Horner’s scheme)
Let \(p(x) = \sum_{i=0}^{n} a_i x^{i}\) have coefficients that are machine numbers, let \(x \in \F\), \(2nu < 1\), and let \(\hat p(x)\) denote the result of Horner’s scheme in floating-point arithmetic (without overflow or underflow). Then
Proof. The scheme computes \(q_n = a_n\) and \(q_i = \fl\bigl(\fl(q_{i+1} x) + a_i\bigr) = \bigl(q_{i+1}x(1 + \varepsilon_i) + a_i\bigr)(1 + \delta_i)\) for \(i = n-1, \dots, 0\), where \(|\varepsilon_i|, |\delta_i| \le u\) by the error model. Unrolling the recurrence, we get \(\hat p(x) = q_0 = \sum_{i=0}^{n} a_i x^{i} (1 + \theta^{(i)})\), where \(1 + \theta^{(i)}\) is a product of \(2i+1\) factors of the form \(1 + \delta\) for \(i < n\), and of \(2n\) factors for \(i = n\). By the lemma, \(|\theta^{(i)}| \le \gamma_{2n}\), so \(|\hat p(x) - p(x)| = \bigl|\sum_i a_i x^{i}\theta^{(i)}\bigr| \le \gamma_{2n}\sum_i|a_i||x|^{i}\). \(\blacksquare\) (N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM 2002, ch. 5.)
The theorem gives more than a bound: a certificate of the sign. If \(|\hat p(x)| > \gamma_{2n}\sum|a_i||x|^{i}\), then \(p(x)\) has the same sign as \(\hat p(x)\), because the error is smaller than the value. Let us check the theorem at our points (we compute the bound exactly, with fractions, so that the bound itself carries no error) and count at how many points it gives a certificate:
u = Fraction(1, 2**53)
gamma14 = 14 * u / (1 - 14 * u) # n = 7, hence gamma_{2n}
def error_bound(x):
X = abs(Fraction(x))
return gamma14 * sum(abs(a) * X**(7 - i) for i, a in enumerate(COEFFS))
violations = certificates = 0
closest = None
for x, w, q in zip(xs, p_float, p_exact):
B = error_bound(x)
violations += abs(Fraction(w) - q) > B
if abs(Fraction(w)) > B:
certificates += 1
if closest is None or abs(x - 1) < closest:
closest = abs(x - 1)
print("bound at the point x = 1:", float(error_bound(1.0)))
print("points where the error exceeds the bound:", violations)
print("points with the sign confirmed by the theorem:", certificates,
f"(for |x - 1| >= {closest:.5f})")
bound at the point x = 1: 1.9895196601282835e-13
points where the error exceeds the bound: 0
points with the sign confirmed by the theorem: 187 (for |x - 1| >= 0.01525)
The theorem did not fail at any point, and at \(187\) points it gives a proof of the sign. Closer to one it is silent: the bound there is about \(2\cdot10^{-13}\), and the values \(|p(x)|\) are smaller. The bound is more than thirty times larger than the largest error measured earlier. This is the price of a theorem that has to cover the worst possible combination of roundings.
2.4.4. Guarantee 2: interval arithmetic#
The second way of obtaining a guarantee does not require a theorem about a specific algorithm. Instead of a number, we store an interval that is guaranteed to contain it, and we perform every operation on intervals.
Definition (interval arithmetic)
For intervals \(X = [a, b]\) and \(Y = [c, d]\) and an operation \(\circ \in \{+, -, \cdot, /\}\) (for division, \(0 \notin Y\)), we set \(X \circ Y = \{x \circ y : x \in X,\ y \in Y\}\); for example, \(X + Y = [a + c,\ b + d]\) and \(X \cdot Y = [\min S, \max S]\) for \(S = \{ac, ad, bc, bd\}\). The endpoints of the result are rounded outward: the left one toward \(-\infty\), the right one toward \(+\infty\). Then the computed interval always contains the exact result (the inclusion property).
The module mpmath.iv implements this arithmetic with a given number of significand bits; we set
\(53\), as many as in float. The function horner works unchanged on intervals as well. Let us
compare two formulas for the same polynomial: the expanded form (Horner’s scheme) and the product
form \((x-1)^7\):
iv.prec = 53
def interval(I):
"""Interval endpoints to 3 significant digits (for printing only)."""
a, b = mpmath.mpf(I.a), mpmath.mpf(I.b)
return f"[{mpmath.nstr(a, 3)}, {mpmath.nstr(b, 3)}]"
print(f"{'x':>6} {'Horner in intervals':>24} {'contains 0':>10}"
f" {'product form':>22}")
for x in (1.001, 1.005, 1.01, 1.02):
P = horner(COEFFS, iv.mpf(x))
R = (iv.mpf(x) - 1)**7
print(f"{x:>6} {interval(P):>24} {str(0 in P):>10} {interval(R):>22}")
x Horner in intervals contains 0 product form
1.001 [-7.33e-15, 6.22e-15] True [1.0e-21, 1.0e-21]
1.005 [-3.77e-15, 9.77e-15] True [7.81e-17, 7.81e-17]
1.01 [3.55e-15, 1.71e-14] False [1.0e-14, 1.0e-14]
1.02 [1.27e-12, 1.29e-12] False [1.28e-12, 1.28e-12]
The interval from Horner’s scheme is wide, because interval arithmetic does not know that the same number \(x\) occurs in every step, and it assumes the worst possible combination of the endpoints. This is the so-called dependency problem; the simplest example is \(X - X\), which for \(X = [1, 2]\) gives \([-1, 1]\) rather than \([0, 0]\). For \(x = 1.001\) and \(x = 1.005\) the interval contains zero, so the computation honestly answers “I don’t know.” For \(x = 1.01\) the interval already lies to the right of zero, and this is a proof that \(p(1.01) > 0\). The product form contains \(x\) only once and gives very narrow intervals. Let us count at how many points of the grid each formula confirms the sign:
horner_iv = product_iv = 0
closest_iv = None
for x in xs:
if 0 not in horner(COEFFS, iv.mpf(x)):
horner_iv += 1
if closest_iv is None or abs(x - 1) < closest_iv:
closest_iv = abs(x - 1)
product_iv += 0 not in (iv.mpf(x) - 1)**7
print("sign confirmed — Horner in intervals:", horner_iv,
f"(for |x - 1| >= {closest_iv:.5f})")
print("sign confirmed — product form: ", product_iv, "of", len(xs))
sign confirmed — Horner in intervals: 432 (for |x - 1| >= 0.00885)
sign confirmed — product form: 800 of 801
Interval arithmetic with Horner’s scheme confirms the sign at \(432\) points, more than twice as many
as the theorem, because it adapts to the specific data. The product form confirms the sign
everywhere except at the single point \(x = 1\), where \(p(x) = 0\) (there the interval is zero, so it
“contains 0”). The guarantee is only as good as the formula we give it, but it never lies: an
interval can be too wide, but never false. Here we trust only the correct implementation of
directed rounding in mpmath.iv.
This honesty is most valuable where float errs the most. Let us compute Muller’s sequence from
the previous section with intervals:
a, b = iv.mpf(2), iv.mpf(-4)
for n in range(2, 15):
a, b = b, 111 - 1130 / b + 3000 / (a * b)
if n in (5, 10, 12, 13, 14):
width = mpmath.nstr(mpmath.mpf(b.delta), 2)
print(f"n = {n:2}: u_n in {interval(b):15} width {width}")
n = 5: u_n in [7.15, 7.15] width 5.6e-12
n = 10: u_n in [6.27, 6.27] width 0.00031
n = 12: u_n in [5.91, 6.45] width 0.54
n = 13: u_n in [-5.58, 17.5] width 23.0
n = 14: u_n in [-inf, +inf] width +inf
The interval grows with every step. For \(n = 13\) it contains both \(6\) and negative numbers, and for
\(n = 14\) division by an interval containing zero gives the whole set \([-\infty, +\infty]\). Interval
arithmetic does not know the limit of the sequence, but neither does it claim, as float does,
that the limit is \(100\). This is the difference between “I don’t know” and a confident but wrong
answer.
2.4.5. Three perspectives — a comparison#
Let us collect the results for the \(801\) points of the interval \([0.98, 1.02]\):
Perspective |
Tool |
What we know about the sign of \(p(x)\) |
What we trust |
|---|---|---|---|
computation |
Horner in |
a result at every point, wrong at \(156\) points, without a warning |
nothing — without an error analysis the result guarantees nothing |
verification |
Horner with |
the exact value and the exact error of |
a simple implementation of fractions; works only for rational operations |
guarantee: theorem |
the bound \(\gamma_{2n}\sum\lvert a_i\rvert\lvert x\rvert^{i}\) |
the sign proved at \(187\) points, for all data at once |
the proof of the theorem and the correct-rounding rule |
guarantee: intervals |
|
the sign proved at \(432\) (Horner) or \(800\) points (product) |
the implementation of directed rounding |
We copied the numbers in the table from the outputs of the cells above. Proofs of such theorems about floating-point arithmetic can also be checked by computer. The Flocq library for the Rocq proof assistant (formerly Coq) contains a formalized theory of floating-point numbers (S. Boldo, G. Melquiond, Flocq: A Unified Library for Proving Floating-Point Algorithms in Coq, ARITH 2011), and the history of formal proofs of hardware correctness, starting from the Pentium FDIV bug, is described in the deep dive, part 2, §8.
2.4.6. Summary#
A computation in
floatgives a result without any information about the error: near a root of a polynomial, even the sign can be wrong.Verification in exact arithmetic measures the error exactly, but only for selected data, only for rational operations, and at the cost of large numbers.
A theorem on the error (e.g., \(|\hat p - p| \le \gamma_{2n}\sum|a_i||x|^{i}\) for Horner’s scheme) covers all data at once and gives a certificate of the sign wherever the value exceeds the bound.
Interval arithmetic gives a guarantee for specific data, also for transcendental functions. It can be overly cautious (the dependency problem), but it never lies.
2.4.7. Exercises#
★ Repeat the experiment from this section for the polynomial \((x - 2)^9\) in expanded form on the interval \([1.95, 2.05]\): count the points with the wrong sign and the points at which the theorem on Horner’s scheme confirms the sign.
★ Compute the expressions \(X - X\) and \(X \cdot X - X^2\) for \(X = [1, 2]\) in
mpmath.iv. Explain the results and give a formula for \(X^2\) that yields the narrowest interval.★★ Derive from the theorem on Horner’s scheme the distance \(|x - 1|\) from which on the sign of \(p(x) = (x-1)^7\) is confirmed, and compare the result with the value printed in this section.
★★ Prove the inclusion property for addition and multiplication of intervals with outward rounding of the endpoints.
★★★ The compensated Horner scheme: in each step, the errors of the multiplication and of the addition are machine numbers, which the functions
two_prodandtwo_sumfrom the deep dive, part 2, §2, compute exactly. Sum these errors with a second Horner scheme and add the sum to the result. At how many points of the grid from this section is the sign now correct? Explain why the correction helps.