2.1. Representing numbers in a computer#
A real number is an infinite object: the binary expansions of the numbers \(\sqrt2\) and \(\tfrac1{10}\)
have infinitely many digits. Computer memory is finite, so every program that computes with numbers
has to choose which numbers it can represent and replace the others with approximations. This
choice is a compromise between accuracy, range, and computational cost. In Lecture 1 we met two
extreme solutions: Python’s integers, which are exact, and float numbers, in which
0.1 + 0.2 is not equal to 0.3
(§1.2, §1.4).
Now we will put the whole picture in order. We will compare four ways of representing numbers, and
then describe in detail the binary64 format, that is, Python’s float: its precision, its range,
and what happens near zero.
The examples use the standard library, NumPy, and Matplotlib:
import math, sys, textwrap
from fractions import Fraction
import numpy as np
import matplotlib.pyplot as plt
2.1.1. Integers: arbitrary length and fixed width#
Python’s integers (the type int) have unlimited precision: the interpreter allocates as much
memory as needed, so numbers such as \(25!\) or \(2^{1000}\) are computed exactly. The price is time,
because an operation on numbers with a million digits takes longer than on numbers with ten digits.
The processor, the C language, NumPy, and graphics cards, on the other hand, use fixed-width
integers, most often 64-bit ones (the type int64). Let us check what happens when a result no
longer fits in 64 bits. The function np.cumprod computes the successive products
\(1!, 2!, \dots, 25!\) in the type int64, and next to them we compute the same factorials exactly:
silnie = np.cumprod(np.arange(1, 26, dtype=np.int64)) # 1!, ..., 25!
for n in (20, 21, 22):
dokladnie = math.factorial(n)
print(f"{n}! dokładnie: {dokladnie:>25} int64: {silnie[n - 1]:>21}")
zle = [n for n in range(1, 26) if int(silnie[n - 1]) != math.factorial(n)]
print("pierwsza błędna silnia w int64:", zle[0], " największy int64:",
np.iinfo(np.int64).max)
20! dokładnie: 2432902008176640000 int64: 2432902008176640000
21! dokładnie: 51090942171709440000 int64: -4249290049419214848
22! dokładnie: 1124000727777607680000 int64: -1250660718674968576
pierwsza błędna silnia w int64: 21 największy int64: 9223372036854775807
Up to \(20!\) the results agree, but \(21! \approx 5.1\cdot10^{19}\) already exceeds the largest number
of the type int64, that is, \(2^{63}-1 \approx 9.2\cdot10^{18}\). NumPy reports neither an error nor
a warning, and the negative number we get is no accident. Let us check what it is:
r = math.factorial(21) % 2**64 # reszta z przedziału [0, 2**64)
print("21! mod 2**64 =", r)
print("r - 2**64 =", r - 2**64)
print("równe wynikowi int64:", r - 2**64 == silnie[20])
21! mod 2**64 = 14197454024290336768
r - 2**64 = -4249290049419214848
równe wynikowi int64: True
Fixed-width integers of \(n\) bits form the ring \(\Z/2^{n}\Z\): addition and multiplication are
performed modulo \(2^{n}\), and the result is stored as a representative from the interval
\([-2^{n-1}, 2^{n-1})\) (this is how two’s complement representation works). A computation
in int64 is therefore correct in \(\Z/2^{64}\Z\), but not in \(\Z\). In Python this problem does not
exist, but the cost of every operation grows with the length of the numbers.
2.1.2. Fixed-point representation#
The simplest way to represent fractions is an integer number of units of a fixed size. We record amounts of money in cents, that is, as multiples of \(\tfrac1{100}\) of the currency unit, and digital signal processors store numbers as multiples of \(2^{-k}\).
Definition (fixed-point representation)
Fix a base \(\beta \ge 2\) and natural numbers \(k\) and \(n\). A fixed-point representation with \(k\) digits after the radix point represents the numbers \(x = m\cdot\beta^{-k}\), where \(m\) is an integer satisfying \(|m| < \beta^{n}\). Adjacent numbers of this representation are \(\beta^{-k}\) apart everywhere, so rounding a real number \(x\), \(|x| \le (\beta^{n}-1)\beta^{-k}\), to the nearest of them has an absolute error of at most \(\tfrac12\beta^{-k}\), regardless of the size of \(x\).
In this representation, addition and subtraction are exact as long as the result stays within the range. That is why accounting works in cents: a sum of arbitrarily many amounts is exact. Multiplication, however, already requires rounding, because \(23\%\) of \(0.99\) is \(22.77\) cents, so one has to fix a rule by which the result becomes a whole number of cents.
The weakness of fixed-point representation shows when numbers have different orders of magnitude.
Let us compare two ways of representing numbers in 16 bits. The first is fixed-point: \(m/2^{8}\)
with integer \(|m| < 2^{15}\) (8 bits after the binary point; such a format is often called Q8.8).
The second is the floating-point format binary16 of the IEEE 754 standard, which NumPy provides
as np.float16. For several numbers we compute the relative representation error (the columns
bł. wzgl.) exactly, with fractions:
def stalopozycyjnie(x, k=8, n=15):
"""Najbliższa liczba m / 2**k z |m| < 2**n; None, gdy x jest za duże."""
m = round(x * 2**k)
return Fraction(m, 2**k) if abs(m) < 2**n else None
def bl_wzgl(y, x):
return f"{float(abs(y - x) / x):.1e}"
print(f"{'x':>9} {'Q8.8':>10} {'bł. wzgl.':>10}"
f" {'binary16':>10} {'bł. wzgl.':>10}")
for napis in ("0.001", "0.01", "0.1", "3.14159", "100.3", "1000.7", "30000.2"):
x = Fraction(napis)
q = stalopozycyjnie(x)
h = Fraction(float(np.float16(float(x)))) # zaokrąglenie do binary16
q_napis = "nadmiar" if q is None else f"{float(q):.6g}"
q_blad = "—" if q is None else bl_wzgl(q, x)
print(f"{napis:>9} {q_napis:>10} {q_blad:>10}"
f" {float(h):>10.6g} {bl_wzgl(h, x):>10}")
x Q8.8 bł. wzgl. binary16 bł. wzgl.
0.001 0 1.0e+00 0.0010004 4.0e-04
0.01 0.0117188 1.7e-01 0.0100021 2.1e-04
0.1 0.101562 1.6e-02 0.0999756 2.4e-04
3.14159 3.14062 3.1e-04 3.14062 3.1e-04
100.3 100.301 7.8e-06 100.312 1.2e-04
1000.7 nadmiar — 1000.5 2.0e-04
30000.2 nadmiar — 30000 6.7e-06
The Q8.8 format has a constant absolute error, at most \(2^{-9} \approx 0.002\). In relative terms,
this is excellent accuracy for the number \(100.3\), but already a \(17\%\) error for \(0.01\), and the
number \(0.001\) turns into zero. The numbers \(1000.7\) and \(30{,}000.2\) do not fit at all (the table
shows nadmiar, overflow), because the range ends at \(128\). The binary16 format has a relative
error of at most \(2^{-11} \approx 4.9\cdot10^{-4}\) over the whole range of normal numbers, from
about \(6\cdot10^{-5}\) to \(65{,}504\). This is the idea of floating-point representation: instead of
a constant absolute error, we have a constant relative error over an enormous range of
magnitudes.
2.1.3. Floating-point representation#
Floating-point representation is scientific notation, such as \(6.022\cdot10^{23}\), with a fixed number of significant digits and a bounded exponent range.
Definition (floating-point system)
Fix a base \(\beta \ge 2\), a precision \(p \ge 2\), and an exponent range \(e_{\min} < e_{\max}\). The machine numbers of the floating-point system \(\F(\beta, p, e_{\min}, e_{\max})\) are zero and the numbers
in which \(d_0 \neq 0\) (normal numbers) or \(e = e_{\min}\) and \(d_0 = 0\) (subnormal numbers). Equivalently, \(x = \pm M\cdot\beta^{e-p+1}\) with an integer significand \(M\), where \(\beta^{p-1} \le M < \beta^{p}\) for normal numbers and \(0 < M < \beta^{p-1}\) for subnormal ones.
The binary64 format (float in Python, double in C) is \(\F(2, 53, -1022, 1023)\). In binary,
the leading digit of the significand of a normal number is always 1, so it is not stored: the
64 bits consist of the sign bit, 11 exponent bits, and 52 bits for the remaining digits of the
significand (Lecture 1, §1.4). The formats binary32 (\(p = 24\), \(e_{\max} = 127\)) and binary16
(\(p = 11\), \(e_{\max} = 15\)) have the same structure; their parameters are listed in a table in the
IEEE 754 deep dive (part 1, §2).
The set of machine numbers is easiest to see in a toy system. Let us list all the positive numbers of the system \(\F(2, 3, -1, 2)\), in which the significand has only three bits:
def liczby_maszynowe(p, emin, emax):
"""Dodatnie liczby systemu F(2, p, emin, emax): (normalne, subnormalne)."""
normalne = [Fraction(M, 2**(p - 1)) * Fraction(2)**e
for e in range(emin, emax + 1)
for M in range(2**(p - 1), 2**p)]
subnormalne = [Fraction(M, 2**(p - 1)) * Fraction(2)**emin
for M in range(1, 2**(p - 1))]
return normalne, subnormalne
normalne, subnormalne = liczby_maszynowe(3, -1, 2)
print("normalne:", textwrap.fill(", ".join(map(str, normalne)), 66,
subsequent_indent=" " * 10))
print("subnormalne:", ", ".join(map(str, subnormalne)))
normalne: 1/2, 5/8, 3/4, 7/8, 1, 5/4, 3/2, 7/4, 2, 5/2, 3, 7/2, 4, 5, 6, 7
subnormalne: 1/8, 1/4, 3/8
There are \(16\) normal numbers: four in each interval \([2^{e}, 2^{e+1})\) for
\(e = -1, 0, 1, 2\). Let us plot them on the number line together with the subnormal ones and compare
them with a fixed-point representation in which the spacing is always \(\tfrac14\) (the row
stałopozycyjne in the plot):
fig, ax = plt.subplots(figsize=(9, 2.3))
kolory = ["#d97706", "#4f46e5", "#059669", "#db2777"]
for i, e in enumerate(range(-1, 3)):
xs = [float(x) for x in normalne if 2**e <= x < 2**(e + 1)]
ax.plot(xs, [1] * len(xs), "|", ms=22, mew=2, color=kolory[i],
label=f"$[2^{{{e}}}, 2^{{{e + 1}}})$")
ax.plot([float(x) for x in subnormalne], [1] * 3, "|", ms=22, mew=2,
color="#94a3b8", label="subnormalne")
ax.plot([k / 4 for k in range(0, 32)], [0] * 32, "|", ms=22, mew=2,
color="#334155")
ax.set_yticks([0, 1], ["stałopozycyjne", r"$\mathbb{F}(2,3,-1,2)$"])
ax.set_ylim(-0.6, 1.6)
ax.set_xlim(-0.2, 8.2)
ax.legend(ncol=5, fontsize=8, loc="lower center", bbox_to_anchor=(0.5, 1.0),
frameon=False)
ax.spines[["top", "right", "left"]].set_visible(False)
fig.tight_layout()
plt.show()
Each interval \([2^{e}, 2^{e+1})\) contains the same number of machine numbers, so the spacing doubles whenever we pass a power of two. Floating-point numbers are dense near zero and sparse far from it, while fixed-point numbers are spread evenly. The three subnormal numbers \(\tfrac18, \tfrac14, \tfrac38\) fill the gap between zero and the smallest normal number \(\tfrac12\) — with the same spacing \(\tfrac18\) as the numbers in the interval \([\tfrac12, 1)\).
For a float number, the significand and the exponent are returned by the function math.frexp:
it represents \(|x|\) as \(m\cdot2^{e}\) with \(\tfrac12 \le m < 1\). It is enough to shift the binary
point by 53 places to obtain the integer significand from the definition; for subnormal numbers the
exponent cannot go below \(-1074 = e_{\min} - p + 1\):
def rozklad(x):
"""Mantysa M i wykładnik E liczby x != 0, dla których |x| = M * 2**E."""
m, e = math.frexp(abs(x))
E = max(e - 53, -1074)
return int(math.ldexp(abs(x), -E)), E
print(f"{'x':>24} {'M':>18} {'E':>6} {'bity M':>7}")
for x in (1.0, 0.1, 6.0, 2.0**-1022, 1e-310, 1e-320, 5e-324):
M, E = rozklad(x)
assert Fraction(x) == M * Fraction(2)**E # rozkład jest dokładny
print(f"{x!r:>24} {M:>18} {E:>6} {M.bit_length():>7}")
x M E bity M
1.0 4503599627370496 -52 53
0.1 7205759403792794 -56 53
6.0 6755399441055744 -50 53
2.2250738585072014e-308 4503599627370496 -1074 53
1e-310 20240225330731 -1074 45
1e-320 2024 -1074 11
5e-324 1 -1074 1
The row for 0.1 shows the significand \(7{,}205{,}759{,}403{,}792{,}794\), which has 53 bits, and
the exponent \(-56\). This is the same number that we wrote in Lecture 1 as the fraction
\(3602879701896397/2^{55}\): the significand is even, so the fraction can be reduced. Normal numbers,
including the smallest of them, \(2^{-1022}\), have 53-bit significands. Below \(2^{-1022}\) the exponent
stops at \(-1074\) and the significand loses bits: the number \(10^{-320}\) has only 11 of them left, and
the smallest positive number, 5e-324, that is, \(2^{-1074}\), has just one.
2.1.4. Spacing between numbers: ulp, ε, and u#
Definition (ulp, machine epsilon, unit roundoff)
Let \(x\) be a real number with \(2^{e} \le |x| < 2^{e+1}\), where \(-1022 \le e \le 1023\). The spacing between adjacent binary64 numbers in the interval \([2^{e}, 2^{e+1})\) is
(unit in the last place: one unit in the last digit of the significand). For \(|x| < 2^{-1022}\) the spacing is constant: \(\ulp(x) = 2^{-1074}\). The machine epsilon is \(\varepsilon = \ulp(1) = 2^{-52}\), the distance from \(1\) to the next machine number, and the unit roundoff is \(u = \varepsilon/2 = 2^{-53}\).
The function math.ulp returns \(\ulp(x)\) for a float number. Let us see how the relative
spacing \(\ulp(x)/x\) changes for \(x\) from \(\tfrac14\) to \(16\), and check the value of
\(\varepsilon\) while we are at it:
xs = np.geomspace(0.25, 16, 3000)
wzgledny = np.array([math.ulp(float(x)) / x for x in xs])
fig, ax = plt.subplots(figsize=(8, 2.6))
ax.plot(xs, wzgledny / 2**-53, color="#d97706")
ax.axhline(1, color="#64748b", ls="--", lw=1)
ax.axhline(2, color="#64748b", ls="--", lw=1)
ax.set_xscale("log", base=2)
ax.set_xlabel("$x$")
ax.set_ylabel(r"$\mathrm{ulp}(x)\,/\,(x\,u)$")
ax.set_ylim(0.8, 2.2)
ax.grid(alpha=0.3)
plt.show()
print("najmniejszy i największy iloraz ulp(x)/(x·u):",
wzgledny.min() / 2**-53, wzgledny.max() / 2**-53)
print("ulp(1) == 2**-52 == epsilon:",
math.ulp(1.0) == 2**-52 == sys.float_info.epsilon)
najmniejszy i największy iloraz ulp(x)/(x·u): 1.000231152813916 2.0
ulp(1) == 2**-52 == epsilon: True
The plot has a sawtooth shape. In the interval \([2^{e}, 2^{e+1})\) the absolute spacing is constant, so the relative spacing decreases from \(\varepsilon = 2u\) at the point \(2^{e}\) to a value just above \(u\) at the end of the interval, and then jumps back to \(2u\). So for every normal number, \(u < \ulp(x)/|x| \le \varepsilon\). This gives the most important inequality of this section: if \(x\) lies in the range of normal numbers and \(\fl(x)\) denotes the machine number nearest to it, then
that is, the relative representation error does not exceed \(u = 2^{-53} \approx 1.1\cdot10^{-16}\). That is roughly 16 decimal digits, regardless of whether \(x\) is of order \(10^{-300}\) or \(10^{300}\).
2.1.5. Range: overflow, underflow, and subnormal numbers#
The range of binary64 numbers is determined by three numbers: the largest finite number
\((2-2^{-52})\cdot2^{1023}\), the smallest positive normal number \(2^{-1022}\), and the smallest
positive subnormal number \(2^{-1074}\). Python gives the first two in sys.float_info, and the third
is returned by math.ulp(0.0):
print("największa: ", sys.float_info.max,
sys.float_info.max == (2 - 2**-52) * 2.0**1023)
print("najm. normalna: ", sys.float_info.min,
sys.float_info.min == 2.0**-1022)
print("najm. subnormalna:", math.ulp(0.0), math.ulp(0.0) == 2.0**-1074)
print("największa * 2 =", sys.float_info.max * 2)
największa: 1.7976931348623157e+308 True
najm. normalna: 2.2250738585072014e-308 True
najm. subnormalna: 5e-324 True
największa * 2 = inf
When the rounded result would exceed the largest finite number, we have overflow: in the default
mode, the operation then returns the infinity inf. At the other end of the range there is
underflow. Let us ask a simple question: how many times can we divide \(1\) by \(2\) before we get
zero?
x, kroki = 1.0, 0
while x > 0:
x, kroki = x / 2, kroki + 1
print("liczba dzieleń przez 2:", kroki)
print("2**-1074 / 2 =", 2.0**-1074 / 2)
liczba dzieleń przez 2: 1075
2**-1074 / 2 = 0.0
The answer is \(1075\), not \(1022\). After \(1022\) divisions we reach the smallest normal number \(2^{-1022}\), but division by \(2\) is still exact: the successive powers of two down to \(2^{-1074}\) are subnormal numbers. Only \(2^{-1075}\) is not a machine number. It lies exactly halfway between \(0\) and \(2^{-1074}\), and such a tie is broken in favor of the number with the even significand, that is, zero (we discuss the rounding rule in the next section).
Subnormal numbers are, in essence, a fixed-point representation near zero: there are \(2^{52}-1\)
positive ones, all of them are multiples of \(2^{-1074}\), and they are equally spaced. They therefore
lose relative precision, like the numbers \(10^{-320}\) and 5e-324 in the table above, but they fill
the gap between zero and \(2^{-1022}\). This gradual loss of digits is called gradual underflow.
Thanks to it, for finite \(x, y\) we have \(x \ne y \iff x - y \ne 0\), so the test if x != y:
protects a division by \(x - y\). The IEEE 754 deep dive (part 1, §4)
presents W. Kahan’s argument and a simulation of a processor without subnormal numbers,
and exercise B1 in Lab 3
measures how often, without them, two different numbers have a zero difference.
2.1.6. Summary#
Python’s integers are exact, and their cost grows with their length. Fixed-width numbers of \(n\) bits form the ring \(\Z/2^{n}\Z\): a result outside the range “wraps around,” in NumPy without a warning.
Fixed-point representation has a constant absolute error \(\tfrac12\beta^{-k}\). It is suitable for amounts of money, but not for quantities of different orders of magnitude.
A floating-point system \(\F(\beta, p, e_{\min}, e_{\max})\) has a constant relative error. The binary64 format is \(\F(2, 53, -1022, 1023)\).
The spacing \(\ulp(x) = 2^{e-52}\) doubles at every power of two; \(\varepsilon = 2^{-52}\), \(u = 2^{-53}\), and the relative error of representing a number in the normal range does not exceed \(u\).
Normal numbers occupy the range from \(2^{-1022} \approx 2.2\cdot10^{-308}\) to about \(1.8\cdot10^{308}\). Below them lie the subnormal numbers, down to \(2^{-1074} \approx 4.9\cdot10^{-324}\), with less and less precision.
In the next section we will see what happens to the result of an operation on two machine numbers.
2.1.7. Exercises#
★ For the toy system \(\F(2, 3, -1, 2)\), determine \(\varepsilon\), \(u\), the largest number, the smallest positive normal number, and the smallest positive subnormal number. Check your answers with the function
liczby_maszynowe.★ For which integers \(n\) does
float(n) == nhold? Describe this set and justify your answer using the definition of a floating-point system.★★ Prove that for every number \(x\) in the interval \([2^{-1022}, 2^{1024})\) we have \(u < \ulp(x)/x \le \varepsilon\), and deduce that \(|\fl(x) - x| \le u\,x\). Why does this inequality not hold for subnormal numbers?
★★ From which \(n\) on is the factorial \(n!\) computed by
np.cumprodin the typeint64equal to \(0\)? Justify your answer with Legendre’s formula for the exponent of two in \(n!\), and check it with code.★★★ Every finite
floatnumber has a finite decimal expansion. How many digits after the decimal point does the exact expansion of the number \(2^{-1074}\) have, and how many significant digits? How many digits does the largest finite number \((2-2^{-52})\cdot2^{1023}\) have? Justify the result, and then check it withdecimal.Decimal, which converts afloatnumber to a decimal fraction without rounding.