Part 1. The standard: what IEEE 754 promises#

Work on the standard lasted from 1977 to 1985, and its principal architect was William Kahan (1989 Turing Award, for his contributions to numerical analysis). Before that, every computer manufacturer did arithmetic its own way, and the same program gave different results on different machines. The 2008 revision added, among other things, the FMA operation, decimal formats, and the binary16 format; the 2019 revision made it more precise. This part describes what the standard guarantees — and what follows from these guarantees.

The plan is as follows. In §1 we state the correct-rounding rule, on which all of error analysis rests, and test it experimentally. In §2 we describe the format of the numbers and their distribution on the real line; in §3, the rounding modes; in §4, the special values: signed zero, infinities, NaN, and subnormal numbers. In §5 we derive the consequences: exact subtraction of nearby numbers (Sterbenz’s lemma) and the failure of associativity of addition. The first cell imports the required modules and defines the function bity, which shows the 64 bits of a float as a single integer:

import math, cmath, random, struct
from fractions import Fraction
from decimal import Decimal, localcontext, ROUND_HALF_UP, ROUND_HALF_EVEN
import mpmath
import numpy as np

random.seed(754)

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

1. One rule#

The correct-rounding rule

The result of addition, subtraction, multiplication, division, square root, the FMA operation (\(a\cdot b+c\)), and conversion is the exact mathematical result, rounded to a machine number according to the current rounding mode (by default: round to nearest, ties to even).

This single rule suffices for error analysis. Let \(\circ\) denote one of the operations \(+,-,\cdot,/\). If we round to nearest and the exact result \(x\circ y\) lies in the range of normal numbers, then

\[ \fl(x\circ y)=(x\circ y)(1+\delta),\qquad |\delta|\le u=2^{-53}, \]

where \(u\) is the unit roundoff and \(\varepsilon=2u=2^{-52}\) is the machine epsilon — the gap between \(1\) and the next machine number. The justification is short. If \(2^k\le|z|<2^{k+1}\) and \(z\) lies in the range of normal numbers, then adjacent machine numbers in this interval are \(2^{k-52}\) apart. Rounding to nearest therefore moves \(z\) by at most half of this gap: \(|\fl(z)-z|\le2^{k-53}\le2^{-53}|z|\). It suffices to take \(z=x\circ y\) and \(\delta=(\fl(z)-z)/z\). In the directed rounding modes (§3), rounding can move \(z\) by almost the whole gap, so in those modes \(|\delta|<\varepsilon\).

The rule can be tested experimentally. Fraction computes exactly, and float(Fraction(...)) rounds correctly, so we have a reference. We compare the machine’s results with it for random numbers from widely different ranges:

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

def pierwiastek_poprawny(a, s):
    """Czy s = fl(√a)? Dokładnie: √a leży nie dalej niż pół ulp od s."""
    h = Fraction(math.ulp(s)) / 2
    return (Fraction(s) - h)**2 <= a <= (Fraction(s) + h)**2

N = 50_000
bledy = {"+": 0, "·": 0, "/": 0, "√": 0}
for _ in range(N):
    x, y = losowa(), losowa()
    X, Y = Fraction(x), Fraction(y)
    bledy["+"] += x + y != float(X + Y)
    bledy["·"] += x * y != float(X * Y)
    bledy["/"] += x / y != float(X / Y)
    bledy["√"] += not pierwiastek_poprawny(abs(X), math.sqrt(abs(x)))
print(f"{N} losowych par; wyniki różne od poprawnie zaokrąglonych:", bledy)
50000 losowych par; wyniki różne od poprawnie zaokrąglonych: {'+': 0, '·': 0, '/': 0, '√': 0}

The function pierwiastek_poprawny does not need the exact value of \(\sqrt a\) (which is usually irrational): it suffices to check, in rational arithmetic, that \(\sqrt a\) lies between \(s-\tfrac12\ulp(s)\) and \(s+\tfrac12\ulp(s)\), that is, that \(a\) lies between the squares of these endpoints. When \(s\) is a power of two, the gap below \(s\) is half as large, so there the test is slightly too lenient; in random data this case practically never occurs.

There is not a single mismatch. For the four operations and the square root, the standard’s promise is a theorem that can be tested: every conforming machine must produce exactly the same bits. (In Part 2 we will see how a compiler can get around this promise.)

2. The format: three bit fields#

