6. Precision Pitfalls

Where floating-point math goes wrong — and how to fight back

Now that we understand how floating-point arithmetic actually works — the rounding that happens at every operation, the finite precision of the 52-bit significand — it's time to see where things go spectacularly wrong.

The failures are not random. They follow patterns. Once you recognise those patterns you can spot them in production code, choose appropriate workarounds, and make informed decisions about when "good enough" is actually good enough.

Catastrophic Cancellation

Subtraction is the most dangerous operation in floating-point arithmetic. When two nearly-equal numbers are subtracted, their significant digits cancel out, leaving a result built almost entirely from rounding noise.

Diagram

Catastrophic Cancellation

a b a − b 1 . 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ← these digits cancel → 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ← only noise remains
Catastrophic Cancellation

When two numbers share many leading digits, subtracting them eliminates those shared digits. Whatever remains is the low-order bits — and those are the bits most contaminated by earlier rounding.

Worked Example: (1 + 1e-15) − 1

Mathematically, the answer is exactly 1e-15. Let's see what happens in IEEE 754 double precision.

The number 1 + 1e-15 cannot be represented exactly. A double has about 15–16 significant decimal digits. The value 1e-15 sits at the very edge of that precision when added to 1. The hardware rounds 1 + 1e-15 to the nearest representable double, which is 1.0000000000000009992007221626... — the 1e-15 portion has already been perturbed by rounding.

Subtracting 1 leaves 8.881784197001252e-16 — roughly 11% away from the correct answer of 1e-15. We lost about one significant digit entirely to cancellation.

If the inputs were themselves the result of earlier computations, the error compounds. Catastrophic cancellation turns small rounding errors into large relative errors in the result.

The key word is relative. The absolute error may be tiny, but relative to the magnitude of the correct answer, it can be enormous. A result accurate to only one significant figure is worthless for many applications.

When to watch for it: differences of quantities that are nearly equal, computing small values as the difference of large ones, and evaluating expressions like 1 - cos(x) for small x.

Accumulation Error

A single floating-point addition introduces at most half a ULP (unit in the last place) of rounding error. That sounds negligible — and for one addition, it is. But programs rarely add two numbers once. They sum arrays of a million elements, integrate over thousands of time steps, multiply matrices. Each operation contributes a small error, and small errors accumulate.

Diagram

Naive vs. Kahan Summation Error Growth

iterations error naive Kahan 0 high 0 N
Naive vs. Kahan Summation Error Growth

The naive running sum accumulates O(N) error in the worst case. The exact growth depends on the data, but for uniform positive values the error grows roughly proportionally to N. At N = 1,000,000 that rounding noise has been amplified a million-fold relative to a single operation.

The standard demonstration: sum 0.1 exactly ten times. The exact answer is 1.0. In JavaScript (IEEE 754 double): 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 evaluates to 0.9999999999999999. The error is in the 16th decimal place — tiny in absolute terms, but it is nonzero, and it grows with longer sums.

Comparison Pitfalls

The natural reaction to discovering that 0.1 + 0.1 + 0.1 !== 0.3 is to want to fix the comparison. Using == on floats is almost always a mistake.

Three progressively better strategies:

1. Absolute Epsilon

Math.abs(a - b) < epsilon

Choose epsilon based on the expected magnitude of the values. Works well when you know the scale of your numbers. Fails when values span many orders of magnitude: an epsilon of 1e-9 is too tight for numbers near 1e12 and too loose for numbers near 1e-20.

2. Relative Epsilon

Math.abs(a - b) <= epsilon * Math.max(Math.abs(a), Math.abs(b))

Scales the tolerance to the magnitude of the inputs. Far more robust across different scales. The typical relative epsilon for doubles is around 1e-9 to 1e-12. Still has a corner case: when both values are near zero, the relative tolerance collapses to near zero, and you should fall back to an absolute check.

3. ULP Comparison

ULP stands for unit in the last place — the magnitude of the least significant bit of a floating-point number. Two doubles that are within a small number of ULPs are "as equal as they can be" given rounding.

The trick: IEEE 754 doubles, when reinterpreted as 64-bit integers, increase monotonically with value. Adjacent representable doubles differ by exactly 1 integer. So Math.abs(view_as_int64(a) - view_as_int64(b)) <= maxUlps answers "are a and b within N representable floats of each other?"

In JavaScript you need a DataView or BigInt64Array to reinterpret the bits. Languages like C can use a union or memcpy. This is the most principled approach but also the most code.

