Sub topic 15
Floating-point pitfalls: inexact decimals and non-associativity
This chapter assumes you can encode a number in IEEE 754, know the sign, biased exponent and fraction fields, and know that rounding to nearest is the default. It explains two consequences of finite precision that GATE questions and real programs both depend on. Many decimal fractions cannot be stored exactly, and floating-point addition does not obey the associative law.
Why 0.1 is inexact
A binary floating-point number has the form m × 2^k, where m is an integer. Every finite value is therefore a fraction whose denominator is a power of two. A decimal fraction in lowest terms is exact in binary only if its denominator has no prime factor other than 2.
- 0.5 = 1/2, 0.25 = 1/4 and 0.375 = 3/8 are exact.
- 0.1 = 1/10 = 1/(2 × 5) has a factor of 5, so its binary expansion never ends: 0.0001100110011... (the block 0011 repeats).
- 0.2 and 0.3 are inexact for the same reason.
Hardware keeps only 24 significant bits in single precision and 53 in double precision. It stores the nearest representable value, so the stored 0.1 is slightly off.
from fractions import Fraction
print(Fraction(0.1)) # 3602879701896397/36028797018963968
print(Fraction(0.1) == Fraction(1, 10)) # False
print(Fraction(0.5)) # 1/2The denominator 36028797018963968 is 2^55. The stored value of 0.1 is exactly 3602879701896397 / 2^55, which is a little larger than 1/10.
Size of the error
For round-to-nearest, each basic operation returns the exact result rounded to a representable number. The relative error is at most the unit roundoff u, which is half the machine epsilon:
| Format | Fraction bits | Machine epsilon | Unit roundoff u |
|---|---|---|---|
| Single | 23 | 2^-23 | 2^-24 |
| Double | 52 | 2^-52 | 2^-53 |
The relative error is bounded, but the absolute error grows with the magnitude of the number. Between 2^e and 2^(e+1) the gap between neighbouring values (the ulp) is 2^(e − fraction bits). In doubles the gap is about 1.1 × 10^-16 near 1.0 and 2 near 10^16.
Consequences of inexact values
Each decimal literal is rounded when it is read. Each operation rounds again. The errors are tiny, but they are enough to break exact comparisons.
import math
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
print(math.isclose(0.1 + 0.2, 0.3)) # True
print(sum([0.1] * 10)) # 0.9999999999999999
print(math.fsum([0.1] * 10)) # 1.0The sum of ten copies of 0.1 misses 1.0 because the error in each stored 0.1 and each partial sum accumulates. math.fsum tracks the lost low-order bits, so it returns the correctly rounded total.
A callout on comparisons:
Absorption and cancellation
Two more effects follow from the fixed number of significant bits.
- Absorption. When two operands differ greatly in magnitude, the smaller one is shifted right to align exponents. Its bits fall off the end and it may vanish. The smaller value disappears if it is below half an ulp of the larger one.
- Catastrophic cancellation. Subtracting two nearly equal numbers cancels the leading digits. The result keeps only the earlier rounding errors, now as a large relative error.
print(2.0**53 + 1 == 2.0**53) # True: 1 is below half the ulp (ulp is 2 here)
print((1 + 1e-16) - 1) # 0.0: 1e-16 < 2^-53, so 1 + 1e-16 rounds to 1Non-associativity
Real addition satisfies (a + b) + c = a + (b + c). Floating-point addition does not, because each addition rounds its own result. Different groupings round at different points.
a, b, c = 1e16, 1.0, 1.0
print((a + b) + c) # 1e+16
print(a + (b + c)) # 1.0000000000000002e+16
x, y, z = 0.1, 0.2, 0.3
print((x + y) + z) # 0.6000000000000001
print(x + (y + z)) # 0.6Near 10^16 the ulp is 2. In (a + b) + c, the sum 10^16 + 1 lies exactly halfway between two neighbours, and ties-to-even picks 10^16. The second 1 is absorbed in the same way, so the answer is 10^16. In a + (b + c), the small values combine first into 2, which is a full ulp and survives.
The diagram shows the two evaluation orders for this example.
Floating-point addition and multiplication are still commutative: a + b = b + a. Distributivity fails too, so a × (b + c) may differ from a × b + a × c. Overflow gives another failure case. With a = 1e308, (a + a) - a is inf because a + a overflows. But a + (a - a) is 1e308.
Worked example in a small format
GATE questions often use a toy format. Take a normalized significand 1.fff (three fraction bits) with round-to-nearest-even. Evaluate (16 + 1) + 1 and 16 + (1 + 1).
- 16 = 1.000 × 2^4. With three fraction bits, the ulp at 2^4 is 2^(4−3) = 2. The neighbours of 16 are 16 and 18.
- 16 + 1 = 17 is halfway between 16 (fraction 000, even) and 18 (fraction 001, odd). Ties-to-even gives 16.
- 16 + 1 = 17 again rounds to 16. So (16 + 1) + 1 = 16.
- 1 + 1 = 2 is exact. 16 + 2 = 18 is representable. So 16 + (1 + 1) = 18.
A hardware adder performs this with guard, round and sticky bits. These bits record enough of the shifted-out part of the smaller operand to decide ties and round correctly.
Reducing the damage
- Sum numbers from smallest magnitude to largest, so small terms can accumulate before meeting a large one.
- Use compensated summation (Kahan) or
math.fsumwhen the total must be accurate. - Rearrange formulas to avoid subtracting nearly equal numbers. For example, compute
x*x - y*yas(x - y) * (x + y). - Use integers for money, for example whole cents, or a decimal type, because decimal fractions are not exact in binary.
- Use a wider format (double instead of single) when accumulated error matters. Remember that this lowers the error but does not remove it.
- Do not rely on a compiler or parallel reduction preserving your summation order. Reordering changes results, because addition is not associative.
Common errors
- Claiming 0.1 is stored exactly "up to the last digit". It is stored as the nearest binary fraction, which differs from 0.1.
- Treating machine epsilon as the absolute error. It bounds the relative error, so the absolute error scales with the number.
- Writing that floating-point addition is not commutative. It is commutative but not associative.
- Forgetting ties-to-even. A value exactly halfway rounds to the neighbour with an even last fraction bit, not always up.
Exercise
A format uses normalized significands 1.fff (three fraction bits) and round-to-nearest-even. Compute (32 + 2) + 2 and 32 + (2 + 2).
Show answer
32 = 1.000 × 2^5, so the ulp is 2^(5−3) = 4 and the neighbours of 32 are 32 and 36. For (32 + 2) + 2: 32 + 2 = 34 is halfway between 32 (fraction 000, even) and 36 (fraction 001, odd), so it rounds to 32. Adding 2 again gives the same tie and the result 32. For 32 + (2 + 2): 2 + 2 = 4 exactly, and 32 + 4 = 36 is representable. The two results are 32 and 36, so the grouping changes the answer.
Exercise
Why is 0.375 stored exactly in binary floating point while 0.3 is not? Why does adding 0.1 ten times in double precision not give exactly 1.0?
Show answer
0.375 = 3/8 has a power-of-two denominator, so it is 0.011 in binary and fits in the fraction field. 0.3 = 3/10 has a factor of 5 in its denominator, so its binary expansion repeats forever and is rounded to 53 significant bits. The stored 0.1 is slightly above 1/10, and each partial sum is rounded again. These rounding errors accumulate and give 0.9999999999999999. A correctly rounded sum such as math.fsum returns 1.0.