A binary64 number occupies 64 bits: the sign \(s\) (1 bit), the exponent \(e\) (11 bits), and the fractional part \(f\) of the significand (52 bits). For \(1\le e\le2046\)

\[ x=(-1)^s\cdot\bigl(1.f_1f_2\ldots f_{52}\bigr)_2\cdot2^{\,e-1023}. \]

The leading digit of the significand \((1.f_1\ldots f_{52})_2\) of a normal number is always 1, so it is not stored — the precision is \(p=53\) bits. Two exponent values are reserved: \(e=0\) encodes zero and the subnormal numbers \((-1)^s\cdot(0.f_1\ldots f_{52})_2\cdot2^{-1022}\) (zero is the case \(f=0\)), and \(e=2047\) encodes infinity (\(f=0\)) or NaN (\(f\ne0\)). The other formats have the same structure and differ only in the number of bits:

FORMATY = [  # nazwa, liczba bitów, precyzja p (z ukrytą jedynką), e_max
    ("binary16", 16, 11, 15),
    ("bfloat16", 16, 8, 127),
    ("binary32", 32, 24, 127),
    ("binary64", 64, 53, 1023),
    ("binary128", 128, 113, 16383),
]
dwa = mpmath.mpf(2)
print(f"{'format':9} {'bity':>4} {'p':>4} {'ε':>9} {'cyfry':>5} {'największa':>11} "
      f"{'najm. norm.':>11} {'najm. subn.':>11}")
for nazwa, n, p, emax in FORMATY:
    emin = 1 - emax
    eps, najw = dwa**(1 - p), (2 - dwa**(1 - p)) * dwa**emax
    norm, subn = dwa**emin, dwa**(emin - p + 1)
    print(f"{nazwa:9} {n:4} {p:4} {mpmath.nstr(eps, 3):>9} {p * math.log10(2):5.1f} "
          f"{mpmath.nstr(najw, 3):>11} {mpmath.nstr(norm, 3):>11} {mpmath.nstr(subn, 3):>11}")
format    bity    p         ε cyfry  największa najm. norm. najm. subn.
binary16    16   11  0.000977   3.3     6.55e+4      6.1e-5     5.96e-8
bfloat16    16    8   0.00781   2.4    3.39e+38    1.18e-38    9.18e-41
binary32    32   24   1.19e-7   7.2     3.4e+38    1.18e-38     1.4e-45
binary64    64   53  2.22e-16  16.0    1.8e+308   2.23e-308   4.94e-324
binary128  128  113  1.93e-34  34.0  1.19e+4932  3.36e-4932  6.48e-4966

The values in the table follow directly from the structure of a format with precision \(p\) and largest exponent \(e_{\max}\) (the smallest one is \(e_{\min}=1-e_{\max}\)):

  • \(\varepsilon=2^{1-p}\) — the gap between \(1\) and the next machine number;

  • the largest finite number is \((2-2^{1-p})\cdot2^{e_{\max}}\);

  • the smallest positive normal number is \(2^{e_{\min}}\), and the smallest positive subnormal number is \(2^{e_{\min}-p+1}\).

The column “cyfry” (digits) is \(p\log_{10}2\) — roughly the number of decimal digits that the significand carries. NumPy knows the binary16, binary32, and binary64 formats, so the table can be checked independently:

print(f"{'typ':8} {'ε':>9} {'największa':>11} {'najm. norm.':>11} {'najm. subn.':>11}")
for typ in (np.float16, np.float32, np.float64):
    fi = np.finfo(typ)
    print(f"{typ.__name__:8} {float(fi.eps):9.3g} {float(fi.max):11.3g} "
          f"{float(fi.smallest_normal):11.3g} {float(fi.smallest_subnormal):11.3g}")
typ              ε  największa najm. norm. najm. subn.
float16   0.000977    6.55e+04     6.1e-05    5.96e-08
float32   1.19e-07     3.4e+38    1.18e-38     1.4e-45
float64   2.22e-16    1.8e+308   2.23e-308   4.94e-324

The values from NumPy agree with the corresponding rows of the table. Python’s float is binary64; binary32 is float in C and the basic format of graphics cards; binary16 and bfloat16 are used in machine learning. The bfloat16 format (Google Brain) is not part of the standard, but it has the same structure: the range of binary32 and only 8 bits of precision.

Example: almost half of the nonnegative numbers are less than one#

