Floating-Point Numbers
Computers store real numbers in floating point: a sign, a fixed number of significant binary digits, and an exponent, the binary version of scientific notation. Almost every number in a numerical computation is rounded to this format, so its properties set the limits of everything else in this course.
The double-precision format
The IEEE 754 double (Python's float, NumPy's float64) stores
in 64 bits: 1 sign bit, 11 exponent bits and 52 fraction bits (the leading 1 is implicit, so there are 53 significant bits).
Three numbers describe the format:
| Quantity | Meaning | Value for double |
|---|---|---|
| machine epsilon | gap between 1 and the next float | |
| largest float | overflow threshold | |
| smallest normal float | underflow threshold |
import numpy as np
info = np.finfo(np.float64)
print("eps :", info.eps, "=", 2.0**-52)
print("max :", info.max)
print("tiny :", info.tiny)
print("1 + eps == 1 ?", 1.0 + info.eps == 1.0)
print("1 + eps/2 == 1 ?", 1.0 + info.eps / 2 == 1.0)
print("float32 eps:", np.finfo(np.float32).eps)eps : 2.220446049250313e-16 = 2.220446049250313e-16
max : 1.7976931348623157e+308
tiny : 2.2250738585072014e-308
1 + eps == 1 ? False
1 + eps/2 == 1 ? True
float32 eps: 1.1920929e-07
Floats are not evenly spaced
Between and there are exactly equally spaced floats, so the gap is : it doubles every time the exponent goes up. The relative gap stays about everywhere. np.spacing(x) returns the gap after .
import numpy as np
for x in (1.0, 1000.0, 1e16, 2.0**53):
print(f"spacing after {x:.6g}: {np.spacing(x):.6g}, relative {np.spacing(x) / x:.3g}")
print("2**53 + 1 == 2**53 ?", 2.0**53 + 1 == 2.0**53)spacing after 1: 2.22045e-16, relative 2.22e-16
spacing after 1000: 1.13687e-13, relative 1.14e-16
spacing after 1e+16: 2, relative 2e-16
spacing after 9.0072e+15: 2, relative 2.22e-16
2**53 + 1 == 2**53 ? True
Beyond even integers can no longer all be represented, which matters for large IDs stored as floats (for example in JSON read by JavaScript).
Rounding and the fundamental property
Every real number in range is rounded to the nearest float with
where is the unit roundoff. IEEE arithmetic guarantees that and give the correctly rounded exact result: . This one rule is the basis of all rounding-error analysis (Rounding Error and Its Propagation).
Decimal fractions such as are infinite in binary, so they are rounded on input:
from decimal import Decimal
print(Decimal(0.1))
print(0.1 + 0.2 == 0.3, abs((0.1 + 0.2) - 0.3))
print(0.1.hex(), (0.5).hex())0.1000000000000000055511151231257827021181583404541015625
False 5.551115123125783e-17
0x1.999999999999ap-4 0x1.0000000000000p-1
Special values
- inf results from overflow (
1e308 * 10) or division by zero in NumPy;-inflikewise. - nan (not a number) results from undefined operations such as
inf - infor0/0; it is not equal to anything, even itself, so test withnp.isnan. - Subnormal numbers fill the gap between and with reduced precision, so underflow is gradual.
import numpy as np
with np.errstate(all="ignore"):
a = np.array([1e308]) * 10
b = np.array([0.0]) / 0.0
print(a, b, b == b, np.isnan(b))
print("smallest subnormal:", np.nextafter(0.0, 1.0))
print("5e-324 / 2 =", 5e-324 / 2)[inf] [nan] [False] [ True]
smallest subnormal: 5e-324
5e-324 / 2 = 0.0
In software
float32(single precision, ) halves memory and is standard on GPUs; deep learning even usesfloat16andbfloat16(8 bits of precision). Numerical algorithms that are fine in double may fail in single precision.- Never compare floats with
==after computation; usemath.iscloseornp.isclosewith a tolerance suited to the problem. - Money should be stored as integers (cents) or
decimal.Decimal, not binary floats.
Exercises
Exercise 1: Spacing
What is the gap between consecutive doubles in ?
Answer
.
Solution
In the gap is .
Exercise 2: Representable integers
Is exactly representable as a double? And ?
Answer
yes; no.
Solution
In the spacing is , so only even integers are representable there.
Exercise 3: Find epsilon by halving (code)
Starting from e = 1.0, halve e while 1.0 + e / 2 > 1.0. Which value do you end with?
Answer
.
Solution
e = 1.0
count = 0
while 1.0 + e / 2 > 1.0:
e /= 2
count += 1
print(e, count, e == 2.0**-52)2.220446049250313e-16 52 True
The loop stops after 52 halvings. (1 + 2**-53 rounds to 1 because it is exactly halfway and ties round to the even neighbour.)
Test yourself
Machine epsilon for double precision is about…
How does the absolute gap between consecutive floats change as numbers grow?
- It stays constant
- It grows in proportion to the magnitude
- It shrinks
- It is random
Which test correctly detects a NaN x?
x == np.nannp.isnan(x)x is Nonex == 0