{"course":{"slug":"maths-you-need","title":"The Maths You Actually Need","url":"https://addaly.com/learn/maths-you-need","level":"intermediate","track":"deep"},"lesson":{"slug":"cancellation-and-summation-order","title":"Catastrophic cancellation, and why a sum depends on its order","url":"https://addaly.com/learn/maths-you-need/cancellation-and-summation-order","position":69,"of":76,"minutes":9,"answer":"Subtracting nearly equal floats leaves only their rounding error, and adding a small float to a large one loses it, so variances must subtract the mean before squaring.","keyIdea":"Subtracting nearly equal floats leaves only their rounding error, and adding a small float to a large one loses it, so variances must subtract the mean before squaring, long sums must accumulate in float64 or pairwise, and because addition is not associative a GPU's varying reduction order makes identical runs diverge."},"body":{"format":"markdown","text":"## Subtracting two nearly equal numbers\n\nEvery float carries about seven digits, in float32, of which the leading ones are the most trustworthy. Subtract two numbers that agree in their first five digits and the result has two digits left: the five that agreed have cancelled, and what remains is the rounding error of the inputs, promoted to the front. This is **catastrophic cancellation**, and it is the mechanism behind most numerical bugs that are not overflow.\n\nThe cleanest example is a variance computed by the textbook shortcut, `E[x²] − E[x]²`. A thousand values near 10,000 with a true spread of 1:\n\n```\nE[x²]  ≈ 100,000,001   (seven digits: stored as 100,000,000)\nE[x]²  ≈ 100,000,000\nvariance = E[x²] − E[x]² → 8.0 in float32, or 0.0, or negative\n```\n\nBoth terms are about `10^8` and are each known to about 8 units. Their difference is supposed to be 1, which is smaller than the error in either. In one run the float32 answer was 8; on other data it comes out as zero or as a negative number, from which `sqrt` returns NaN. The remedy is to subtract the mean first and then square, so that the numbers being squared are near 1 rather than near 10,000, and there is nothing large to cancel. Or use float64, whose sixteen digits leave nine to spare. Every serious library uses one of these; every hand-written `mean(x**2) - mean(x)**2` in a notebook is a bug waiting for data with a large mean.\n\n## Adding a small number to a large one\n\nThe mirror image: `10^8 + 1` in float32 is `10^8`, because the spacing between floats near `10^8` is 8, and 1 is below half of it. Nothing dramatic happens; the 1 is gone.\n\nNow do that ten million times. Sum `0.1` repeatedly in float32:\n\n```\nafter 1,000,000 additions:   100,958   (should be 100,000: 1% high)\nafter 10,000,000 additions: 1,087,937  (should be 1,000,000: 9% high)\n```\n\nThe running total grows; the increment does not; and once the total passes a few million, each `0.1` is rounded to whatever the local spacing allows, which is not 0.1. The error is systematic, not random, because the rounding of `0.1` at each magnitude is always in the same direction. A loss averaged by accumulating `total += batch_loss` in float32 over a long run drifts in exactly this way, and the reported average is wrong by a per cent or more, silently.\n\n## Three fixes, in order of effort\n\n1. **Accumulate in float64.** One word changes and the error falls by nine orders of magnitude. This is the right default for anything that sums across a training run.\n2. **Sum pairwise.** Add neighbours, then add the pairs, and so on, so that every addition combines numbers of similar size. NumPy's `sum` does this, which is why `np.sum` of a float32 array of ten million `0.1`s gives `1,000,000.125`, while a Python loop over the same array gives `1,087,937`. The error grows like `log n` instead of `n`.\n3. **Compensated summation.** Kahan's algorithm keeps a second variable holding the part that was rounded off at each step and adds it back. Four lines; the float32 sum of a million `0.1`s comes out as exactly `100,000.0`.\n\n```python\ndef kahan_sum(xs):\n    s, c = 0.0, 0.0\n    for x in xs:\n        y = x - c\n        t = s + y\n        c = (t - s) - y      # the rounding error, recovered\n        s = t\n    return s\n```\n\n## Addition is not associative\n\nIn exact arithmetic `(a + b) + c = a + (b + c)`. In floating point it does not hold:\n\n```\n(1e16 + −1e16) + 1 = 1.0\n1e16 + (−1e16 + 1) = 0.0      (the 1 was lost inside the brackets)\n```\n\nSame three numbers in the same order, grouped differently, different answer. Most of the time the differences are in the last digit and nobody notices. But a GPU adds up the contributions to a gradient from thousands of threads, and the order in which they arrive is not fixed from one run to the next. So the same code on the same data with the same seed gives a gradient that differs in its last bits, the weights diverge by a little, and after ten thousand steps the two runs are visibly different models. This is the arithmetic beneath the observation in `how-llms-work` that temperature zero is not deterministic: the sampling is fixed; the addition order is not.\n\nFrameworks offer deterministic modes that force a fixed reduction order at a cost in speed. Use them when you need bitwise reproducibility, and know that without them, two runs agreeing to three digits is agreement.\n\n## Where else it hides\n\n- **Softmax without the max subtraction** (module 5): `exp` of large numbers, then a division of huge by huge.\n- **Numerical derivatives** (later in this module): `f(x + h) − f(x)` is a subtraction of nearly equal numbers by construction.\n- **Normalising a vector of tiny values**: dividing by a norm that was itself rounded to zero.\n- **Any formula with a minus sign between two terms of similar size.** Rearranging algebra to avoid the subtraction, as with the variance above, is a legitimate and common numerical technique.\n\nThe habit: when a computed number is the small difference of large ones, ask how many digits the large ones had, and subtract that from seven. What is left is what you know."},"check":{"question":"A monitoring script computes the variance of a latency column as mean(x²) − mean(x)² in float32 and occasionally reports a negative variance. The latencies are around 3,000 ms with a spread of a few ms. What is wrong?","options":[{"text":"The mean of the squares should be divided by n − 1 rather than n.","correct":false,"tempting":"Bessel's correction changes the estimate by a factor near 1 and cannot flip its sign; the sign flip is catastrophic cancellation."},{"text":"Some latencies are negative due to clock skew, which makes the variance negative.","correct":false,"tempting":"A variance is a sum of squares and cannot be negative for any real data; a negative result can only come from the arithmetic, not the inputs."},{"text":"float32 cannot hold numbers as large as 9 million, so the squared terms overflow.","correct":false,"tempting":"Float32 reaches 3.4 × 10^38; the squares are nowhere near overflow. The problem is precision at that magnitude, not range."},{"text":"Both means are near 9 × 10⁶; their small difference is lost to rounding.","correct":true}]},"prev":{"slug":"half-precision-and-mixed-precision","title":"bf16, fp16, and why training keeps a float32 copy","url":"https://addaly.com/learn/maths-you-need/half-precision-and-mixed-precision"},"next":{"slug":"integers-overflow-and-the-size-of-things","title":"Integers, overflow, and the token id that would not fit","url":"https://addaly.com/learn/maths-you-need/integers-overflow-and-the-size-of-things"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Catastrophic cancellation, and why a sum depends on its order', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/cancellation-and-summation-order (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Catastrophic cancellation, and why a sum depends on its order","courseTitle":"The Maths You Actually Need","module":{"index":8,"slug":"numbers-in-a-machine","title":"Numbers inside a machine"},"answer":null,"keyIdea":"Subtracting nearly equal floats leaves only their rounding error, and adding a small float to a large one loses it, so variances must subtract the mean before squaring, long sums must accumulate in float64 or pairwise, and because addition is not associative a GPU’s varying reduction order makes identical runs diverge.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"subtracting-two-nearly-equal-numbers","runs":[{"text":"Subtracting two nearly equal numbers"}]},{"t":"p","runs":[{"text":"Every float carries about seven digits, in float32, of which the leading ones are the most trustworthy. Subtract two numbers that agree in their first five digits and the result has two digits left: the five that agreed have cancelled, and what remains is the rounding error of the inputs, promoted to the front. This is "},{"text":"catastrophic cancellation","b":true},{"text":", and it is the mechanism behind most numerical bugs that are not overflow."}]},{"t":"p","runs":[{"text":"The cleanest example is a variance computed by the textbook shortcut, "},{"text":"E[x²] − E[x]²","code":true},{"text":". A thousand values near 10,000 with a true spread of 1:"}]},{"t":"code","lang":"","label":"Text","text":"E[x²]  ≈ 100,000,001   (seven digits: stored as 100,000,000)\nE[x]²  ≈ 100,000,000\nvariance = E[x²] − E[x]² → 8.0 in float32, or 0.0, or negative"},{"t":"p","runs":[{"text":"Both terms are about "},{"text":"10^8","code":true},{"text":" and are each known to about 8 units. Their difference is supposed to be 1, which is smaller than the error in either. In one run the float32 answer was 8; on other data it comes out as zero or as a negative number, from which "},{"text":"sqrt","code":true},{"text":" returns NaN. The remedy is to subtract the mean first and then square, so that the numbers being squared are near 1 rather than near 10,000, and there is nothing large to cancel. Or use float64, whose sixteen digits leave nine to spare. Every serious library uses one of these; every hand-written "},{"text":"mean(x**2) - mean(x)**2","code":true},{"text":" in a notebook is a bug waiting for data with a large mean."}]},{"t":"h2","id":"adding-a-small-number-to-a-large-one","runs":[{"text":"Adding a small number to a large one"}]},{"t":"p","runs":[{"text":"The mirror image: "},{"text":"10^8 + 1","code":true},{"text":" in float32 is "},{"text":"10^8","code":true},{"text":", because the spacing between floats near "},{"text":"10^8","code":true},{"text":" is 8, and 1 is below half of it. Nothing dramatic happens; the 1 is gone."}]},{"t":"p","runs":[{"text":"Now do that ten million times. Sum "},{"text":"0.1","code":true},{"text":" repeatedly in float32:"}]},{"t":"code","lang":"","label":"Text","text":"after 1,000,000 additions:   100,958   (should be 100,000: 1% high)\nafter 10,000,000 additions: 1,087,937  (should be 1,000,000: 9% high)"},{"t":"p","runs":[{"text":"The running total grows; the increment does not; and once the total passes a few million, each "},{"text":"0.1","code":true},{"text":" is rounded to whatever the local spacing allows, which is not 0.1. The error is systematic, not random, because the rounding of "},{"text":"0.1","code":true},{"text":" at each magnitude is always in the same direction. A loss averaged by accumulating "},{"text":"total += batch_loss","code":true},{"text":" in float32 over a long run drifts in exactly this way, and the reported average is wrong by a per cent or more, silently."}]},{"t":"h2","id":"three-fixes-in-order-of-effort","runs":[{"text":"Three fixes, in order of effort"}]},{"t":"ol","start":1,"items":[[{"text":"Accumulate in float64.","b":true},{"text":" One word changes and the error falls by nine orders of magnitude. This is the right default for anything that sums across a training run."}],[{"text":"Sum pairwise.","b":true},{"text":" Add neighbours, then add the pairs, and so on, so that every addition combines numbers of similar size. NumPy’s "},{"text":"sum","code":true},{"text":" does this, which is why "},{"text":"np.sum","code":true},{"text":" of a float32 array of ten million "},{"text":"0.1","code":true},{"text":"s gives "},{"text":"1,000,000.125","code":true},{"text":", while a Python loop over the same array gives "},{"text":"1,087,937","code":true},{"text":". The error grows like "},{"text":"log n","code":true},{"text":" instead of "},{"text":"n","code":true},{"text":"."}],[{"text":"Compensated summation.","b":true},{"text":" Kahan’s algorithm keeps a second variable holding the part that was rounded off at each step and adds it back. Four lines; the float32 sum of a million "},{"text":"0.1","code":true},{"text":"s comes out as exactly "},{"text":"100,000.0","code":true},{"text":"."}]]},{"t":"code","lang":"python","label":"Python","text":"def kahan_sum(xs):\n    s, c = 0.0, 0.0\n    for x in xs:\n        y = x - c\n        t = s + y\n        c = (t - s) - y      # the rounding error, recovered\n        s = t\n    return s"},{"t":"h2","id":"addition-is-not-associative","runs":[{"text":"Addition is not associative"}]},{"t":"p","runs":[{"text":"In exact arithmetic "},{"text":"(a + b) + c = a + (b + c)","code":true},{"text":". In floating point it does not hold:"}]},{"t":"code","lang":"","label":"Text","text":"(1e16 + −1e16) + 1 = 1.0\n1e16 + (−1e16 + 1) = 0.0      (the 1 was lost inside the brackets)"},{"t":"p","runs":[{"text":"Same three numbers in the same order, grouped differently, different answer. Most of the time the differences are in the last digit and nobody notices. But a GPU adds up the contributions to a gradient from thousands of threads, and the order in which they arrive is not fixed from one run to the next. So the same code on the same data with the same seed gives a gradient that differs in its last bits, the weights diverge by a little, and after ten thousand steps the two runs are visibly different models. This is the arithmetic beneath the observation in "},{"text":"how-llms-work","code":true},{"text":" that temperature zero is not deterministic: the sampling is fixed; the addition order is not."}]},{"t":"p","runs":[{"text":"Frameworks offer deterministic modes that force a fixed reduction order at a cost in speed. Use them when you need bitwise reproducibility, and know that without them, two runs agreeing to three digits is agreement."}]},{"t":"h2","id":"where-else-it-hides","runs":[{"text":"Where else it hides"}]},{"t":"ul","items":[[{"text":"Softmax without the max subtraction","b":true},{"text":" (module 5): "},{"text":"exp","code":true},{"text":" of large numbers, then a division of huge by huge."}],[{"text":"Numerical derivatives","b":true},{"text":" (later in this module): "},{"text":"f(x + h) − f(x)","code":true},{"text":" is a subtraction of nearly equal numbers by construction."}],[{"text":"Normalising a vector of tiny values","b":true},{"text":": dividing by a norm that was itself rounded to zero."}],[{"text":"Any formula with a minus sign between two terms of similar size.","b":true},{"text":" Rearranging algebra to avoid the subtraction, as with the variance above, is a legitimate and common numerical technique."}]]},{"t":"p","runs":[{"text":"The habit: when a computed number is the small difference of large ones, ask how many digits the large ones had, and subtract that from seven. What is left is what you know."}]}],"check":{"question":[{"text":"A monitoring script computes the variance of a latency column as mean(x²) − mean(x)² in float32 and occasionally reports a negative variance. The latencies are around 3,000 ms with a spread of a few ms. What is wrong?"}],"options":[{"text":[{"text":"The mean of the squares should be divided by n − 1 rather than n."}],"correct":false,"tempting":[{"text":"Bessel’s correction changes the estimate by a factor near 1 and cannot flip its sign; the sign flip is catastrophic cancellation."}]},{"text":[{"text":"Some latencies are negative due to clock skew, which makes the variance negative."}],"correct":false,"tempting":[{"text":"A variance is a sum of squares and cannot be negative for any real data; a negative result can only come from the arithmetic, not the inputs."}]},{"text":[{"text":"float32 cannot hold numbers as large as 9 million, so the squared terms overflow."}],"correct":false,"tempting":[{"text":"Float32 reaches 3.4 × 10^38; the squares are nowhere near overflow. The problem is precision at that magnitude, not range."}]},{"text":[{"text":"Both means are near 9 × 10⁶; their small difference is lost to rounding."}],"correct":true,"tempting":null}],"order":[0,3,2,1],"why":null},"prev":{"slug":"half-precision-and-mixed-precision","title":"bf16, fp16, and why training keeps a float32 copy","minutes":9},"next":{"slug":"integers-overflow-and-the-size-of-things","title":"Integers, overflow, and the token id that would not fit","minutes":8}}}