The fields come in the order: sign, exponent, significand. Therefore, for numbers with sign bit \(0\) (the zero \(+0\) and the positive numbers), the order of the numbers agrees with the order of their bits read as an integer, and the integer bity(x) tells us how many nonnegative machine numbers are smaller than \(x\) (counting zero and the subnormal numbers):

print("bity(1.0) =", bity(1.0), "=", hex(bity(1.0)))
print("bity(inf) =", bity(math.inf), "=", hex(bity(math.inf)))
print("udział liczb z [0, 1) wśród nieujemnych skończonych:",
      Fraction(bity(1.0), bity(math.inf)), "≈", bity(1.0) / bity(math.inf))
print("liczb w [1, 2):", bity(2.0) - bity(1.0), "  liczb w [0,1; 0,2):", bity(0.2) - bity(0.1),
      "  2**52 =", 2**52)
bity(1.0) = 4607182418800017408 = 0x3ff0000000000000
bity(inf) = 9218868437227405312 = 0x7ff0000000000000
udział liczb z [0, 1) wśród nieujemnych skończonych: 1023/2047 ≈ 0.49975574010747437
liczb w [1, 2): 4503599627370496   liczb w [0,1; 0,2): 4503599627370496   2**52 = 4503599627370496

Exactly \(1023/2047\) of the nonnegative finite binary64 numbers — almost half — are less than \(1\). Every interval \([2^k,2^{k+1})\) with \(-1022\le k\le1023\) contains the same number of machine numbers, \(2^{52}\); therefore exactly as many of them lie between \(0.1\) and \(0.2\) as between \(1\) and \(2\) (multiplication by \(2\) is exact, so 0.2 is exactly 2 * 0.1).

Example: where the integers end#

All integers of absolute value at most \(2^{53}\) are machine numbers; beyond that the spacing is \(2\), then \(4\), and so on:

for k in range(6):
    print(f"2**53 + {k}  →  2**53 + {int(float(2**53 + k)) - 2**53}")
2**53 + 0  →  2**53 + 0
2**53 + 1  →  2**53 + 0
2**53 + 2  →  2**53 + 2
2**53 + 3  →  2**53 + 4
2**53 + 4  →  2**53 + 4
2**53 + 5  →  2**53 + 4

\(2^{53}+1\) lies exactly halfway between \(2^{53}\) and \(2^{53}+2\). The tie is broken in favor of the number with the even significand, that is, \(2^{53}\); for the same reason \(2^{53}+3\) and \(2^{53}+5\) both give \(2^{53}+4\).

Let us now check which powers of ten are machine numbers and what the literal 1e23 really is:

dokladne = [k for k in range(40) if float(10**k) == 10**k]
print("10**k jest liczbą maszynową dla k =", dokladne[0], "…", dokladne[-1])
print("repr(1e23) =", repr(1e23), "  ale int(1e23) =", int(1e23))
print("5**22 =", 5**22, "< 2**53 =", 2**53, "<", 5**23, "= 5**23")
10**k jest liczbą maszynową dla k = 0 … 22
repr(1e23) = 1e+23   ale int(1e23) = 99999999999999991611392
5**22 = 2384185791015625 < 2**53 = 9007199254740992 < 11920928955078125 = 5**23

Since \(10^k=2^k\cdot5^k\), the number \(10^k\) with \(k\ge0\) is a machine number if and only if \(5^k<2^{53}\), that is, for \(k\le22\): the factor \(2^k\) goes into the exponent, and the odd part \(5^k\) must fit into the 53-bit significand. The literal 1e23 is the number \(99{,}999{,}999{,}999{,}999{,}991{,}611{,}392\); Python prints it as 1e+23 because that is the shortest representation that converts back to the same number (Part 2, §5).

The gap between consecutive machine numbers near \(x\) is the ulp (unit in the last place). In the range of normal numbers, for \(2^k\le|x|<2^{k+1}\), it equals \(\ulp(x)=2^{k-52}\), and in the range of subnormal numbers it is constant, equal to \(2^{-1074}\). The function math.ulp returns this value; let us compare it with \(x\) itself:

