Part 2. Implementation: tricks and subtleties#

The standard says what the result must be. This part shows what that looks like in practice: in the bits, in the compiler, in Python, and in math libraries — and which tricks follow from it.

In §1 we read the bits of a number as an integer and derive the fast inverse square root from this. In §2 we show that the rounding error of an addition or a multiplication is itself a machine number, and we build compensated summation algorithms on this fact. In §3 we turn to the FMA operation, in §4 to situations in which the same program gives different results, in §5 to how Python handles exceptions, NaN, negative zero, and the printing of numbers, and in §6 to the elementary functions, on which the standard imposes no binding requirements. In §7 we collect formulas that are robust to rounding, and §8 gives a brief history. The first cell defines helper functions: bity and z_bitow convert between a float and its 64 bits, and losowa draws random numbers from a wide range of magnitudes.

import math, platform, random, shutil, statistics, struct, subprocess, tempfile, warnings
from fractions import Fraction
from pathlib import Path
import mpmath
import numpy as np
import matplotlib.pyplot as plt

random.seed(754)

def bity(x):
    """64 bity liczby float odczytane jako liczba całkowita bez znaku."""
    return struct.unpack('<Q', struct.pack('<d', x))[0]

def z_bitow(n):
    """Liczba float o podanych 64 bitach."""
    return struct.unpack('<d', struct.pack('<Q', n))[0]

def losowa(zakres=40):
    """Losowa liczba float: mantysa z [1, 2), wykładnik od -zakres do zakres, losowy znak."""
    return random.uniform(1, 2) * 2.0**random.randint(-zakres, zakres) * random.choice((1, -1))

1. Bits as an integer#

In Part 1 we saw that for the zero \(+0\) and the positive numbers, the order of the numbers is the order of their bits. Some simple tricks follow from this.

The next number is “+1”, and 0.1 + 0.2 is the neighbor of 0.3#

Since the order of the numbers is the order of their bits, the next machine number after a positive number \(x\) is obtained by adding \(1\) to its bits. The distance between two numbers of the same sign, measured in ulps, is simply the difference of their bits:

print("z_bitow(bity(1.0) + 1) =", z_bitow(bity(1.0) + 1), "= nextafter(1, 2):",
      z_bitow(bity(1.0) + 1) == math.nextafter(1.0, 2.0))
print("odległość 0.1 + 0.2 od 0.3:", bity(0.1 + 0.2) - bity(0.3), "ulp")
print("sąsiedzi 0.3:", math.nextafter(0.3, 0), "|", 0.3, "|", math.nextafter(0.3, 1))
z_bitow(bity(1.0) + 1) = 1.0000000000000002 = nextafter(1, 2): True
odległość 0.1 + 0.2 od 0.3: 1 ulp
sąsiedzi 0.3: 0.29999999999999993 | 0.3 | 0.30000000000000004

0.1 + 0.2 is not just “some” wrong number: it is the next machine number after 0.3. The test suites of numerical libraries measure the agreement of results in exactly this way — in ulps, that is, by the difference of the bit patterns.

The bits are almost a logarithm#

If \(x=2^E(1+m)\) with \(0\le m<1\) is a positive normal number, then the bits of \(x\) are \(2^{52}(E+1023)+2^{52}m\), so

\[ \frac{\texttt{bity}(x)}{2^{52}}-1023=E+m\approx E+\log_2(1+m)=\log_2x . \]

Reading the bits as an integer gives a piecewise linear approximation of the base-2 logarithm. The largest error is \(\max_{0\le m<1}\bigl(\log_2(1+m)-m\bigr)\approx0.0861\), attained at \(m=1/\ln2-1\). Let us plot \(\log_2x\) and the rescaled bits for \(x\in[1/16,16]\) and compare the largest measured difference with this value:

xs = np.geomspace(1 / 16, 16, 4000)
przyblizenie = np.array([bity(float(x)) / 2**52 - 1023 for x in xs])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3.2))
ax1.plot(xs, np.log2(xs), lw=2, label=r"$\log_2 x$")
ax1.plot(xs, przyblizenie, lw=1.2, ls="--", label=r"$\mathtt{bity}(x)/2^{52}-1023$")
ax1.legend()
ax2.plot(xs, np.log2(xs) - przyblizenie, color="C2")
ax2.set_title("różnica", fontsize=10)
for ax in (ax1, ax2):
    ax.set_xscale("log", base=2)
    ax.set_xlabel("$x$")
    ax.grid(alpha=0.3)
fig.tight_layout()
plt.show()
m = 1 / math.log(2) - 1
print("największa różnica na wykresie:", max(np.log2(xs) - przyblizenie),
      "  teoretycznie:", math.log2(1 + m) - m)
../_images/96f6ee51428792956fbdb369b697cd7580b7f0203c7310331a5e7f3ad84332db.png
największa różnica na wykresie: 0.08607132740461654   teoretycznie: 0.0860713320559342

The largest measured difference agrees with the theoretical value \(0.0861\). At powers of two (\(m=0\)) the approximation is exact, and the largest error occurs roughly in the middle of each interval \([2^E,2^{E+1})\).

Fast inverse square root (Quake III Arena, 1999)#

