Skip to content
LeetQuant
F7 Programming and Algorithms Foundations

F7 · Programming and Algorithms Foundations · Lesson 6 of 6

Numerical Computation in Python

How doubles are stored, where rounding error comes from, catastrophic cancellation, compensated summation and math.fsum, Python's unbounded integers, Fraction and Decimal, and comparing floats safely.

18 min

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

(−1)s×1.f×2e−1023,(-1)^s \times 1.f \times 2^{e - 1023},

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: ε=2−52≈2.22×10−16\varepsilon = 2^{-52} \approx 2.22 \times 10^{-16} (sys.float_info.epsilon). Each arithmetic operation rounds its exact result to the nearest float, with relative error at most u=ε/2=2−53≈1.11×10−16u = \varepsilon/2 = 2^{-53} \approx 1.11 \times 10^{-16}.
  • The spacing between floats scales with their size: math.ulp(1.0) is about 2.2×10−162.2 \times 10^{-16}, but math.ulp(1e16) is 2.0.
  • Every integer up to 253=9,007,199,254,740,9922^{53} = 9{,}007{,}199{,}254{,}740{,}992 is exact; beyond it, not all are. float(2**53 + 1) is 9007199254740992.0.
  • The range runs from about 1.8×103081.8 \times 10^{308} (sys.float_info.max) down to 2.2×10−3082.2 \times 10^{-308} for normal numbers, with subnormals down to 5e-324. Beyond the top you get inf; inf - inf is nan, and nan == nan is False (test with math.isnan).

Worked example

why 0.1 + 0.2 != 0.3

Explain exactly why 0.1 + 0.2 == 0.3 is False in Python.

Show solution

0.1=1/100.1 = 1/10 has a denominator that is not a power of two, so its binary expansion 0.000110011001100…20.000110011001100\ldots_2 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 2−54≈5.55×10−172^{-54} \approx 5.55 \times 10^{-17}, 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 aa and bb agree in their first 12 digits, a−ba - b has only about 4 meaningful digits left. The cure is algebra that avoids the subtraction.

  • Small-argument functions. ex−1e^x - 1 and ln⁡(1+x)\ln(1 + x) for tiny xx (a small return, a small rate) lose precision when written directly. math.exp(1e-10) - 1 gives 1.000000082740371e-10, wrong in the 8th digit; math.expm1(1e-10) gives 1.00000000005e-10. Likewise use math.log1p(r) for log-returns of small rr.
  • The quadratic formula. For x2+bx+cx^2 + bx + c with ∣b∣≫∣c∣|b| \gg |c|, the root (−b+b2−4c)/2(-b + \sqrt{b^2 - 4c})/2 subtracts nearly equal numbers. Compute the large-magnitude root q=−12(b+sign⁡(b)b2−4c)q = -\tfrac12\left(b + \operatorname{sign}(b)\sqrt{b^2 - 4c}\right) first, which adds numbers of the same sign, then get the small root as c/qc/q from the product of the roots.

For x2+108x+1=0x^2 + 10^8 x + 1 = 0, the naive small root evaluates to −7.45×10−9-7.45 \times 10^{-9}, a 25% error; c/qc/q gives −1.0×10−8-1.0 \times 10^{-8}, correct to full precision (the true root is −10−8−10−24+…-10^{-8} - 10^{-24} + \ldots).

Worked example

(1 − cos x) / x² near zero

The limit of (1−cos⁡x)/x2(1 - \cos x)/x^2 as x→0x \to 0 is 12\tfrac12. What does Python return at x=10−8x = 10^{-8} and x=10−5x = 10^{-5}, and how do you fix it?

Show 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 cos⁡x≈1−x2/2\cos x \approx 1 - x^2/2. At x=10−8x = 10^{-8} the correction x2/2=5×10−17x^2/2 = 5 \times 10^{-17} is below half the spacing of floats just under 1 (that spacing is 2−532^{-53}, so half of it is 2−54≈5.6×10−172^{-54} \approx 5.6 \times 10^{-17}), so math.cos(1e-8) rounds to exactly 1.0 and the numerator is 0: total loss. At x=10−5x = 10^{-5} the subtraction keeps only about 7 correct digits, hence the error in the 8th digit.

The half-angle identity 1−cos⁡x=2sin⁡2(x/2)1 - \cos x = 2\sin^2(x/2) removes the subtraction, and every remaining operation is a product or quotient, which keep relative error near uu. The stable form returns 0.5 at x=10−8x = 10^{-8} and agrees with the Taylor value 12−x2/24≈0.4999999999958333\tfrac12 - x^2/24 \approx 0.4999999999958333 at x=10−5x = 10^{-5}.

Summation: order matters

Floating-point addition is not associative: (1e16 + 1) - 1e16 is 0.0 (the spacing at 101610^{16} 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 nn.

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 nn (to first order), against roughly nun u 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 0.10.1 one million times with a plain loop, with kahan_sum and with math.fsum. How far is each from 100,000100{,}000?

Show 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 1.33×10−61.33 \times 10^{-6}. Each addition rounds to the spacing of the running total (about 1.5×10−111.5 \times 10^{-11} near 10510^5), 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 5.6×10−125.6 \times 10^{-12} above 100,000100{,}000, 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 263−12^{63} - 1. 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−b∣≤max⁡(rel_tol⋅max⁡(∣a∣,∣b∣), abs_tol)|a - b| \le \max(\text{rel\_tol} \cdot \max(|a|, |b|),\ \text{abs\_tol}).

  • 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) is False because nothing is relatively close to 0. Pass an abs_tol suited 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.1 never terminates, because t steps from 0.9999999999999999 to 1.0999999999999999. Loop over integers and compute i / 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: ε=2−52≈2.2×10−16\varepsilon = 2^{-52} \approx 2.2 \times 10^{-16}, integers exact to 2532^{53}, 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; Fraction is exact, and Decimal from strings gives base-10 money arithmetic with explicit rounding.
  • Compare with math.isclose, and always pass abs_tol when comparing with zero.

Practice problems

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).