print(f"{'x':>22} {'ulp(x)':>24} {'ulp(x)/x':>9}")
for x in (1.0, 1000.0, 1e16, 2.0**53, 1e22, 1e300, 1e-300, 1e-320, 5e-324):
    print(f"{x!r:>22} {math.ulp(x)!r:>24} {math.ulp(x) / x:9.1e}")
                     x                   ulp(x)  ulp(x)/x
                   1.0    2.220446049250313e-16   2.2e-16
                1000.0   1.1368683772161603e-13   1.1e-16
                 1e+16                      2.0   2.0e-16
    9007199254740992.0                      2.0   2.2e-16
                 1e+22                2097152.0   2.1e-16
                1e+300   1.487016908477783e+284   1.5e-16
                1e-300           1.6578092e-316   1.7e-16
                1e-320                   5e-324   4.9e-04
                5e-324                   5e-324   1.0e+00

In absolute terms the gaps grow with \(x\), but in relative terms they stay put: for normal numbers the ratio \(\ulp(x)/|x|\) lies in the interval \((2^{-53},2^{-52}]\), that is, it is of order \(10^{-16}\). This is the idea behind floating-point representation — constant relative precision over an enormous range of magnitudes. Subnormal numbers are the exception: for \(10^{-320}\) the relative gap is already \(4.9\cdot10^{-4}\), and the smallest positive number, \(2^{-1074}\approx4.9\cdot10^{-324}\) (printed as 5e-324), has only one significant bit.

3. Rounding#

Let \(\mathcal F\) denote the set of machine numbers of a given format, extended by \(\pm\infty\). The standard defines four basic modes of rounding a real number \(x\):

  • toward \(-\infty\): \(\mathrm{RD}(x)=\max\{y\in\mathcal F: y\le x\}\);

  • toward \(+\infty\): \(\mathrm{RU}(x)=\min\{y\in\mathcal F: y\ge x\}\);

  • toward zero: \(\mathrm{RZ}(x)\) is whichever of \(\mathrm{RD}(x)\), \(\mathrm{RU}(x)\) lies closer to zero;

  • to nearest (the default mode): \(\mathrm{RN}(x)\) is whichever of \(\mathrm{RD}(x)\), \(\mathrm{RU}(x)\) lies closer to \(x\), and in case of a tie, the one whose significand ends in 0 (ties to even). The exception is overflow: every \(x\) with \(|x|\ge(2-2^{-p})\cdot2^{e_{\max}}\), that is, lying at least half a gap beyond the largest finite number, is rounded in this mode to \(\pm\infty\), even though a finite number lies closer (this is why 1e308 * 10 gives inf in §4).

If \(x\in\mathcal F\), all four modes give \(x\); otherwise \(\mathrm{RD}(x)<x<\mathrm{RU}(x)\), and these are two adjacent machine numbers. Since 2008 there has been an additional mode, round to nearest with ties away from zero, which is required for the decimal formats. The directed modes give guaranteed lower and upper bounds, and interval arithmetic rests on them — this is how the certificates in the worked example for Richardson’s theorem were obtained.

Example: why ties to even#

Ties occur often, especially in decimal arithmetic. The decimal module lets us choose the rounding rule. We compute with three significant digits and, for \(u=1.00\) and \(v=0.555\), repeat \(u\leftarrow(u+v)-v\) (here \(u\) and \(v\) are ordinary numbers, not the unit roundoff from §1):

for regula, nazwa in ((ROUND_HALF_UP, "połówki w górę"), (ROUND_HALF_EVEN, "do parzystej")):
    with localcontext() as ctx:
        ctx.prec, ctx.rounding = 3, regula
        u, v = Decimal("1.00"), Decimal("0.555")
        ciag = [u]
        for _ in range(8):
            u = (u + v) - v
            ciag.append(u)
    print(f"{nazwa:15}", " ".join(str(c) for c in ciag))
połówki w górę  1.00 1.01 1.02 1.03 1.04 1.05 1.06 1.07 1.08
do parzystej    1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00

Mathematically, \((u+v)-v=u\). With round half up, \(1.00+0.555=1.555\to1.56\) and \(1.56-0.555=1.005\to1.01\), and so on, over and over: the result drifts by \(0.01\) per step. With ties to even, \(1.005\to1.00\) and the sequence stays put. Reiser and Knuth (1975) proved that with ties to even the sequence \(u_{k+1}=(u_k\oplus v)\ominus v\), where \(\oplus\) and \(\ominus\) denote addition and subtraction with rounding, stabilizes after the first step — for arbitrary \(u\) and \(v\).

The ties-to-even rule has a second advantage as well: it is unbiased. Rounding all halves in the same direction is biased, because the errors accumulate instead of canceling. Let us check this on a thousand ties \(k+0.5\) for \(k=0,1,\dots,999\): we round them to integers under both rules and add up the errors (value minus rounded value):