Since the bits are almost a logarithm, \(\log_2(1/\sqrt x)=-\tfrac12\log_2x\) translates into the bits: \(i_y\approx K-i_x/2\) for a suitable constant \(K\), where \(i_x\) and \(i_y\) are the bits of \(x\) and of \(y\approx1/\sqrt x\) read as integers (here 32-bit ones). The game Quake III Arena (id Software, 1999; the source code was released in 2005) computed \(1/\sqrt x\) this way when normalizing vectors for graphics: in the binary32 format, with the constant 0x5f3759df and one step of Newton’s method for \(f(y)=1/y^2-x\). Here the Newton step \(y\leftarrow y-f(y)/f'(y)\) takes a division-free form:

\[ y \leftarrow y-\frac{y^{-2}-x}{-2y^{-3}} = y\Bigl(\frac32-\frac{x}{2}\,y^2\Bigr). \]

If \(y=(1+e)/\sqrt x\), then after the step the relative error is \(-\tfrac32e^2-\tfrac12e^3\) — Newton’s method converges quadratically. Let us see how this works for the number \(2\) and on the whole interval \([1,4)\):

def odwrotny_pierwiastek(x, kroki_newtona=1):
    """1/√x sztuczką z Quake III (binary32)."""
    x = np.float32(x)
    i = np.array([x]).view(np.int32)[0]            # bity liczby x jako int32
    i = np.int32(0x5f3759df - (int(i) >> 1))       # „połowa logarytmu” ze zmienionym znakiem
    y = np.array([i]).view(np.float32)[0]          # te same bity jako float32
    for _ in range(kroki_newtona):
        y = y * (np.float32(1.5) - np.float32(0.5) * x * y * y)
    return y

print("x = 2:", odwrotny_pierwiastek(2.0, 0), "→ po kroku Newtona", odwrotny_pierwiastek(2.0),
      "  dokładnie:", 1 / math.sqrt(2))
siatka = np.linspace(1, 4, 30001)    # wystarczy [1, 4): x·4 daje dokładnie wynik / 2
for kroki in (0, 1, 2):
    blad = max(abs(float(odwrotny_pierwiastek(v, kroki)) * math.sqrt(v) - 1) for v in siatka)
    print(f"kroki Newtona: {kroki}   największy błąd względny: {blad:.4%}")
x = 2: 0.7162151 → po kroku Newtona 0.70693004   dokładnie: 0.7071067811865475
kroki Newtona: 0   największy błąd względny: 3.4375%
kroki Newtona: 1   największy błąd względny: 0.1752%
kroki Newtona: 2   największy błąd względny: 0.0005%

After one Newton step the error does not exceed \(0.18\%\) — more than enough for graphics, and with no division and no square root. The numbers agree with the convergence analysis: \(\tfrac32\cdot(3.44\%)^2\approx0.18\%\), and \(\tfrac32\cdot(0.18\%)^2\approx0.0005\%\). An analysis of the constant was given by C. Lomont (2003); today processors have dedicated instructions for this. In the original, the bits were read through a pointer cast, which in C is formally undefined behavior; in Python we use a NumPy array view (view).

2. The rounding error is a machine number#

So far we have only estimated the rounding error. It turns out, however, that the error of a single addition or multiplication is itself a machine number and can be computed exactly with ordinary operations. Double-length arithmetic and compensated summation rest on this fact.

TwoSum: the exact error of addition#

Theorem (Møller 1965, Knuth 1969)

If we round to nearest, then for machine numbers \(a,b\) (barring overflow) the six operations of the function two_sum yield \(s=\fl(a+b)\) and a machine number \(e\) such that \(a+b=s+e\) exactly.

The theorem says two things. First, with rounding to nearest, the error of an addition, \(a+b-\fl(a+b)\), is always a machine number — no extra precision is needed to store it. Second, this error can be computed with ordinary operations. In the code, bb = s - a is the part of \(b\) that “made it” into the sum, s - bb is the part of \(a\) that made it into the sum, and the two differences in the last line are what was lost from \(a\) and from \(b\). The proof that all the operations except the first are exact relies on Sterbenz’s lemma (Knuth, TAOCP, vol. 2, §4.2.2). When it is known that \(|a|\ge|b|\), three operations suffice (Dekker’s FastTwoSum).

Let us test the theorem on \(50{,}000\) random pairs and on two well-known examples:

def two_sum(a, b):
    s = a + b
    bb = s - a
    e = (a - (s - bb)) + (b - bb)
    return s, e

zle = sum(Fraction(a) + Fraction(b) != sum(map(Fraction, two_sum(a, b)))
          for a, b in ((losowa(), losowa()) for _ in range(50_000)))
print("niedokładnych rozkładów na 50 000:", zle)
print("two_sum(0.1, 0.2) =", two_sum(0.1, 0.2))
print("two_sum(1e16, 1.0) =", two_sum(1e16, 1.0))
niedokładnych rozkładów na 50 000: 0
two_sum(0.1, 0.2) = (0.30000000000000004, -2.7755575615628914e-17)
two_sum(1e16, 1.0) = (1e+16, 1.0)

The error of the addition \(0.1+0.2\) is exactly \(-2^{-55}\approx-2.78\cdot10^{-17}\). In \(10^{16}+1\) the whole 1 was lost — and two_sum recovers it.

TwoProduct: the exact error of multiplication#

A product also splits exactly: \(a\cdot b=p+e\), where \(p=\fl(ab)\) and \(e\) is a machine number (provided there is no underflow). Without hardware FMA this is done by Dekker’s method (1971). Veltkamp’s splitting writes each number as a sum \(a=a_h+a_l\) in which both parts have at most \(26\) significant bits. The product of two such parts has at most \(52\) bits, so it fits into the \(53\)-bit significand and is computed exactly; from the four exact partial products we assemble the error \(e\).

C = 2.0**27 + 1          # 134217729

def rozszczep(a):
    t = C * a
    hi = t - (t - a)
    return hi, a - hi

def two_prod(a, b):
    p = a * b
    ah, al = rozszczep(a)
    bh, bl = rozszczep(b)
    e = ((ah * bh - p) + ah * bl + al * bh) + al * bl
    return p, e

zle = sum(Fraction(a) * Fraction(b) != sum(map(Fraction, two_prod(a, b)))
          for a, b in ((losowa(), losowa()) for _ in range(50_000)))
print("niedokładnych rozkładów na 50 000:", zle, "  two_prod(0.1, 0.1) =", two_prod(0.1, 0.1))
niedokładnych rozkładów na 50 000: 0   two_prod(0.1, 0.1) = (0.010000000000000002, -8.326672684688674e-19)

All \(50{,}000\) decompositions are exact, and the error of the product \(0.1\cdot0.1\) is about \(-8.33\cdot10^{-19}\) (in §3 we will compute it with a single FMA operation). From such pairs of numbers one builds “double-length” arithmetic (double-double): a pair \((p,e)\) with \(|e|\le\tfrac12\ulp(p)\) represents the number \(p+e\) with a precision of about \(2\cdot53=106\) bits, without any special hardware.

Compensated summation#

A sum of \(n\) numbers can be computed in several ways, which come with different guarantees (N. J. Higham, Accuracy and Stability of Numerical Algorithms, Chapter 4). Neglecting terms of higher order in \(u\) (we assume that \(nu\ll1\)), the bounds on the absolute error are as follows:

  • the plain loop has an error of at most \((n-1)\,u\sum_i|x_i|\);

  • pairwise summation (a tree of additions), at most about \(u\log_2 n\sum_i|x_i|\);

  • Kahan’s compensated summation, at most \(2u\sum_i|x_i|\), independently of \(n\).

The functions below implement the loop and the methods of Kahan and Neumaier; we compare them with the ready-made sum, np.sum, and math.fsum on a sum in which the plain loop loses all the small terms:

def petla(xs):
    s = 0.0
    for x in xs:
        s += x
    return s

def kahan(xs):
    s = c = 0.0                      # c: utracona część poprzednich dodawań
    for x in xs:
        y = x - c
        t = s + y
        c = (t - s) - y
        s = t
    return s

def neumaier(xs):
    s = c = 0.0
    for x in xs:
        t = s + x
        c += (s - t) + x if abs(s) >= abs(x) else (x - t) + s
        s = t
    return s + c

def porownaj(xs, dokladnie):
    for nazwa, f in (("pętla", petla), ("Kahan", kahan), ("Neumaier", neumaier),
                     ("sum()", sum), ("np.sum", np.sum), ("math.fsum", math.fsum)):
        w = float(f(xs))
        print(f"{nazwa:10} {w!r:24} błąd: {Fraction(w) - dokladnie}")

porownaj([1e16] + [1.0] * 1000, Fraction(10**16 + 1000))
pętla      1e+16                    błąd: -1000
Kahan      1.0000000000001e+16      błąd: 0
Neumaier   1.0000000000001e+16      błąd: 0
sum()      1.0000000000001e+16      błąd: 0
np.sum     1.0000000000000988e+16   błąd: -12
math.fsum  1.0000000000001e+16      błąd: 0

The plain loop (petla) loses every single 1: \(\ulp(10^{16})=2\), and \(10^{16}+1\) is a tie, broken to even, that is, to \(10^{16}\). Kahan (1965) carries the lost part \(c\) over to the next step. NumPy sums pairwise, so the error grows like \(\log n\) rather than like \(n\) — here it loses \(12\). Since Python 3.12, sum uses Neumaier’s method (Lecture 1, §1.4), and math.fsum (Shewchuk’s algorithm) returns the correctly rounded exact sum. How does Neumaier’s method differ from Kahan’s? This is best seen on a sum in which a term much larger than the running sum appears:

porownaj([1.0, 1e100, 1.0, -1e100], Fraction(2))
pętla      0.0                      błąd: -2
Kahan      0.0                      błąd: -2
Neumaier   2.0                      błąd: 0
sum()      2.0                      błąd: 0
np.sum     0.0                      błąd: -2
math.fsum  2.0                      błąd: 0

Kahan’s method assumes that the running sum is larger in absolute value than the number being added. When a number larger than the sum arrives (\(10^{100}\)), the correction is lost. Neumaier (1974) handles both cases — and it is his version that Python’s sum uses. Pairwise summation does not help: np.sum also gives \(0\), because both ones are lost before \(10^{100}\) and \(-10^{100}\) cancel.

3. FMA: one rounding instead of two#

The FMA operation (fused multiply-add, in the standard since 2008) computes \(\fl(a\cdot b+c)\) with a single rounding. Almost all modern processors have it; Python has had math.fma since version 3.13. Here we emulate it exactly with rational arithmetic:

def fma(a, b, c):
    """fl(a*b + c) z jednym zaokrągleniem."""
    return float(Fraction(a) * Fraction(b) + Fraction(c))

print("0.1*10 - 1 =", 0.1 * 10 - 1, "   fma(0.1, 10, -1) =", fma(0.1, 10.0, -1.0),
      "= 2**-54:", fma(0.1, 10.0, -1.0) == 2.0**-54)
p = 0.1 * 0.1
print("błąd iloczynu 0,1·0,1:  fma →", fma(0.1, 0.1, -p), "  two_prod →", two_prod(0.1, 0.1)[1])
0.1*10 - 1 = 0.0    fma(0.1, 10, -1) = 5.551115123125783e-17 = 2**-54: True
błąd iloczynu 0,1·0,1:  fma → -8.326672684688674e-19   two_prod → -8.326672684688674e-19

The exact product of the machine number 0.1 and \(10\) is \(1+2^{-54}\), which rounds to exactly \(1\), so ordinary operations hide the error; FMA reveals it: \(2^{-54}\). With FMA, the exact error of a product takes a single instruction, \(e=\mathrm{fma}(a,b,-p)\); the second line of the output shows that it gives the same result as two_prod from §2.

The compiler fuses operations: \(\sqrt{a\cdot a-a\cdot a}=\mathrm{NaN}\)#

The C standard allows the compiler to replace \(a\cdot b+c\) within a single expression by an FMA (FP_CONTRACT). Clang does so by default (-ffp-contract=on), GCC even more boldly (-ffp-contract=fast). Then a*a - a*a is computed as \(\mathrm{fma}\bigl(a,a,-\fl(a\cdot a)\bigr)\), that is, as the rounding error of the product, not as zero:

for a in (0.1, 0.3, 0.7):
    e = fma(a, a, -(a * a))
    print(f"a = {a}:  a*a - a*a z FMA = {e!r:>24}   sqrt: {math.sqrt(e) if e >= 0 else 'NaN'}")
a = 0.1:  a*a - a*a z FMA =   -8.326672684688674e-19   sqrt: NaN
a = 0.3:  a*a - a*a z FMA =  -3.3306690738754695e-18   sqrt: NaN
a = 0.7:  a*a - a*a z FMA =    2.220446049250315e-18   sqrt: 1.4901161193847663e-09

For \(a=0.1\) and \(a=0.3\) the error of the product is negative, so there is a negative number under the square root, and the result is NaN; for \(a=0.7\) the error is positive, and instead of zero we get about \(1.5\cdot10^{-9}\). Let us now run a real C program, compiled twice: with the default settings and with operation fusing turned off (the cell runs the clang compiler if it is available on the system). The program receives \(a=0.1\) only at run time (atof(argv[1])), so that the compiler cannot compute the result in advance:

def uruchom_c(zrodlo, flagi, *argumenty, przedrostek=()):
    """Kompiluje program w C (clang) i uruchamia go; zwraca wypisany tekst."""
    if shutil.which("clang") is None:
        return "(brak kompilatora clang)"
    with tempfile.TemporaryDirectory() as kat:
        plik, exe = Path(kat) / "p.c", Path(kat) / "p"
        plik.write_text(zrodlo)
        kompilacja = subprocess.run(["clang", "-O2", *flagi, str(plik), "-o", str(exe), "-lm"],
                                    capture_output=True, text=True)
        if kompilacja.returncode != 0:
            return "(nie udało się skompilować)"
        try:
            wynik = subprocess.run([*przedrostek, str(exe), *argumenty],
                                   capture_output=True, text=True, timeout=30)
        except OSError:
            return "(nie udało się uruchomić)"
        return wynik.stdout.strip() or "(nie udało się uruchomić)"

PROGRAM_FMA = r"""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char **argv) {
    double a = atof(argv[1]);           /* a = 0.1 podane w czasie działania */
    double d = a * a - a * a;
    printf("a*a - a*a = %g,  sqrt = %g\n", d, sqrt(d));
    return 0;
}
"""
print("procesor:", platform.machine())
for flagi in ([], ["-ffp-contract=off"]):
    opis = " ".join(flagi) or "(ustawienia domyślne)"
    print(f"clang {opis:22}", uruchom_c(PROGRAM_FMA, flagi, "0.1"))
procesor: arm64
clang (ustawienia domyślne)  a*a - a*a = -8.32667e-19,  sqrt = nan
clang -ffp-contract=off      a*a - a*a = 0,  sqrt = 0

On a processor with an FMA instruction (e.g., ARM), the result depends on the compiler flag: with the default settings the square root of “zero” is NaN. An expression that is mathematically identically zero depends, in practice, on the compiler.

4. Same program, different results#

The rule from Part 1 guarantees the same bits only when the program performs the same operations in the same format. In practice this condition is easy to violate: intermediate results are sometimes stored in a different precision, and for some operations the standard does not specify the outcome at all. Here are three such situations.

Double rounding#

The x87 coprocessor (x86 processors before SSE2 became widespread) computed in 80-bit registers with a 64-bit significand and rounded to binary64 only when storing to memory. Two roundings are not the same as one. To show this, we need a reference rounding to an arbitrary number of bits. The function zaokraglij(q, p) determines the exponent \(e\) from the condition \(2^e\le q<2^{e+1}\), scales \(q\) to the interval \([2^{p-1},2^p)\), divides it by \(1\) with remainder, and breaks ties to even — exactly as the standard prescribes:

def zaokraglij(q, p):
    """Fraction q > 0 zaokrąglona do p bitów mantysy (do najbliższej, remis do parzystej)."""
    e = q.numerator.bit_length() - q.denominator.bit_length()
    if Fraction(2)**e > q:
        e -= 1                                     # teraz 2**e <= q < 2**(e + 1)
    skala = Fraction(2)**(p - 1 - e)
    n, r = divmod(q * skala, 1)
    if r > Fraction(1, 2) or (r == Fraction(1, 2) and n % 2 == 1):
        n += 1
    return n / skala

b = 2.0**-53 + 2.0**-70                             # liczba maszynowa
dokladnie = 1 + Fraction(b)
print("jedno zaokrąglenie (53 bity):     ", float(zaokraglij(dokladnie, 53)), "  Python:", 1 + b)
print("najpierw do 64 bitów, potem do 53:", float(zaokraglij(zaokraglij(dokladnie, 64), 53)))
jedno zaokrąglenie (53 bity):      1.0000000000000002   Python: 1.0000000000000002
najpierw do 64 bitów, potem do 53: 1.0

\(1+b\) lies just above the midpoint between \(1\) and \(1+2^{-52}\), so the correct result is \(1+2^{-52}\). Rounding to 64 bits loses \(2^{-70}\) and turns the number into an exact tie, which the second rounding breaks to even — downward, to \(1\). Modern processors (x86-64 with SSE2, ARM) compute in binary64 directly, but old 32-bit code and mixed precision still produce such discrepancies (Monniaux 2008).

float32 in the middle of a computation#

The second source of discrepancies is mixed precision. A number stored once in the binary32 format and then carried over to binary64 retains the binary32 rounding error — of relative order \(2^{-24}\), not \(2^{-53}\):

x32 = np.float32(0.1)
print("float32:", x32, "  → z powrotem jako float64:", float(x32),
      "  równe 0.1?", float(x32) == 0.1)
float32: 0.1   → z powrotem jako float64: 0.10000000149011612   równe 0.1? False

Graphics cards and machine-learning libraries often compute in binary32 or bfloat16. The number “0.1” stored once in binary32 and read back as float64 is \(0.10000000149011612\). In binary32 it looks innocent (0.1), because that is its shortest representation in that format — which is why such an error in a data pipeline is easy to miss.

NaN converted to an integer#

When NaN or a number that is too large is converted to an integer, the standard requires the invalid exception to be signaled, but it does not say which integer to return; in C this is undefined behavior. Processors handle it differently (the x86-64 version runs on Apple computers with ARM processors thanks to the Rosetta 2 translation layer):

PROGRAM_NAN = r"""
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char **argv) {
    volatile double nan_ = NAN * atof(argv[1]), duza = 1e300;
    printf("(long long)NaN = %lld,  (long long)1e300 = %lld\n",
           (long long)nan_, (long long)duza);
    return 0;
}
"""
print("ARM64: ", uruchom_c(PROGRAM_NAN, ["-arch", "arm64"], "1"))
print("x86-64:", uruchom_c(PROGRAM_NAN, ["-arch", "x86_64"], "1",
                           przedrostek=["arch", "-x86_64"]))
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    print("NumPy na tym komputerze:", np.array([np.nan, 1e300]).astype(np.int64))
ARM64:  (long long)NaN = 0,  (long long)1e300 = 9223372036854775807
x86-64: (long long)NaN = -9223372036854775808,  (long long)1e300 = -9223372036854775808
NumPy na tym komputerze: [                  0 9223372036854775807]

For every invalid argument, x86-64 processors return the “integer indefinite” value \(-2^{63}\); ARM64 saturates the result to the representable range and converts NaN to \(0\). So the same program gives different numbers on different computers. NumPy converts numbers the same way as the C program, so on this computer (ARM64) it gives the same results.

The conversion that destroyed a rocket

On June 4, 1996, 37 seconds after engine ignition, the Ariane 5 rocket (Flight 501) lost control and was destroyed. The software of the inertial reference system converted a 64-bit floating-point number (the quantity BH, horizontal bias, related to the horizontal velocity) into a 16-bit signed integer. The value exceeded 32,767, the conversion was not protected, and the resulting exception shut down both inertial reference systems (report of the Inquiry Board chaired by J. L. Lions, ESA 1996).

5. Python and the standard#

Python computes with binary64 numbers using the processor’s hardware operations, so the results of individual operations conform to the standard. It does, however, have its own rules for handling exceptional situations, for comparisons with NaN, for printing negative zero, and for converting numbers to text.

Exceptions instead of special values#

According to the standard, computations do not stop by default: the result receives a special value, and the processor raises a flag (Part 1, §4). Python chose otherwise and in many cases raises an exception. Let us compare it with NumPy on the same expressions:

def sprobuj(f):
    try:
        return str(f())
    except Exception as e:
        return type(e).__name__

PRZYPADKI = [
    ("1.0 / 0.0", lambda: 1.0 / 0.0, lambda: np.float64(1.0) / 0.0),
    ("0.0 / 0.0", lambda: 0.0 / 0.0, lambda: np.float64(0.0) / 0.0),
    ("math.sqrt(-1.0)", lambda: math.sqrt(-1.0), lambda: np.sqrt(np.float64(-1.0))),
    ("math.log(0.0)", lambda: math.log(0.0), lambda: np.log(np.float64(0.0))),
    ("math.exp(1000.0)", lambda: math.exp(1000.0), lambda: np.exp(np.float64(1000.0))),
    ("10.0 ** 400", lambda: 10.0**400, lambda: np.float64(10.0)**400),
    ("1e308 * 10", lambda: 1e308 * 10, lambda: np.float64(1e308) * 10),
    ("math.inf - math.inf", lambda: math.inf - math.inf, lambda: np.float64(np.inf) - np.inf),
]
print(f"{'wyrażenie':22} {'Python':20} NumPy")
with np.errstate(all="ignore"):
    for opis, f, g in PRZYPADKI:
        print(f"{opis:22} {sprobuj(f):20} {sprobuj(g)}")
wyrażenie              Python               NumPy
1.0 / 0.0              ZeroDivisionError    inf
0.0 / 0.0              ZeroDivisionError    nan
math.sqrt(-1.0)        ValueError           nan
math.log(0.0)          ValueError           -inf
math.exp(1000.0)       OverflowError        inf
10.0 ** 400            OverflowError        inf
1e308 * 10             inf                  inf
math.inf - math.inf    nan                  nan

On division by zero and on domain errors, Python raises an exception instead of returning \(\infty\) or NaN — a deliberate design decision, but an inconsistent one: overflow in multiplication gives inf, overflow in math.exp and in exponentiation gives OverflowError, and math.inf - math.inf gives nan without any exception. NumPy sticks to the standard’s default behavior: it returns special values and reports raised flags only with a RuntimeWarning, which we silenced in the cell with np.errstate(all="ignore").

NaN in lists#

A value that is not equal to itself breaks the assumptions of many algorithms. Let us see how Python’s containers, the max function, sorting, and the median behave with NaN:

x = float("nan")
print("x == x:", x == x, "  [x] == [x]:", [x] == [x], "  x in [x]:", x in [x],
      "  float('nan') in [float('nan')]:", float("nan") in [float("nan")])
print("słownik z dwoma kluczami NaN:", {float("nan"): 1, float("nan"): 2})
print("max([nan, 1, 2]) =", max([x, 1.0, 2.0]), "  max([1, nan, 2]) =", max([1.0, x, 2.0]))
for dane in ([3.0, x, 1.0, 2.0], [x, 3.0, 1.0, 2.0], [3.0, 1.0, x, 2.0]):
    print(f"sorted({dane}) = {sorted(dane)}   mediana: {statistics.median(dane)}")
print("NumPy:", np.sort([3.0, x, 1.0, 2.0]), "  np.median:", np.median([3.0, x, 1.0, 2.0]),
      "  np.nanmedian:", np.nanmedian([3.0, x, 1.0, 2.0]))
x == x: False   [x] == [x]: True   x in [x]: True   float('nan') in [float('nan')]: False
słownik z dwoma kluczami NaN: {nan: 1, nan: 2}
max([nan, 1, 2]) = nan   max([1, nan, 2]) = 2.0
sorted([3.0, nan, 1.0, 2.0]) = [3.0, nan, 1.0, 2.0]   mediana: nan
sorted([nan, 3.0, 1.0, 2.0]) = [nan, 1.0, 2.0, 3.0]   mediana: 1.5
sorted([3.0, 1.0, nan, 2.0]) = [1.0, 2.0, 3.0, nan]   mediana: 2.5
NumPy: [ 1.  2.  3. nan]   np.median: nan   np.nanmedian: 2.0

Python’s containers compare object identity first and only then values (the language reference, §6.10.1). That is why the same NaN object “is equal” to itself inside a list, even though x == x is false. Two different NaN objects are neither the same object nor equal, so a dictionary treats them as two keys. The max function starts with the first element and replaces it only with a larger element; a comparison with NaN always gives false, so a NaN at the beginning of the list “wins,” while a NaN further down the list is skipped. Sorting assumes a total order, and every comparison with NaN gives false — so the result depends on where the NaN was. As a consequence, statistics.median of the same four numbers gives nan, \(1.5\), or \(2.5\). NumPy behaves consistently: NaN goes to the end, the median of data containing NaN is NaN, and the np.nan… functions skip missing values.

Signed zero in printed output#

Negative zero is equal to the ordinary zero, but it is printed with a minus sign — and this can be visible to the user:

pomiary = [-0.04, 0.03, -0.2]
print([f"{t:.1f} °C" for t in pomiary])
print("round(-0.04, 1) =", round(-0.04, 1), "  max(0.0, -0.0) =", max(0.0, -0.0),
      "  max(-0.0, 0.0) =", max(-0.0, 0.0))
['-0.0 °C', '0.0 °C', '-0.2 °C']
round(-0.04, 1) = -0.0   max(0.0, -0.0) = 0.0   max(-0.0, 0.0) = -0.0

A weather station will display “−0.0 °C”: rounding \(-0.04\) to one decimal place gives \(-0.0\). When its arguments are equal, the max function returns the first of them, so the result depends on the order, even though 0.0 == -0.0.

The shortest decimal representation#

How should a float be printed in decimal? Its exact value has dozens of digits (for very large and very small numbers, even hundreds), and a representation that is too short does not allow the number to be recovered. Python follows the rule: print the shortest decimal representation that reads back as the same number. Let us check this property on \(50{,}000\) random strings of \(64\) bits:

skonczone = powroty = najwiecej_cyfr = 0
for _ in range(50_000):
    x = z_bitow(random.getrandbits(64))       # losowe 64 bity — także liczby subnormalne
    if math.isfinite(x):
        skonczone += 1
        r = repr(x)
        powroty += float(r) == x
        cyfry = r.split("e")[0].lstrip("-").replace(".", "").strip("0")
        najwiecej_cyfr = max(najwiecej_cyfr, len(cyfry))
print(f"zapisów repr, które wracają do tej samej liczby: {powroty} / {skonczone}")
print("najwięcej cyfr znaczących w repr:", najwiecej_cyfr)
print(repr(0.1), "|", f"{0.1:.17g}", "|", f"{0.1:.25f}")
zapisów repr, które wracają do tej samej liczby: 49980 / 49980
najwięcej cyfr znaczących w repr: 17
0.1 | 0.10000000000000001 | 0.1000000000000000055511151

All finite numbers came back unchanged; the remaining \(20\) of the \(50{,}000\) strings are infinities and NaNs (exponent \(e=2047\), about \(1/2048\) of all strings). Since Python 3.1, repr prints the shortest decimal string that reads back as the same number (David Gay’s algorithm). For binary64, no more than 17 significant digits are ever needed. That is why 0.1 looks innocent, even though the exact value of this number has 55 digits after the decimal point.

6. Elementary functions: the standard only recommends#

The correct-rounding rule covers only the operations \(+,-,\cdot,/\), \(\sqrt{\ }\), FMA, and conversions (Part 1, §1). For \(\sin\), \(\exp\), \(\log\), the standard (since 2008) merely recommends correct rounding; libraries usually promise an error below one or a few ulps.

An exact argument, a hard result: \(\sin(10^{22})\)#

\(10^{22}\) is a machine number (Part 1), so \(\sin(10^{22})\) is well defined. To compute it, however, one needs \(10^{22}\bmod 2\pi\) — and for that, \(\pi\) to many digits:

mpmath.mp.dps = 60
x = mpmath.mpf(10)**22
print("math.sin(1e22) =", math.sin(1e22), "  dokładnie:", mpmath.nstr(mpmath.sin(x), 20))
for cyfry in (20, 30, 38):
    pi_c = mpmath.mpf(mpmath.nstr(mpmath.pi, cyfry))          # π z tyloma cyframi znaczącymi
    reszta = x - mpmath.nint(x / (2 * pi_c)) * 2 * pi_c
    print(f"redukcja z π o {cyfry} cyfrach:  sin =", float(mpmath.sin(reszta)))
math.sin(1e22) = -0.8522008497671888   dokładnie: -0.85220084976718880177
redukcja z π o 20 cyfrach:  sin = -0.5222274046123522
redukcja z π o 30 cyfrach:  sin = -0.8522008505951075
redukcja z π o 38 cyfrach:  sin = -0.8522008497671888

With \(\pi\) to 20 digits the result is wrong already in the first digit; almost 40 digits are needed. This follows from a simple computation: \(10^{22}/(2\pi)\approx1.6\cdot10^{21}\), so in the reduction the error of the approximation of \(\pi\) is multiplied by a number of order \(10^{21}\), and for the remainder to still have \(16\) correct digits, \(\pi\) must have about \(21+16\) of them. The system library does this correctly. The FSIN instruction of the x87 coprocessor reduced the argument using an approximation of \(\pi\) with only 66 bits, so near multiples of \(\pi\) (already for \(x\approx\pi\)) its error was many orders of magnitude larger than Intel’s documentation promised (B. Dawson, 2014).

A good function, a bad argument#

The opposite situation: the library computes correctly, but the argument already carries an error. Near \(10^{15}\) the gap between machine numbers is \(0.125\), so the number \(10^{15}+0.3\) cannot be represented exactly:

x = 1e15 + 0.3
print("1e15 + 0.3 zapisane jako", repr(x), "  (ulp(1e15) =", math.ulp(1e15), ")")
print("math.sin(x)               =", math.sin(x))
prawdziwy = mpmath.sin(mpmath.mpf(10)**15 + mpmath.mpf(3) / 10)
print("sin(10^15 + 0,3) dokładnie =", mpmath.nstr(prawdziwy, 16))
1e15 + 0.3 zapisane jako 1000000000000000.2   (ulp(1e15) = 0.125 )
math.sin(x)               = 0.7046250079258086
sin(10^15 + 0,3) dokładnie = 0.6682801974911698

The function correctly computed the sine of the number it received, namely \(10^{15}+0.25\) (the printed 1000000000000000.2 is the shortest representation of this number, §5). The error arose earlier, when the argument was stored. The same mechanism spoiled the float64 computations in §4 of the worked example for Richardson’s theorem.

How often does the library round incorrectly?#

We compare functions from the math module with correctly rounded values (mpmath, 200 bits):

mpmath.mp.prec = 200

def dokladna(v):
    """Wartość mpmath zamieniona dokładnie na Fraction."""
    znak = -1 if v < 0 else 1
    m, e = abs(v).man_exp
    return znak * Fraction(m) * Fraction(2)**e

FUNKCJE = [("exp", math.exp, mpmath.exp, (-700, 700)),
           ("log", math.log, mpmath.log, (1e-3, 1e3)),
           ("sin", math.sin, mpmath.sin, (-100, 100)),
           ("tan", math.tan, mpmath.tan, (-100, 100)),
           ("cbrt", math.cbrt, mpmath.cbrt, (1e-3, 1e10)),
           ("gamma", math.gamma, mpmath.gamma, (0.1, 170))]
N = 2000
print(f"{'funkcja':8} {'niepoprawnie zaokrąglonych':>27} {'największy błąd':>16}")
for nazwa, f, g, (a, b) in FUNKCJE:
    zle, najwiekszy = 0, 0.0
    for _ in range(N):
        x = random.uniform(a, b)
        q, w = dokladna(g(mpmath.mpf(x))), f(x)
        zle += w != float(q)
        najwiekszy = max(najwiekszy, float(abs(Fraction(w) - q) / Fraction(math.ulp(w))))
    print(f"{nazwa:8} {zle:>20} / {N}  {najwiekszy:>12.3f} ulp")
funkcja   niepoprawnie zaokrąglonych  największy błąd
exp                         2 / 2000         0.500 ulp
log                         1 / 2000         0.500 ulp
sin                        81 / 2000         0.714 ulp
tan                       839 / 2000         2.484 ulp
cbrt                      159 / 2000         0.702 ulp
gamma                    1225 / 2000         4.792 ulp

For the basic operations in Part 1 there was not a single mismatch. Here the number of incorrectly rounded results depends on the function: from isolated cases (exp, log) to more than half of the samples (gamma), and the largest error reaches almost \(5\) ulps. The numbers come from the library of the system on which this page was built; on another computer they may differ. Correct rounding of transcendental functions is hard: it is not known in advance how many digits must be computed to decide the rounding (the “Table Maker’s Dilemma”). The CORE-MATH project provides such correctly rounded implementations.

7. Tricks: formulas robust to rounding#

Many mathematically correct formulas lose accuracy in machine arithmetic or leave the range of representable numbers. What usually helps is to transform the formula or to use a library function that avoids the dangerous operation. We show four examples; in the last one, Muller’s sequence, no finite precision helps.

\((1+1/n)^n\)#

The sequence \((1+1/n)^n\) tends to \(e\). Let us compute it for \(n\) from \(10\) to \(10^{17}\) directly and with a second, mathematically equivalent formula, and compare the errors of the two methods in a plot:

ks = np.arange(1, 17.01, 0.25)
naiwnie, z_log1p = [], []
for k in ks:
    n = 10.0**k
    naiwnie.append(abs((1 + 1 / n)**n - math.e))
    z_log1p.append(abs(math.exp(n * math.log1p(1 / n)) - math.e))
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.loglog(10**ks, naiwnie, "o-", ms=3, label=r"$(1+1/n)^n$")
ax.loglog(10**ks, np.where(np.array(z_log1p) > 0, z_log1p, np.nan), "s-", ms=3,
          label=r"$\exp(n\cdot\mathrm{log1p}(1/n))$")
ax.set_xlabel("$n$")
ax.set_ylabel("$|$wynik $- e|$")
ax.legend()
ax.grid(alpha=0.3)
plt.show()
for k in (8, 12, 15, 16):
    n = 10.0**k
    print(f"n = 1e{k}:  (1 + 1/n)**n = {(1 + 1 / n)**n!r:20}  exp(n·log1p(1/n)) = "
          f"{math.exp(n * math.log1p(1 / n))!r}")
../_images/33e729aacf2fd74ad030ca6b41bea7c94208520008567962e9211e43657ecd03.png
n = 1e8:  (1 + 1/n)**n = 2.7182817983473577    exp(n·log1p(1/n)) = 2.7182818148676366
n = 1e12:  (1 + 1/n)**n = 2.7185234960372378    exp(n·log1p(1/n)) = 2.718281828457686
n = 1e15:  (1 + 1/n)**n = 3.035035206549262     exp(n·log1p(1/n)) = 2.7182818284590438
n = 1e16:  (1 + 1/n)**n = 1.0                   exp(n·log1p(1/n)) = 2.718281828459045

Mathematically, \((1+1/n)^n\to e\). Numerically, everything agrees up to \(n\approx10^{8}\); after that the error grows, and for \(n=10^{16}\) the result is exactly \(1\): \(1+10^{-16}\) rounds to \(1\). The reason: \(\fl(1+1/n)=(1+1/n)(1+\delta)\) with \(|\delta|\le u\), and \(\bigl((1+1/n)(1+\delta)\bigr)^n\approx e\cdot e^{n\delta}\) — raising to the power \(n\) multiplies the relative error by roughly \(n\). For \(n=10^8\) the bound gives \(10^8u\approx1.1\cdot10^{-8}\), and the actual rounding error here is about \(6\cdot10^{-9}\). The error of the approximation itself contributes almost as much: \((1+1/n)^n\approx e\bigl(1-\tfrac1{2n}\bigr)\), that is, \(5\cdot10^{-9}\) in relative terms. Together this gives a relative error of about \(1.1\cdot10^{-8}\), visible in the printout. The remedy is the formula \((1+1/n)^n=\exp\bigl(n\log(1+1/n)\bigr)\), in which math.log1p(x) computes \(\log(1+x)\) with a relative error of order \(u\) even for very small \(x\), because it does not form \(1+x\). Its twin, math.expm1(x), computes \(e^x-1\) just as accurately. In the plot, the curve for the formula with log1p decreases like \(e/(2n)\): this is the error of the approximation \((1+1/n)^n\approx e\) itself, since rounding contributes only a relative error of order \(10^{-16}\) here. The value \(3.035\) for \(n=10^{15}\) is the example from Part 1, §5: \(\fl(1+10^{-15})=1+1.11\cdot10^{-15}\), so the direct formula in fact computes \(e^{1.1102\ldots}\approx3.035\).

hypot#

The length of a vector, \(\sqrt{x^2+y^2}\), computed directly can leave the range of representable numbers even though the result itself lies well within it: for \(x=10^{200}\) the square \(10^{400}\) exceeds the range and gives \(\infty\), and for \(x=10^{-200}\) the square vanishes in underflow. The function math.hypot avoids this:

for x in (1e200, 1e-200):
    wprost = math.sqrt(x * x + x * x)
    print(f"x = {x}:  sqrt(x*x + x*x) = {wprost!r:22}  hypot(x, x) = {math.hypot(x, x)!r}")
print("hypot(inf, nan) =", math.hypot(math.inf, math.nan),
      "  sqrt(inf**2 + nan**2) =", math.sqrt(math.inf**2 + math.nan**2))
x = 1e+200:  sqrt(x*x + x*x) = inf                     hypot(x, x) = 1.414213562373095e+200
x = 1e-200:  sqrt(x*x + x*x) = 0.0                     hypot(x, x) = 1.414213562373095e-200
hypot(inf, nan) = inf   sqrt(inf**2 + nan**2) = nan

hypot scales its arguments, so there is neither overflow nor underflow in the intermediate computations. And one more subtlety: the standard (since 2008, §9.2.1) specifies the result \(\mathrm{hypot}(\pm\infty,\mathrm{NaN})=+\infty\) — whatever the other coordinate may be, the length of the vector is infinite. NaN does not always propagate.

Numerical derivative: the best \(h\approx\sqrt\varepsilon\)#

The difference quotient \(\bigl(f(x+h)-f(x)\bigr)/h\) approximates \(f'(x)\) more and more accurately as \(h\) decreases — but only in exact arithmetic. Let us examine the error for \(f=\sin\) at the point \(x=1\) and for \(h\) from \(10^{-1}\) to \(10^{-16}\):

hs = 10.0**-np.arange(1, 16.01, 0.25)
bledy = [abs((math.sin(1 + h) - math.sin(1)) / h - math.cos(1)) for h in hs]
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.loglog(hs, bledy, "o-", ms=3)
ax.axvline(math.sqrt(2**-52), color="crimson", ls="--", lw=1, label=r"$h=\sqrt{\varepsilon}$")
ax.set_xlabel("$h$")
ax.set_ylabel("błąd ilorazu różnicowego")
ax.legend()
ax.grid(alpha=0.3)
plt.show()
i = int(np.argmin(bledy))
print(f"najmniejszy błąd {bledy[i]:.1e} dla h = {hs[i]:.1e};"
      f"  sqrt(eps) = {math.sqrt(2**-52):.1e}")
../_images/3ddd70345277dc27533479929b0e6e8815320f807f5932309d7cdfe888e72863.png
najmniejszy błąd 2.5e-09 dla h = 5.6e-09;  sqrt(eps) = 1.5e-08

The quotient \(\bigl(\sin(1+h)-\sin1\bigr)/h\) has two errors. The truncation error, about \(\tfrac h2|\sin''(1)|\), decreases with \(h\). The rounding error: the numerator carries an error of order \(\varepsilon\), and division by \(h\) amplifies it, so this error grows like \(\varepsilon/h\). The two are of the same order when \(h\) is of order \(\sqrt\varepsilon\approx1.5\cdot10^{-8}\) — and that is where, up to a small factor, the minimum in the plot lies. A smaller \(h\) only does harm: for \(h=10^{-16}\) we have \(\fl(1+h)=1\), the quotient is zero, and the error equals \(\cos1\approx0.54\).

Muller’s sequence: rounding picks a different limit#

Muller’s sequence is a classic test of arithmetic: the recurrence is simple, and the computation in float gives a stable but wrong result.

\[ u_0=2,\qquad u_1=-4,\qquad u_{n+1}=111-\frac{1130}{u_n}+\frac{3000}{u_n\,u_{n-1}} . \]

We compute it side by side in float and exactly, with Fraction numbers:

u, v = 2.0, -4.0
U, V = Fraction(2), Fraction(-4)
print(f"{'n':>3} {'float':>22} {'dokładnie':>22}")
for n in range(2, 31):
    u, v = v, 111 - 1130 / v + 3000 / (u * v)
    U, V = V, 111 - 1130 / V + 3000 / (U * V)
    if n in (2, 5, 10, 15, 16, 20, 25, 30):
        print(f"{n:3} {v!r:>22} {float(V)!r:>22}")
  n                  float              dokładnie
  2                   18.5                   18.5
  5      7.154414480975333      7.154414480975249
 10      6.274438662728116      6.274438598216328
 15      6.166086559598099      6.094739439333681
 16      7.235021165534931      6.077722304847243
 20       99.8985692661829      6.036031881081857
 25      99.99999991932181      6.014174914550819
 30      99.99999999999993       6.00564868877142

In exact arithmetic the sequence tends to \(6\); in float, to \(100\). The substitution \(u_n=y_{n+1}/y_n\) gives the linear recurrence \(y_{n+1}=111y_n-1130y_{n-1}+3000y_{n-2}\) with characteristic roots \(5\), \(6\), and \(100\), so

\[ u_n=\frac{\alpha\,100^{n+1}+\beta\,6^{n+1}+\gamma\,5^{n+1}}{\alpha\,100^{n}+\beta\,6^{n}+\gamma\,5^{n}} . \]

The initial values give exactly \(\alpha=0\) (and \(\beta=-3\), \(\gamma=4\)), hence the limit \(6\). The first rounding turns \(\alpha\) into a tiny nonzero number, and \(100^n\) eventually wins. No finite precision helps here — only exact computation or a proof that \(\alpha=0\).

8. History: from a processor bug to formal proof#

Pentium FDIV (1994)

Thomas Nicely of Lynchburg College was computing Brun’s constant — the sum of the reciprocals of the twin primes — and noticed that the Pentium processor divided some numbers incorrectly. The lookup table of the SRT division algorithm was missing 5 of its 1066 entries. In January 1995 Intel took a charge of 475 million dollars. The industry responded with formal proofs: J S. Moore, T. Lynch, and M. Kaufmann proved in the ACL2 system that the division microcode of the AMD K5 processor returns the correctly rounded quotient, and J. Harrison at Intel verified floating-point algorithms in the HOL Light system. It is the same path — computation, verification, proof — as in Lecture 1.

9. Questions and exercises#

  1. Why is the constant in Veltkamp’s splitting equal to \(2^{27}+1\)? How many significant bits do the parts \(a_h\) (hi) and \(a_l\) (a - hi) have, and why?

  2. For which \(a\) is the value \(\mathrm{fma}\bigl(a,a,-\fl(a\cdot a)\bigr)\) negative? What does its sign depend on?

  3. Explain why statistics.median gives three different results for the same list containing NaN. How can you guard against this?

  4. Find the smallest \(n=2^k\) and the smallest \(n=10^k\) for which (1 + 1/n)**n gives exactly \(1\).

  5. Why does \(\mathrm{hypot}(\infty,\mathrm{NaN})=\infty\) make sense, while \(\infty+\mathrm{NaN}=\infty\) would not?

Computer exercises for this part — FastTwoSum, a counterexample for Neumaier summation, Muller’s sequence in mpmath, and the fast inverse square root in binary64 — are in the problem set Lab 3 (Parts C and D, and exercise Z2 for independent practice).

References. O. Møller, Quasi double-precision in floating point addition, BIT 5 (1965), 37–50 · T. J. Dekker, A floating-point technique for extending the available precision, Numerische Mathematik 18 (1971), 224–242 · W. Kahan, Further remarks on reducing truncation errors, Communications of the ACM 8 (1965), 40 · A. Neumaier, Rundungsfehleranalyse einiger Verfahren zur Summation endlicher Summen, ZAMM 54 (1974), 39–51 · J. R. Shewchuk, Adaptive precision floating-point arithmetic and fast robust geometric predicates, Discrete & Computational Geometry 18 (1997), 305–363 · C. Lomont, Fast inverse square root, technical report, 2003 · D. Monniaux, The pitfalls of verifying floating-point computations, ACM TOPLAS 30 (2008), no. 3 · J.-M. Muller et al., Handbook of Floating-Point Arithmetic, 2nd ed., Birkhäuser 2018 · Clang: the -ffp-contract option · Python: Floating Point Arithmetic: Issues and Limitations · Python: Value comparisons (§6.10.1) · B. Dawson, Intel Underestimates Error Bounds by 1.3 quintillion, 2014 · The CORE-MATH project · J. L. Lions et al., Ariane 5 Flight 501 Failure — Report by the Inquiry Board, ESA 1996 · T. Coe, T. Mathisen, C. Moler, V. Pratt, Computational aspects of the Pentium affair, IEEE Computational Science & Engineering 2 (1995), 18–30 · J S. Moore, T. Lynch, M. Kaufmann, A mechanically checked proof of the AMD5K86 floating-point division program, IEEE Transactions on Computers 47 (1998), 913–926 · J. Harrison, Formal verification of floating point trigonometric functions, FMCAD 2000, LNCS 1954, 217–233.