When to use which

Use absolute epsilon when you know the domain and all values have similar magnitude (e.g., angles in radians, probabilities in [0,1]). Use relative epsilon as the general-purpose default. Use ULP comparison when you need to reason precisely about floating-point representability, such as in numerical library tests.

The Quadratic Formula Disaster

The quadratic formula is a perfect case study in cancellation. Given ax² + bx + c = 0, the two roots are:

x = (-b ± √(b² - 4ac)) / 2a

When b² >> 4ac — meaning |b| is large relative to |4ac| — one of the two roots involves a subtraction of nearly equal quantities. Specifically, if b > 0, the + branch computes -b + √(b² - 4ac). The square root is very close to b, so the addition is actually a subtraction of nearly-equal values.

Concrete Example: a=1, b=1e8, c=1

The two roots are approximately:

  • x₁ ≈ −1e8 (the large root)
  • x₂ ≈ −1e−8 (the small root)

Computing x₂ via the standard formula: (-1e8 + √(1e16 - 4)) / 2. The discriminant 1e16 - 4 rounds to exactly 1e16 in double precision — the 4 is swamped. So √(1e16) = 1e8 exactly, and the numerator becomes -1e8 + 1e8 = 0. The computed root is 0 instead of -1e-8. Catastrophic cancellation has wiped out the entire result.

The fix: use the alternative form for the root that would otherwise cancel. The two formulas are algebraically equivalent but numerically different:

Standard:     x = (-b ± √(b² - 4ac)) / 2a
Alternative:  x = 2c / (-b ∓ √(b² - 4ac))

The trick is to choose which formula to use for each root based on the sign of b: always add in the numerator (never subtract), then derive the other root via x₁ × x₂ = c/a (Vieta's formula):

if b >= 0:
    x₁ = (-b - √(b² - 4ac)) / 2a   // no cancellation: sum of same-sign terms
    x₂ = c / (a × x₁)               // Vieta avoids the formula entirely
else:
    x₁ = (-b + √(b² - 4ac)) / 2a
    x₂ = c / (a × x₁)

This is a general lesson: if you know which branch of a formula cancels, derive an algebraically equivalent form that avoids the cancellation.

Kahan Summation

The most elegant fix for accumulation error in long sums is Kahan's compensated summation algorithm. The key insight: after each addition, compute the rounding error and carry it forward as a correction to the next addition.

function kahanSum(values):
    sum = 0.0
    compensation = 0.0           // tracks accumulated rounding error

    for each x in values:
        y = x - compensation     // apply the correction before adding
        t = sum + y              // sum is big, y may be small — precision lost here
        compensation = (t - sum) - y   // recover the lost low-order bits
        sum = t

    return sum

Why does this work? After t = sum + y, the high-order bits of y are absorbed into sum, but the low-order bits are lost due to the limited precision of the significand. The expression (t - sum) - y recovers exactly those lost bits and stores them in compensation, so they get added back in the next iteration.

The error of Kahan summation is O(1) — it does not grow with N. The compensated sum is accurate to within a small constant number of ULPs regardless of how many terms are summed. The cost is roughly 4× the operations of a naive sum, which is usually acceptable.

Pairwise summation

A simpler alternative: split the array in half recursively and sum each half, then add the two sub-sums. This gives O(log N) error growth — much better than naive O(N), and simpler than Kahan. Many linear algebra libraries (NumPy, for instance) use pairwise summation as a practical default because it is cache-friendly and branchless.

Key Takeaways

Key Takeaways

  • Catastrophic cancellation occurs when nearly-equal values are subtracted — the significant digits cancel and only rounding noise remains in the result
  • Accumulation error grows with the number of operations; naive summation of N values accumulates O(N) rounding error in the worst case
  • Never use == to compare floats; use an absolute or relative epsilon, or ULP distance, depending on the scale of the values
  • The quadratic formula can lose all precision when b² >> 4ac; the fix is to choose the algebraic form that avoids subtraction of nearly-equal terms
  • Kahan summation achieves O(1) error for long sums by tracking and recycling the rounding error from each step
  • Most pitfalls follow one pattern: a small exact result computed as the difference of large approximate values — restructure to avoid that difference

Try It Yourself — Precision Pitfalls Explorer

Select a scenario to see the naive floating-point result alongside the mathematically exact value, the absolute and relative errors, and how an improved method reduces that error.