def suma_bledow(regula):
    """Suma błędów (wartość - zaokrąglenie) dla liczb k + 0,5, k = 0, …, 999."""
    return sum(Decimal(k) + Decimal("0.5")
               - (Decimal(k) + Decimal("0.5")).quantize(Decimal(1), rounding=regula)
               for k in range(1000))

print("połówki w górę:", suma_bledow(ROUND_HALF_UP),
      "  do parzystej:", suma_bledow(ROUND_HALF_EVEN))
połówki w górę: -500.0   do parzystej: 0.0

A thousand ties rounded up give a total error of \(-500\), because each rounding contributes \(-0.5\). The ties-to-even rule splits the ties evenly: half go up, half go down, and the errors cancel. Python’s round function works the same way (Lecture 1, §1.2).

Example: the machine gives away its precision#

The expression \(3\cdot(4/3-1)-1\) is mathematically equal to zero. In machine arithmetic it is not — and, interestingly, its value lets us read off the machine’s precision without knowing the format:

print("4/3 =", (4/3).hex())
print("3*(4/3 - 1) - 1 =", 3 * (4/3 - 1) - 1, "  równe -2**-52:", 3 * (4/3 - 1) - 1 == -2**-52)
4/3 = 0x1.5555555555555p+0
3*(4/3 - 1) - 1 = -2.220446049250313e-16   równe -2**-52: True

\(4/3=1.0101\ldots_2\) has to be rounded to 53 bits. The discarded part is \(\tfrac13\) of the gap \(2^{-52}\), less than half of it, so the rounding goes down and \(\fl(4/3)=4/3-2^{-52}/3\). The remaining operations are exact: subtracting \(1\) is exact by Sterbenz’s lemma (§5), multiplying by \(3\) gives the machine number \(1-2^{-52}\), and subtracting \(1\) gives exactly \(-2^{-52}\). The only rounding error comes to the surface, multiplied by \(3\): the result is exactly \(-\varepsilon\).

4. Special values#

Normal numbers are not the whole story. The standard also has special values (two zeros, two infinities, and NaN) and subnormal numbers, which fill the gap between zero and the smallest normal number. Thanks to them, every operation has a well-defined result, and computations do not have to stop.

Signed zero#

The standard has two zeros, \(+0\) and \(-0\). They compare equal, but the sign of zero carries information — it tells us which side we came from:

print("-0.0 == 0.0:", -0.0 == 0.0, "  copysign(1, -0.0) =", math.copysign(1.0, -0.0))
print("atan2(+0, -1) =", math.atan2(0.0, -1.0), "  atan2(-0, -1) =", math.atan2(-0.0, -1.0))
print("sqrt(-1 + 0i) =", cmath.sqrt(complex(-1, 0.0)),
      "  sqrt(-1 - 0i) =", cmath.sqrt(complex(-1, -0.0)))
print("log(-1 + 0i) =", cmath.log(complex(-1, 0.0)),
      "  log(-1 - 0i) =", cmath.log(complex(-1, -0.0)))
-0.0 == 0.0: True   copysign(1, -0.0) = -1.0
atan2(+0, -1) = 3.141592653589793   atan2(-0, -1) = -3.141592653589793
sqrt(-1 + 0i) = 1j   sqrt(-1 - 0i) = -1j
log(-1 + 0i) = 3.141592653589793j   log(-1 - 0i) = -3.141592653589793j

The function atan2(y, x) returns the angle of the point \((x,y)\); for \((-1,\pm0)\) it is \(\pm\pi\), because the sign of zero tells us whether the point lies just above or just below the negative half-axis. The complex square root and logarithm have a branch cut along the negative real axis: near the point \(-1\), just above the cut we have \(\sqrt z\approx i\), and just below it \(\sqrt z\approx-i\). Signed zero distinguishes the two sides of the cut: at \(-1+0i\) we get the limit from above, at \(-1-0i\) the limit from below. Kahan (1987) titled his paper on the subject, paraphrasing Shakespeare, Much ado about nothing’s sign bit. Watch out for the notation of a complex number with a negative zero: the result of the intuitive notation -1 - 0j depends on the Python version.

z = -1 - 0j
print(z, "  znak części urojonej:", math.copysign(1.0, z.imag), "  sqrt:", cmath.sqrt(z))
(-1+0j)   znak części urojonej: 1.0   sqrt: 1j

