What a float is
A Python float is an IEEE 754 double: 1 sign bit, 11 exponent bits and 52 fraction bits. A normal number is
so it has 53 significant bits, about 15 to 17 decimal digits. Consequences worth memorising:
- Machine epsilon is the gap between 1 and the next float: (
sys.float_info.epsilon). Each arithmetic operation rounds its exact result to the nearest float, with relative error at most . - The spacing between floats scales with their size:
math.ulp(1.0)is about , butmath.ulp(1e16)is2.0. - Every integer up to is exact; beyond it, not all are.
float(2**53 + 1)is9007199254740992.0. - The range runs from about (
sys.float_info.max) down to for normal numbers, with subnormals down to5e-324. Beyond the top you getinf;inf - infisnan, andnan == nanisFalse(test withmath.isnan).
Worked example
why 0.1 + 0.2 != 0.3
Explain exactly why 0.1 + 0.2 == 0.3 is False in Python.
Show solutionHide solution
has a denominator that is not a power of two, so its binary expansion repeats forever and must be rounded to 53 bits. Decimal shows the exact values that are stored:
from decimal import Decimal
print(Decimal(0.1)) # 0.1000000000000000055511151231257827021181583404541015625
print(Decimal(0.2)) # 0.200000000000000011102230246251565404236316680908203125
print(Decimal(0.3)) # 0.299999999999999988897769753748434595763683319091796875
print(0.1 + 0.2) # 0.30000000000000004
The stored 0.1 and 0.2 are both slightly above their true values, while the stored 0.3 is slightly below. The exact sum of the two stored values lies between two adjacent doubles, and rounding to nearest picks the one above 0.3, which is one unit in the last place above the double nearest 0.3. The difference is , exactly what abs((0.1 + 0.2) - 0.3) prints.
No individual step was sloppy: each operation was correctly rounded. Decimal fractions are simply not representable in binary. Hence integer ticks or cents for prices, and a tolerance for comparisons.
Catastrophic cancellation
Subtracting two nearly equal numbers is exact in itself, but it exposes the rounding errors already in its inputs. If and agree in their first 12 digits, has only about 4 meaningful digits left. The cure is algebra that avoids the subtraction.
- Small-argument functions. and for tiny (a small return, a small rate) lose precision when written directly.
math.exp(1e-10) - 1gives1.000000082740371e-10, wrong in the 8th digit;math.expm1(1e-10)gives1.00000000005e-10. Likewise usemath.log1p(r)for log-returns of small . - The quadratic formula. For with , the root subtracts nearly equal numbers. Compute the large-magnitude root first, which adds numbers of the same sign, then get the small root as from the product of the roots.
For , the naive small root evaluates to , a 25% error; gives , correct to full precision (the true root is ).
Worked example
(1 − cos x) / x² near zero
The limit of as is . What does Python return at and , and how do you fix it?
Show solutionHide solution
import math
for x in (1e-5, 1e-8):
naive = (1 - math.cos(x)) / x**2
stable = 2 * math.sin(x / 2) ** 2 / x**2
print(x, naive, stable)
# 1e-05 0.5000000413701854 0.4999999999958333
# 1e-08 0.0 0.5
Near zero . At the correction is below half the spacing of floats just under 1 (that spacing is , so half of it is ), so math.cos(1e-8) rounds to exactly 1.0 and the numerator is 0: total loss. At the subtraction keeps only about 7 correct digits, hence the error in the 8th digit.
The half-angle identity removes the subtraction, and every remaining operation is a product or quotient, which keep relative error near . The stable form returns 0.5 at and agrees with the Taylor value at .
Summation: order matters
Floating-point addition is not associative: (1e16 + 1) - 1e16 is 0.0 (the spacing at is 2, so the 1 is rounded away), while (1e16 - 1e16) + 1 is 1.0. Adding many small terms to a large running total loses their low-order bits each time, and the error grows with .
Kahan (compensated) summation keeps the lost bits in a correction term:
def kahan_sum(xs):
total, c = 0.0, 0.0 # c holds the low-order bits lost so far
for x in xs:
y = x - c
t = total + y # low bits of y are lost here...
c = (t - total) - y # ...and recovered here (algebraically zero)
total = t
return total
Its error bound does not grow with (to first order), against roughly for the plain loop. math.fsum goes further and returns the correctly rounded exact sum, even with cancelling terms where Kahan fails: for [1.0, 1e100, 1.0, -1e100], kahan_sum returns 0.0 and math.fsum returns 2.0.
Since Python 3.12 the built-in sum() of floats is itself compensated (Neumaier's variant of Kahan), so sum([0.1] * 10) gives 1.0 there but 0.9999999999999999 on 3.11 and earlier. A hand-written total += x loop is never compensated, and neither is functools.reduce(operator.add, xs).
Worked example
summing a million ticks of 0.1
Add one million times with a plain loop, with kahan_sum and with math.fsum. How far is each from ?
Show solutionHide solution
import math
xs = [0.1] * 10**6
total = 0.0
for x in xs:
total += x
print(repr(total)) # 100000.00000133288
print(repr(kahan_sum(xs))) # 100000.0
print(repr(math.fsum(xs))) # 100000.0
The plain loop is off by about . Each addition rounds to the spacing of the running total (about near ), and here the roundings are biased in one direction, so they accumulate rather than cancel. Kahan and fsum both return 100000.0, the double nearest to the exact sum of the million stored values (which is about above , less than half the spacing).
In practice: use math.fsum for accuracy, and for running quantities such as PnL that must reconcile to the cent, accumulate integer cents or ticks instead.
Integers, Fraction and Decimal
Python int never overflows. 2**1000 is an exact 302-digit integer, and 10**20 // 3 is exact. This hides a bug class that C++, Java and NumPy expose: a NumPy int64 array wraps around silently past . Overflow appears in Python only when converting to float: float(10**400) and math.exp(1000) raise OverflowError, while float arithmetic such as 1e308 * 10 quietly returns inf.
fractions.Fraction is exact rational arithmetic: Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10) is True. It is ideal for checking a probability answer exactly, but numerators and denominators can grow without bound, so it is slow in long loops.
decimal.Decimal is base-10 floating point with a settable precision (28 significant digits by default) and explicit rounding modes, which is what money calculations need:
from decimal import Decimal, ROUND_HALF_UP
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3")) # True
print(round(2.675, 2)) # 2.67, since the double is 2.67499999...
print(Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) # 2.68
Construct a Decimal from a string. Decimal(0.1) faithfully copies the binary error into a 55-digit decimal.
Comparing floats
Never test computed floats with ==. Use math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0), which checks .
- A relative tolerance scales with magnitude, which is right for prices and most quantities.
- Near zero a relative tolerance is useless:
math.isclose(1e-12, 0.0)isFalsebecause nothing is relatively close to 0. Pass anabs_tolsuited to your units when comparing with zero. - Do not use floats as loop counters or equality-tested keys.
t = 0.0; while t != 1.0: t += 0.1never terminates, becausetsteps from0.9999999999999999to1.0999999999999999. Loop over integers and computei / 10.
Knowledge check
What does float(253) + 1 == float(253) evaluate to, and why?
Knowledge check
A test checks math.isclose(residual, 0.0) where residual is 1e-12. What is the result?
Knowledge check
Which expression gives the most accurate value of ln(1 + r) for r = 1e-10?
Knowledge check
Which line computes a cash amount of exactly 0.30 that compares equal to Decimal("0.3")?
Key takeaways
- A double has 53 significant bits: , integers exact to , spacing proportional to magnitude.
- Each operation is correctly rounded; the damage comes from cancellation, which you remove with algebra (
expm1,log1p, half-angle identities, the stable quadratic formula). - Summation order matters: use
math.fsum(or Kahan) for long sums, and integer ticks or cents for money. - Python ints never overflow, but conversion to float can;
Fractionis exact, andDecimalfrom strings gives base-10 money arithmetic with explicit rounding. - Compare with
math.isclose, and always passabs_tolwhen comparing with zero.
Practice problems
Finished reading?
Answer the 4 knowledge checks to complete this lesson (0 done).