Up to and including Python 3.13 (as on the computer on which this page was built), the expression -1-0j is the difference of the numbers \(-1+0i\) and \(0+0i\), and \(0-0=+0\) — there is no negative zero here. It has to be given explicitly: complex(-1, -0.0). Since Python 3.14, operations that combine a real number with a complex number follow the rules of the C language (the C99 standard): \(-1\) no longer receives the imaginary part \(+0\), so the imaginary part of the result is \(-0\), and cmath.sqrt(-1 - 0j) gives -1j. The notation complex(-1, -0.0) works the same way in every version.

Infinities, NaN, and the five exceptions#

The standard lists five exceptional situations: invalid operation, division by zero, overflow, underflow, and inexact. By default none of them stops the computation: the result receives a value specified by the standard (\(\pm\infty\), NaN, a subnormal number, or the ordinary rounded result), and the processor raises a flag, which stays raised until the program clears it. NumPy lets us see these flags. The cell performs each operation twice: once with the messages silenced, to obtain the result, and once in np.errstate(all="raise") mode, in which a raised flag turns into a FloatingPointError exception — we read the name of the flag from its message:

PRZYPADKI = [
    ("1/0", lambda: np.float64(1) / np.float64(0)),
    ("0/0", lambda: np.float64(0) / np.float64(0)),
    ("sqrt(-1)", lambda: np.sqrt(np.float64(-1))),
    ("inf - inf", lambda: np.float64(np.inf) - np.float64(np.inf)),
    ("1e308 * 10", lambda: np.float64(1e308) * 10),
    ("1e-308 * 1e-10", lambda: np.float64(1e-308) * 1e-10),
    ("5e-324 / 2", lambda: np.float64(5e-324) / 2),
    ("0.1 + 0.2", lambda: np.float64(0.1) + np.float64(0.2)),
]
for opis, f in PRZYPADKI:
    with np.errstate(all="ignore"):
        wynik = f()
    with np.errstate(all="raise"):
        try:
            f()
            flaga = "—"
        except FloatingPointError as e:
            flaga = str(e).split(" encountered")[0]
    print(f"{opis:15} {str(wynik):>20}   {flaga}")
1/0                              inf   divide by zero
0/0                              nan   invalid value
sqrt(-1)                         nan   invalid value
inf - inf                        nan   invalid value
1e308 * 10                       inf   overflow
1e-308 * 1e-10                1e-318   underflow
5e-324 / 2                       0.0   underflow
0.1 + 0.2        0.30000000000000004   —

The table shows four of the five exceptional situations (the fifth, inexact, is discussed at the end of this paragraph): \(1/0\) gives \(+\infty\) and the division-by-zero flag, operations without a meaningful value (\(0/0\), \(\sqrt{-1}\), \(\infty-\infty\)) give NaN and the invalid flag, and a result that is too large gives \(+\infty\) and the overflow flag. Underflow is signaled when the exact result is nonzero, smaller in absolute value than the smallest normal number, and the rounded result is inexact; in the second-to-last row, half of the smallest positive subnormal number is a tie that is rounded to zero. (The standard allows tininess to be detected either before or after rounding, so in borderline cases the underflow flag may depend on the processor.) NumPy does not show the inexact flag — it is raised by almost every operation, including \(0.1+0.2\).

NaN (not a number) has one remarkable property: it is the only value that is not equal to itself.

nan = float("nan")
print("nan == nan:", nan == nan, "  nan != nan:", nan != nan,
      "  nan < 1:", nan < 1, "  nan > 1:", nan > 1)
nan == nan: False   nan != nan: True   nan < 1: False   nan > 1: False

Every comparison with NaN except != gives false. So the relation < on float numbers is no longer a total order once NaN is involved: neither < nor > nor == holds for nan and 1. The test x != x is a portable way of detecting NaN (in Python it is more convenient to use math.isnan). We will see the consequences for sorting and the median in Part 2, §5.

Subnormal numbers: gradual underflow#

The smallest positive normal number is \(2^{-1022}\approx2.2\cdot10^{-308}\). Below it the standard has subnormal numbers, all the way down to \(2^{-1074}\approx4.9\cdot10^{-324}\); this gradual loss of digits as we approach zero is called gradual underflow. What is all this for? Here is Kahan’s argument. Take two different normal numbers just above the threshold, \(x=1.5\cdot2^{-1022}\) and \(y=1.25\cdot2^{-1022}\). Their difference, \(2^{-1024}\), is smaller than the smallest normal number:

x, y = 1.5 * 2.0**-1022, 1.25 * 2.0**-1022
print("x != y:", x != y, "  x - y =", x - y, "=", (x - y).hex(), "  x / (x - y) =", x / (x - y))
x != y: True   x - y = 5.562684646268003e-309 = 0x0.4000000000000p-1022   x / (x - y) = 6.0

The difference is a subnormal number, represented exactly (exponent \(-1022\), significand \(0.01_2\)), and the quotient \(x/(x-y)=1.5/0.25=6\) is correct. If the processor replaced subnormal results by zero — which is what flush to zero mode does — the same division would end in a division by zero. Let us simulate such a mode:

def bez_subnormalnych(v):
    """Tryb „flush to zero”: wynik mniejszy od najmniejszej liczby normalnej staje się zerem."""
    return 0.0 if abs(v) < 2.0**-1022 else v

roznica = bez_subnormalnych(x - y)
print("bez liczb subnormalnych: x - y =", roznica)
try:
    print(x / roznica)
except ZeroDivisionError as e:
    print("x / (x - y):", type(e).__name__)
bez liczb subnormalnych: x - y = 0.0
x / (x - y): ZeroDivisionError

With subnormal numbers, finite numbers enjoy the guarantee

\[ x\ne y\iff x-y\ne0, \]

so the test if x != y: protects a division by \(x-y\). Without them — in flush to zero mode, which is turned on for speed, e.g., by the compiler option -ffast-math or on graphics cards — two different numbers can have a zero difference. Gradual underflow does have its price, though: subnormal numbers have fewer significant digits. Let us check this on the number \(10^{-320}\): we print its hexadecimal representation and count its significant bits as \(\log_2\) of its ratio to the smallest positive subnormal number \(2^{-1074}\):

print("1e-320 =", (1e-320).hex(),
      "  bitów znaczących ≈", round(math.log2(1e-320 / 2.0**-1074), 1))
1e-320 = 0x0.00000000007e8p-1022   bitów znaczących ≈ 11.0

The number \(10^{-320}\) is \(2024\cdot2^{-1074}\) (in hexadecimal 0x7e8), and \(2024<2^{11}\), so it has only \(11\) significant bits instead of \(53\); its relative gap is about \(4.9\cdot10^{-4}\), as in the table in §2.

5. What follows from the guarantee#

Several theorems follow from the correct-rounding rule; they let us predict when an operation is exact and when the result depends on the order of operations. We present two: Sterbenz’s lemma on subtracting nearby numbers, and the failure of associativity of addition.

Subtracting nearby numbers is exact#

Sterbenz’s lemma (1974)

If \(x,y\) are machine numbers of a format with subnormal numbers (such as binary64) and \(y/2\le x\le 2y\), then \(x-y\) is a machine number — the subtraction is performed exactly.

The hypothesis about subnormal numbers is necessary: the pair \(x=1.5\cdot2^{-1022}\), \(y=1.25\cdot2^{-1022}\) from §4 satisfies \(y/2\le x\le2y\), but without subnormal numbers its difference \(2^{-1024}\) would not be a machine number. Let us test the lemma on \(50{,}000\) random pairs: \(y\) has an exponent from \(-30\) to \(30\), \(x\) is drawn from the interval \([y/2,2y]\), and Fraction decides whether the computed difference is exact:

niedokladne = 0
for _ in range(50_000):
    y = random.uniform(1, 2) * 2.0**random.randint(-30, 30)
    x = random.uniform(y / 2, 2 * y)
    niedokladne += Fraction(x) - Fraction(y) != Fraction(x - y)
print("odejmowań y/2 ≤ x ≤ 2y z błędem zaokrąglenia:", niedokladne)
odejmowań y/2 ≤ x ≤ 2y z błędem zaokrąglenia: 0

The experiment confirms the lemma: in \(50{,}000\) random subtractions satisfying the hypothesis there is not a single rounding error. If subtracting nearby numbers is exact, where does the “catastrophic cancellation” that we saw in Rump’s example (Lecture 1, §1.4) come from? Let us see on a simple example where the error really arises:

a = 1 + 1e-15
r = a - 1
print("a = 1 + 1e-15 =", repr(a), "  a - 1 =", r)
print("odejmowanie dokładne:", Fraction(a) - 1 == Fraction(r))
print("błąd względny wyniku względem 1e-15:", abs(r - 1e-15) / 1e-15)
a = 1 + 1e-15 = 1.000000000000001   a - 1 = 1.1102230246251565e-15
odejmowanie dokładne: True
błąd względny wyniku względem 1e-15: 0.11022302462515646

The subtraction is exact, and yet the result differs from \(10^{-15}\) by 11%. The error arose earlier: when \(1+10^{-15}\) was rounded to a machine number. Relative to \(a\) it is an error of order \(10^{-16}\), but relative to the small difference it is already 11%. Cancellation is not the fault of the subtraction: the subtraction merely reveals an error that was already there.

Associativity fails#

Each operation is correctly rounded, but an expression with two operations already involves two roundings, and their result depends on the order. Let us compare two parenthesizations of the same sums:

print((1 + 1e-16) + 1e-16, "  vs  ", 1 + (1e-16 + 1e-16))
print((0.1 + 0.2) + 0.3, "  vs  ", 0.1 + (0.2 + 0.3))
1.0   vs   1.0000000000000002
0.6000000000000001   vs   0.6

In the first row, \(10^{-16}<u\approx1.11\cdot10^{-16}\), so \(1+10^{-16}\) rounds to \(1\), and the same happens the second time. On the other hand, \(10^{-16}+10^{-16}=2\cdot10^{-16}\) exceeds half the gap between \(1\) and \(1+2^{-52}\), so with the second parenthesization the result is \(1+2^{-52}\). Each operation on its own is correctly rounded, but a composition of two operations need not be. The second row shows the same thing with ordinary decimals: 0.2 + 0.3 gives exactly 0.5, and 0.1 + 0.5 gives 0.6, which is the correctly rounded sum of the three numbers; whereas 0.1 + 0.2 gives the neighbor of 0.3 (Part 2, §1), so after adding 0.3 we get 0.6000000000000001. Commutativity does hold: \(x+y\) and \(y+x\) have the same exact result, hence the same rounding. Algorithms that cope with the order of summation are in Part 2.

6. Questions and exercises#

  1. How many binary64 numbers lie in the interval \([1,2)\)? In \([2^{-1022},2^{-1021})\)? In \([0,2^{-1022})\)?

  2. Explain why, for \(x\ge0\), the number bity(x) is the number of nonnegative machine numbers smaller than \(x\). What changes for \(x<0\)? And for \(x=-0\), which also satisfies \(x\ge0\)?

  3. What is the largest power of three that is a binary64 machine number? And of seven? (Hint: when is an odd number a machine number?)

  4. Prove Sterbenz’s lemma. (Hint: both numbers are multiples of the ulp of the smaller of the two.)

  5. Show that \(3\cdot(4/3-1)-1=-2^{-52}\) exactly: which of the four operations rounds, and which are exact? What does the same expression give in the binary32 format (np.float32), and why does the result have the opposite sign there?

  6. Why does cmath.sqrt(-1-0j) give 1j in Python 3.12 but -1j in Python 3.14? How do you write the number \(-1-0i\) with a negative zero regardless of the Python version?

Computer exercises for this part — rounding fractions to \(p\) significand bits (also in four rounding modes), gradual underflow, and the drift under round half up — are in the problem set Lab 3 (Parts A and B, and exercise Z1 for independent practice).

References. IEEE Std 754-2019, IEEE Standard for Floating-Point Arithmetic, doi:10.1109/IEEESTD.2019.8766229 · D. Goldberg, What every computer scientist should know about floating-point arithmetic, ACM Computing Surveys 23 (1991), 5–48 · M. L. Overton, Numerical Computing with IEEE Floating Point Arithmetic, SIAM 2001 · N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM 2002 · W. Kahan, Branch cuts for complex elementary functions, or much ado about nothing’s sign bit, in: A. Iserles, M. J. D. Powell (eds.), The State of the Art in Numerical Analysis, Clarendon Press 1987, 165–211 · J. F. Reiser, D. E. Knuth, Evading the drift in floating-point addition, Information Processing Letters 3 (1975), 84–87 · P. H. Sterbenz, Floating-Point Computation, Prentice-Hall 1974 · D. E. Knuth, The Art of Computer Programming, vol. 2, 3rd ed., Addison-Wesley 1997, §4.2.