Module contents
Lesson 2 of 26Core 95 min

Rounding errors and numerically sound algorithms

Apply the standard floating-point error model to cancellation, accurate summation and stable reformulations including logsumexp, softmax and online variance.

After this lesson you can

  • Bound rounding error of simple expressions and recursive summation using the standard model.
  • Identify catastrophic cancellation and rewrite formulas using stable identities and functions.
  • Implement pairwise and Kahan summation and Welford's algorithm and compare their errors.
  • Implement stable logsumexp, softmax, softplus and cross-entropy from logits in float32 and float16.
  • Explain why parallel reductions are not bitwise reproducible.

Before you start

Motivation: two failures without warning

The previous lesson showed what numbers exist on the machine: floating-point numbers, their machine epsilon and rounding to nearest. This lesson concerns what happens when you compute with them. Each operation incurs a tiny error, of order 10−1610^{-16} in float64, which usually does not matter. But two mechanisms turn such tiny errors into completely false results, and appear in production code every day. Before theory, watch them fail.

[ ]Two production failuresBrowser
import numpy as np

# 1. Un softmax con temperatura: al bajar T, la pérdida se vuelve NaN
logits = np.array([2.0, 1.0, 0.5, -1.0], dtype=np.float32)
with np.errstate(all="ignore"):
    for T in [1.0, 0.1, 0.01]:
        e = np.exp(logits / np.float32(T))
        print(f"T = {T:<5} softmax ingenuo = {e / e.sum()}")

# 2. La varianza de una serie de precios con la fórmula de los apuntes
rng = np.random.default_rng(0)
precios = 1e9 + rng.normal(0.0, 1.0, size=1000)      # media 1e9, desviación típica 1
print("\nmedia(x²) − media(x)² =", np.mean(precios**2) - np.mean(precios) ** 2)
print("np.var(x)             =", np.var(precios))

With T=0.01T = 0.01, softmax returns nan for the two most likely classes: e200e^{200} does not fit in float32, becomes inf, and ∞/∞\infty/\infty is undefined. Variance calculated as “mean of squares minus square of mean,” the formula in any statistics textbook, comes out negative, −128-128, on data whose variance is 0.9540.954. This is not arbitrary: x2‾\overline{x^2} and xˉ2\bar{x}^2 are about 101810^{18}, and between 2592^{59} and 2602^{60} consecutive doubles are separated by 259−52=1282^{59-52} = 128, so their difference can only be a multiple of 128. Neither failure raises an exception: NaN propagates through the training graph and negative variance enters a square root or position size.

Neither is a NumPy or IEEE 754 failure: both formulas are mathematically correct and numerically unsound. The goal is to predict these failures using a bound, recognize them in formulas and rewrite them to avoid them. The path:

  1. A one-line model for each operation’s error and algebra for accumulating them.
  2. Catastrophic cancellation: why subtracting similar numbers reveals earlier errors.
  3. Summing millions of numbers without losing digits: recursive, pairwise, Kahan and exact summation.
  4. Exponentials without overflow: log-sum-exp, softmax, softplus and cross-entropy from logits.
  5. One-pass statistics: Welford’s algorithm and batch merging.
  6. Why a parallel reduction may not give the same result twice.

The standard model

Let F\mathbb{F} be a binary format with pp significand bits (including the implicit bit): p=53p = 53 in float64, 2424 in float32, 1111 in float16 and 88 in bfloat16 (the IEEE 754 formats). With rounding to nearest, every real xx in the normal range rounds to fl⁡(x)∈F\operatorname{fl}(x) \in \mathbb{F} with

fl⁡(x)=x(1+δ),∣δ∣≤u=2−p.\operatorname{fl}(x) = x(1 + \delta), \qquad \abs{\delta} \le u = 2^{-p}.

uu is unit roundoff: half the relative spacing between consecutive numbers, half machine epsilon εmach=21−p\eps_{\text{mach}} = 2^{1-p}. It is 2−53≈1.11×10−162^{-53} \approx 1.11\times 10^{-16} in float64, 2−24≈5.96×10−82^{-24} \approx 5.96\times 10^{-8} in float32, 2−11≈4.88×10−42^{-11} \approx 4.88\times 10^{-4} in float16 and 2−8≈3.91×10−32^{-8} \approx 3.91\times 10^{-3} in bfloat16.

IEEE 754 requires the four operations and square root to be computed as if the exact operation were performed and the result then rounded. That is all needed to analyze algorithms.

Three observations before using it:

  • Error is relative to the result, not the operands. If x+yx + y is small because x≈−yx \approx -y, absolute error of the sum is also small. What can be large is error xx and yy already carried: we return to this with cancellation.
  • Assumptions matter. Outside the normal range the model fails: a product in the subnormal range loses relative precision (subnormals have fewer bits), and one that overflows gives ∞\infty. Addition and subtraction are the good exception: if x+yx + y falls in the subnormal range, the result is exact, because xx and yy are integer multiples of the smallest subnormal 2emin⁡−p+12^{e_{\min} - p + 1}, their sum is too and, being below 2emin⁡2^{e_{\min}}, fits in p−1p - 1 significand bits.
  • Library functions are outside the model. IEEE 754 recommends but does not require correctly rounded exp, log or cos. Common math libraries guarantee errors of one or a few ulps, practically equivalent to ∣δ∣≤c u\abs{\delta} \le c\,u with small cc.

Checking is inexpensive: compare each float32 operation with its exact value, which fractions.Fraction calculates without rounding.

[ ]The standard model checkedBrowser
import numpy as np
from fractions import Fraction
import operator

u32 = 2.0**-24
rng = np.random.default_rng(0)
a = rng.uniform(-10, 10, 4000).astype(np.float32)
b = rng.uniform(-10, 10, 4000).astype(np.float32)
ops = {"+": (np.add, operator.add), "−": (np.subtract, operator.sub),
       "×": (np.multiply, operator.mul), "/": (np.divide, operator.truediv)}
for nombre, (f_np, f_exacta) in ops.items():
    c = f_np(a, b)
    peor = 0.0
    for ai, bi, ci in zip(a.tolist(), b.tolist(), c.tolist()):
        exacto = f_exacta(Fraction(ai), Fraction(bi))
        if exacto != 0:
            peor = max(peor, abs(float((Fraction(ci) - exacto) / exacto)))
    print(f"x {nombre} y en float32:  max |δ|/u = {peor / u32:.4f}")

# Un error relativo del orden de u en cada operación no impide sorpresas:
print("\n0.1 + 0.2 == 0.3:", 0.1 + 0.2 == 0.3, "  (0.1 + 0.2) - 0.3 =", (0.1 + 0.2) - 0.3)

For all four operations the worst observed ∣δ∣\abs{\delta} is below uu, as the model promises. The final line reminds us that 0.10.1, 0.20.2 and 0.30.3 were already rounded when written: the model concerns the operation, not the data.

Algebra of (1+δ)(1 + \delta) factors

An algorithm performs many operations, each contributing its factor. What allows whole algorithms to be analyzed is that products of (1+δi)(1 + \delta_i) factors combine into one with a clean bound.

Proof

Each factor lies in interval [1−u,(1−u)−1][1 - u, (1 - u)^{-1}]: if ρi=+1\rho_i = +1, because 1−u≤1+δi≤1+u≤(1−u)−11 - u \le 1 + \delta_i \le 1 + u \le (1 - u)^{-1}; if ρi=−1\rho_i = -1, because (1+δi)−1∈[(1+u)−1,(1−u)−1](1 + \delta_i)^{-1} \in [(1 + u)^{-1}, (1 - u)^{-1}] and (1+u)−1≥1−u(1 + u)^{-1} \ge 1 - u. Thus the product lies in [(1−u)n,(1−u)−n][(1 - u)^n, (1 - u)^{-n}]. Bernoulli’s inequality gives (1−u)n≥1−nu(1 - u)^n \ge 1 - nu, used twice. Above, θn≤(1−u)−n−1≤(1−nu)−1−1=γn\theta_n \le (1 - u)^{-n} - 1 \le (1 - nu)^{-1} - 1 = \gamma_n. Below, θn≥(1−u)n−1≥−nu≥−γn\theta_n \ge (1 - u)^n - 1 \ge -nu \ge -\gamma_n.

∎

Notation θk\theta_k denotes “some number with ∣θk∣≤γk\abs{\theta_k} \le \gamma_k,” different at each occurrence, and calculation rules follow directly: (1+θk)(1+θj)=1+θk+j(1 + \theta_k)(1 + \theta_j) = 1 + \theta_{k + j}, γk≤γk+1\gamma_k \le \gamma_{k+1} and γk+γj+γkγj≤γk+j\gamma_k + \gamma_j + \gamma_k\gamma_j \le \gamma_{k+j}. While nu≪1nu \ll 1, γn=nu+O(u2)\gamma_n = nu + \bigO(u^2): each chained operation adds one uu to the bound.

Catastrophic cancellation

Start with the simplest case. Suppose a^=a(1+α)\hat{a} = a(1 + \alpha) and b^=b(1+β)\hat{b} = b(1 + \beta) approximate two numbers, with small relative errors from earlier calculations. Even if subtraction a^−b^\hat{a} - \hat{b} were exact,

∣(a^−b^)−(a−b)∣∣a−b∣=∣aα−bβ∣∣a−b∣≤max⁡(∣α∣,∣β∣) ∣a∣+∣b∣∣a−b∣.\frac{\abs{(\hat{a} - \hat{b}) - (a - b)}}{\abs{a - b}} = \frac{\abs{a\alpha - b\beta}}{\abs{a - b}} \le \max(\abs{\alpha}, \abs{\beta})\,\frac{\abs{a} + \abs{b}}{\abs{a - b}}.

Factor (∣a∣+∣b∣)/∣a−b∣(\abs{a} + \abs{b})/\abs{a - b} is huge when a≈ba \approx b. If aa and bb agree in their first kk decimal digits, the factor is of order 10k10^k and the result loses kk correct digits.

Surprisingly, the subtraction itself incurs no error in that case. This is a classic result.

Proof

Assume 0<y≤x≤2y0 < y \le x \le 2y (x≤y≤2xx \le y \le 2x is symmetric and x=0x = 0 or y=0y = 0 is trivial). Write y=my2ey−p+1y = m_y 2^{e_y - p + 1} with integer mym_y, ∣my∣<2p\abs{m_y} < 2^p and eye_y the exponent of yy (with ey=emin⁡e_y = e_{\min} if subnormal). Since x≥yx \ge y, its exponent is ex≥eye_x \ge e_y, so xx is also an integer multiple of 2ey−p+12^{e_y - p + 1}. Then x−y=k 2ey−p+1x - y = k\,2^{e_y - p + 1} with integer kk, and since 0≤x−y≤y0 \le x - y \le y, also 0≤k≤my<2p0 \le k \le m_y < 2^p. An integer of fewer than pp bits times a power of 2 with exponent at least emin⁡−p+1e_{\min} - p + 1 is representable.

∎

Thus the correct statement is: subtraction does not create errors; it reveals them. Subtracting similar numbers already carrying errors gives an exact result, but exactly the difference between two wrong values.

The lab example: (1−cos⁡x)/x2(1 - \cos x)/x^2

Its limit as x→0x \to 0 is 1/21/2, by the Taylor polynomial cos⁡x=1−x2/2+x4/24−⋯\cos x = 1 - x^2/2 + x^4/24 - \cdots. In float64, fl⁡(cos⁡x)\operatorname{fl}(\cos x) is accurate to relative error of one uu. Subtraction 1−fl⁡(cos⁡x)1 - \operatorname{fl}(\cos x) is exact by Sterbenz. Yet when xx is small, 1−cos⁡x≈x2/21 - \cos x \approx x^2/2 is tiny and absolute error of cos⁡x\cos x, of order uu, becomes relative error ucos⁡x/(1−cos⁡x)≈2u/x2u\cos x/(1 - \cos x) \approx 2u/x^2.

InteractiveCancellation microscope
  • common digits: cancel out
  • correct digits of the result
  • rounding error in cos x and affected digits
  • naive (1 − cos x)/x²
  • stable 2 sin²(x/2)/x²
  • measured relative error
  • prediction u·cos x/(1 − cos x)
x = 1.00e−6
Naive (1−cos⁡x)/x2(1 - \cos x)/x^2…
Stable 2sin⁡2(x/2)/x22\sin^2(x/2)/x^2…
Relative error of naive result…
Common digits of 1 and cos⁡x\cos x…
Correct digits that survive…
Predicted digits lost log⁡10cos⁡x1−cos⁡x\log_{10}\frac{\cos x}{1 - \cos x}…
Above are the exact decimal digits of 1, the double fl⁡(cos⁡x)\operatorname{fl}(\cos x), cos⁡x\cos x and the two differences. Crossed-out digits are common to 1 and cos⁡x\cos x and cancel; green digits are correct survivors; red digits are rounding error in cos⁡x\cos x and what it contaminates. Below left, naive versus stable formula 2sin⁡2(x/2)/x22\sin^2(x/2)/x^2; right, relative error versus prediction ucos⁡x/(1−cos⁡x)u\cos x/(1 - \cos x). Slide xx to 10−810^{-8}: what remains of the result? And just above, at 1.1×10−81.1\times 10^{-8}?

The figure shows what the bound says: correct digits in the result are almost exactly 16 minus the number of common digits of 1 and cos⁡x\cos x. Below x≈1.05×10−8x \approx 1.05\times 10^{-8}, cos⁡x\cos x is less than half a spacing from 1 (2−542^{-54}) and rounds exactly to 1: the formula gives 0. Just above, up to x≈1.8×10−8x \approx 1.8\times 10^{-8}, fl⁡(cos⁡x)=1−2−53\operatorname{fl}(\cos x) = 1 - 2^{-53} and the formula returns 2−53/x22^{-53}/x^2, traversing the entire interval from 1 to 1/31/3 without relating to 1/21/2.

The solution is another formula. With identity 1−cos⁡x=2sin⁡2(x/2)1 - \cos x = 2\sin^2(x/2) there is no subtraction: sin⁡(x/2)\sin(x/2) has relative error of one uu, squaring and division add three more, and the result has relative error of a few uu for all xx.

[ ]Three cancellations and their reformulationsBrowser
import numpy as np

print("   x        (1 − cos x)/x²         2 sen²(x/2)/x²        error relativo   2u/x²")
for k in [1, 2, 4, 6, 7, 8]:
    x = 10.0**-k
    ingenua = (1 - np.cos(x)) / x**2
    estable = 2 * np.sin(x / 2) ** 2 / x**2
    print(f"1e-{k:<2}  {ingenua:.15f}   {estable:.15f}   {abs(ingenua - estable) / estable:.1e}        {2 * 2**-53 / x**2:.1e}")

# La raíz pequeña de x² + b x + c con b = 1e8, c = 1 (raíces ≈ −1e8 y −1e-8)
b, c = 1e8, 1.0
d = np.sqrt(b * b - 4 * c)
print("\nraíz pequeña, fórmula del colegio  :", (-b + d) / 2)
print("raíz pequeña, 2c / (−b − √(b²−4c)):", 2 * c / (-b - d))

# Diferencias de precios: dos cotizaciones de 4 cifras decimales
p1, p0 = 101.37, 101.36
print("\np1 − p0 en float64:", p1 - p0, "  error relativo:", abs((p1 - p0) - 0.01) / 0.01)
print("p1 − p0 en float32:", np.float32(p1) - np.float32(p0))
print("en céntimos enteros:", (round(p1 * 100) - round(p0 * 100)) / 100)

The table confirms the prediction: measured relative error grows like 1/x21/x^2 (two orders of magnitude per order of xx) and stays below bound 2u/x22u/x^2, which assumes the worst possible rounding of cos⁡x\cos x, until it reaches 1. With x=10−4x = 10^{-4} error is 5.2×10−95.2\times 10^{-9} and the result keeps about 8 digits; with x=10−8x = 10^{-8}, none: the formula returns exactly 0. The other two cases show the same phenomenon:

  • The quadratic formula. With b≫0b \gg 0, the small root (−b+b2−4c)/2(-b + \sqrt{b^2 - 4c})/2 subtracts two nearly equal numbers: b2−4c\sqrt{b^2 - 4c} is already rounded and subtraction reveals its error. The large root x1=(−b−b2−4c)/2x_1 = (-b - \sqrt{b^2 - 4c})/2 subtracts nothing, and by Vieta x1x2=cx_1x_2 = c, so x2=c/x1=2c/(−b−b2−4c)x_2 = c/x_1 = 2c/(-b - \sqrt{b^2 - 4c}) is obtained without cancellation. In general, calculate q=−(b+sign⁡(b)b2−4c)/2q = -\big(b + \operatorname{sign}(b)\sqrt{b^2 - 4c}\big)/2 and the roots are qq and c/qc/q.
  • Price differences. 101.37101.37 and 101.36101.36 are not binary-representable; each carries relative error up to uu and subtraction amplifies it about 2⋅101/0.01≈2×1042\cdot 101/0.01 \approx 2\times 10^4 times. In float64 the difference’s relative error is 5.1×10−135.1\times 10^{-13}, about 4600 times uu, but digits remain; in float32 it is 0.0100021360.010002136, retaining only four digits. When data are exact decimals (cents, ticks), subtracting as integers and converting at the end eliminates the problem.

Reformulation: the catalog

All the preceding solutions follow the same recipe: locate subtraction of nearly equal quantities already carrying error and rewrite the expression using an exact identity so that subtraction disappears or uses exact data. This is stable reformulation. The most useful:

Unstable expressionWhere it failsStable reformulation
1−cos⁡x1 - \cos xx→0x \to 02sin⁡2(x/2)2\sin^2(x/2)
x+1−x\sqrt{x + 1} - \sqrt{x}x→∞x \to \infty1/(x+1+x)1/(\sqrt{x + 1} + \sqrt{x})
(−b+b2−4c)/2(-b + \sqrt{b^2 - 4c})/2b2≫∣c∣b^2 \gg \abs{c}, b>0b > 02c/(−b−b2−4c)2c/(-b - \sqrt{b^2 - 4c})
log⁡(1+x)\log(1 + x)x→0x \to 0log1p(x)
ex−1e^x - 1x→0x \to 0expm1(x)
x2−y2x^2 - y^2x≈yx \approx y(x−y)(x+y)(x - y)(x + y)
log⁡x−log⁡y\log x - \log yx≈yx \approx ylog1p((x - y) / y)
sin⁡x−sin⁡y\sin x - \sin yx≈yx \approx y2cos⁡x+y2sin⁡x−y22\cos\frac{x + y}{2}\sin\frac{x - y}{2}

Notice the sixth row: (x−y)(x+y)(x - y)(x + y) also has a subtraction, but of the original data, which are exact, and by Sterbenz x−yx - y is calculated without error if x≈yx \approx y. In x2−y2x^2 - y^2, fl⁡(x2)\operatorname{fl}(x^2) and fl⁡(y2)\operatorname{fl}(y^2) are subtracted after rounding. The problem is not subtraction itself; it is subtracting numbers that already contain error.

Functions log1p and expm1 deserve comment. log⁡(1+x)\log(1 + x) with x=10−10x = 10^{-10} first computes 1+x1 + x, rounded with absolute error up to u≈1.1×10−16u \approx 1.1\times 10^{-16}, huge relative to xx: about 9 of its 16 digits are lost (the library-functions cell below gives 1.0000000827×10−101.0000000827\times 10^{-10} instead of 9.9999999995×10−119.9999999995\times 10^{-11}), and even a perfect logarithm cannot recover them. log1p receives xx directly and never forms 1+x1 + x. That is why they exist in C, NumPy, PyTorch and every serious library: they are not shortcuts but the way to calculate those functions accurately.

Summing accurately

Addition seems the most innocent operation and is repeated most: means, norms, losses, accumulated gradients, P&L, integrals. The obvious algorithm is recursive summation: s^1=x1\hat{s}_1 = x_1 and s^k=fl⁡(s^k−1+xk)\hat{s}_k = \operatorname{fl}(\hat{s}_{k-1} + x_k).

The proof idea, completed in the guided exercise at the end, is to follow each summand: x1x_1 and x2x_2 pass through n−1n - 1 additions, x3x_3 through n−2n - 2, and xnx_n only through the last. Each addition contributes a factor (1+δ)(1 + \delta), the lemma groups them into 1+θ1 + \theta, and the worst has n−1n - 1 factors.

Three practical consequences:

  • The bound is relative to ∑∣xi∣\sum\abs{x_i}, not ∣s∣\abs{s}. If summands have different signs and cancel, ∣s∣\abs{s} can be far smaller than ∑∣xi∣\sum\abs{x_i} and relative error with respect to ss huge. This is cancellation again, now spread across the sum.
  • Order matters. With model variant fl⁡(a+b)=(a+b)/(1+δ)\operatorname{fl}(a + b) = (a + b)/(1 + \delta), each step incurs error s^k−(s^k−1+xk)=−δks^k\hat{s}_k - (\hat{s}_{k-1} + x_k) = -\delta_k\hat{s}_k, and summing gives the finer bound ∣s^n−sn∣≤u∑k=2n∣s^k∣\abs{\hat{s}_n - s_n} \le u\sum_{k=2}^n \abs{\hat{s}_k}: the sizes of partial sums matter. For same-sign summands it helps to add smallest to largest so partial sums grow as late as possible; with mixed signs there is no universally best order (Higham, 1993).
  • The bound is worst-case. If rounding errors behave as independent zero-mean variables, typical error grows like n u\sqrt{n}\,u rather than nunu; Higham and Mary (2019) turned this into a rigorous high-probability bound.

Pairwise summation

In recursive summation x1x_1 passes through n−1n - 1 additions. If a balanced binary tree replaces the chain (sum pairs, then pairs of pairs, and so on), each summand passes only through the tree’s depth.

Deriving that bound is the guided exercise’s final step. The improvement is enormous: for n=106n = 10^6, the constant changes from n−1≈106n - 1 \approx 10^6 to ⌈log⁡2n⌉=20\lceil\log_2 n\rceil = 20. It costs no extra additions because the count is the same. This is what np.sum does in many cases, as the lab shows.

Compensated summation: Kahan and Neumaier

One can do better still and obtain error that does not grow with nn. The key is that error of a floating-point sum is itself a representable number that can be calculated.

Kahan (1965) applied this to recursive summation: each step calculates what was just lost and subtracts it from the next summand.

Its analysis (Higham, 2002, chapter 4) gives ∣s^n−sn∣≤(2u+O(nu2))∑∣xi∣\abs{\hat{s}_n - s_n} \le \big(2u + \bigO(nu^2)\big)\sum\abs{x_i}: while nu≪1nu \ll 1, error no longer depends on nn. The cost is four operations per summand instead of one and a chain dependency preventing naive vectorization.

Kahan has a weakness: Fast2Sum analysis requires ∣s∣≥∣y∣\abs{s} \ge \abs{y}. If a summand exceeds the accumulated sum, (t−s)(t - s) is not the part of yy that entered and the correction is lost. Neumaier (1974) fixed this by comparing magnitudes each step:

t=s+xk,c+={(s−t)+xksi ∣s∣≥∣xk∣,(xk−t)+ssi no,s=t,t = s + x_k, \qquad c \mathrel{+}= \begin{cases} (s - t) + x_k & \text{si } \abs{s} \ge \abs{x_k}, \\ (x_k - t) + s & \text{si no}, \end{cases} \qquad s = t,

and returns s+cs + c at the end. You will implement it in a code exercise, with a case where Kahan fails and Neumaier does not.

InteractiveSummation race
Zoom: the last Kahan step, bit by bit (each box is a power of 2; filled boxes are 1)
  • measured
  • worst-case bound (same color)
  • zero error is drawn at 10−1210^{-12}
n = 1,000,000
Statussumming 10⁶ values…
Sum the first nn of 10610^6 values in float32 using recursive (red), pairwise (blue) and Kahan (teal) summation; same-colored dashed lines are worst-case bounds γn−1\gamma_{n-1}, γ⌈log⁡2n⌉\gamma_{\lceil\log_2 n\rceil} and 2u2u. The reference is exact: data are multiples of 2−242^{-24} and their sum fits in a double. Play the animation and change data: compare the red slope with its bound and try “one 1 and many tiny values.” Below is Kahan's last step in bits: bits of yy to the right of the last bit of tt are lost in the sum and reappear in cc.

With uniform data in [0,1)[0, 1), recursive-sum error grows with nn clearly below its worst-case bound: it rises about three orders of magnitude over five decades of nn, closer to n\sqrt{n} than nn, as probabilistic analysis predicts. Sorting these data barely changes anything: with n=106n = 10^6, smallest-to-largest and largest-to-smallest recursive sums remain the same order of magnitude as unsorted, because with similarly sized summands partial sums grow nearly alike in any order. With alternating signs, partial sums stay small and recursive summation makes much smaller errors relative to ∑∣xi∣\sum\abs{x_i}. Pairwise and Kahan stay near the error of the best possible float32 result, the rounded exact sum (relative error up to u≈6×10−8u \approx 6\times 10^{-8} with respect to ss). With “one 1 and many tiny values” recursive summation stagnates: each summand is less than half float32 spacing around 1, fl⁡(1+xi)=1\operatorname{fl}(1 + x_i) = 1 and the sum does not move, so error grows exactly like nn. The bit zoom shows why Kahan does not stagnate: the bits of yy that tt cannot store are exactly those appearing in −c-c.

Summation lab

Implement four sums from scratch in float32. Variables are np.float32 scalars, so each operation rounds to float32 as on a GPU. Pairwise summation is written iteratively over arrays: adding x[0::2] + x[1::2] is one tree level, and repeating until one element remains traverses the entire tree.

[ ]Four sums from scratchBrowser
import numpy as np
import math

f32 = np.float32

def suma_recursiva(x):
    s = f32(0)
    for xi in x:
        s = s + xi
    return s

def suma_por_pares(x):
    x = np.asarray(x, dtype=np.float32)
    while len(x) > 1:
        if len(x) % 2:                      # número impar: el último pasa al siguiente nivel tal cual
            x = np.append(x[:-1][0::2] + x[:-1][1::2], x[-1])
        else:
            x = x[0::2] + x[1::2]           # un nivel del árbol, cada suma redondeada a float32
    return x[0]

def suma_kahan(x):
    s, c = f32(0), f32(0)
    for xi in x:
        y = xi - c
        t = s + y
        c = (t - s) - y                     # menos lo que se perdió al sumar y
        s = t
    return s

def suma_neumaier(x):
    s, c = f32(0), f32(0)
    for xi in x:
        t = s + xi
        if abs(s) >= abs(xi):
            c += (s - t) + xi
        else:
            c += (xi - t) + s
        s = t
    return s + c

u = 2.0**-24
gamma = lambda k: k * u / (1 - k * u)
rng = np.random.default_rng(0)
datos = (rng.integers(0, 2**24, 10**5) / 2**24).astype(np.float32)   # uniformes en [0, 1)

print("     n   recursiva   por pares   Kahan       Neumaier    cota rec.  cota pares")
for n in [10**2, 10**3, 10**4, 10**5]:
    x = datos[:n]
    exacta = math.fsum(x.astype(float))          # suma exacta, redondeada una vez
    sa = math.fsum(np.abs(x).astype(float))
    errs = [abs(float(f(x)) - exacta) / sa for f in (suma_recursiva, suma_por_pares, suma_kahan, suma_neumaier)]
    assert errs[0] <= gamma(n - 1) and errs[1] <= gamma(math.ceil(math.log2(n))) and errs[2] <= 2 * u + n * u * u
    print(f"{n:>6}   " + "   ".join(f"{e:.2e}" for e in errs) + f"   {gamma(n - 1):.1e}    {gamma(math.ceil(math.log2(n))):.1e}")

print("\nla suma recursiva coincide con np.cumsum(x)[-1]:", suma_recursiva(datos[:1000]) == np.cumsum(datos[:1000])[-1])

All four sums respect their bounds (assert do not trigger) and the pattern matches the figure. Recursive error moves from 1.4×10−71.4\times 10^{-7} with n=100n = 100 to 2.8×10−62.8\times 10^{-6} with n=105n = 10^5: twenty times greater for a thousand times more summands, near n\sqrt{n} and far below its bound 6×10−36\times 10^{-3}. Pairwise, Kahan and Neumaier stay below 10−710^{-7} for every size, at the final rounding level. The last line shows something useful: np.cumsum accumulates in order, so its last element is the recursive sum. What does np.sum do?

[ ]When np.sum uses pairwise summationBrowser
import numpy as np
import math

rng = np.random.default_rng(1)
x = (rng.integers(0, 2**24, 10**6) / 2**24).astype(np.float32)
exacta = math.fsum(x.astype(float))
rel = lambda v, ref: abs(float(v) - ref) / ref

print(f"np.sum(x)          error relativo {rel(np.sum(x), exacta):.1e}")
print(f"np.cumsum(x)[-1]   error relativo {rel(np.cumsum(x)[-1], exacta):.1e}   (recursiva)")
print(f"np.sum(x[::2])     error relativo {rel(np.sum(x[::2]), math.fsum(x[::2].astype(float))):.1e}   (con paso 2)")

# Una matriz 1000×1000 en orden C: las filas son contiguas en memoria
A = x.reshape(1000, 1000)
filas = A.sum(axis=1)       # suma a lo largo del eje rápido
columnas = A.sum(axis=0)    # suma a lo largo del eje lento
e_filas = max(rel(filas[i], math.fsum(A[i].astype(float))) for i in range(1000))
e_cols = max(rel(columnas[j], math.fsum(A[:, j].astype(float))) for j in range(1000))
print(f"\nA.sum(axis=1), peor fila:    {e_filas:.1e}")
print(f"A.sum(axis=0), peor columna: {e_cols:.1e}")
print("A.sum(axis=0) es exactamente la recursiva por filas:", np.array_equal(columnas, np.cumsum(A, axis=0)[-1]))
print("Con float64 como acumulador, axis=0:", f"{max(rel(c, math.fsum(A[:, j].astype(float))) for j, c in enumerate(A.sum(axis=0, dtype=np.float64))):.1e}")

The numpy.sum documentation says NumPy often uses partial pairwise summation, always when axis is omitted, but along an axis only when it is the fast memory axis. On a vector of 10610^6 elements, np.sum gives error 3.9×10−83.9\times 10^{-8} versus 1.0×10−51.0\times 10^{-5} for recursive summation, about 250 times less; the same holds for a stride-2 vector, noncontiguous but one-dimensional. In the matrix, axis=1 traverses contiguous rows and uses pairwise summation (worst row 1.1×10−71.1\times 10^{-7}); axis=0 adds row by row, exactly recursive summation for each column (checked on the penultimate line), with thirteen times greater error in the worst column. A cheap solution for float32 data is float64 accumulation using dtype=np.float64: the last line gives error 0 because here each column adds one thousand 24-bit values and the sum fits exactly in a double’s 53 bits.

What does compensation cost? In pure Python each operation pays interpreter overhead, so compare ratios rather than absolute times.

[ ]The cost of compensationBrowser
import time

x_lista = (np.random.default_rng(2).integers(0, 2**24, 2 * 10**5) / 2**24).astype(np.float32)

def cronometra(f, *args, reps=3):
    mejor = float("inf")
    for _ in range(reps):
        t0 = time.perf_counter()
        f(*args)
        mejor = min(mejor, time.perf_counter() - t0)
    return mejor

t_rec = cronometra(suma_recursiva, x_lista)
t_kahan = cronometra(suma_kahan, x_lista)
x64 = x_lista.astype(float)
t_np = cronometra(np.sum, x64, reps=20)
t_fsum = cronometra(math.fsum, x64.tolist(), reps=5)
print(f"Kahan / recursiva (bucles en Python): {t_kahan / t_rec:.1f}×")
print(f"math.fsum / np.sum (código compilado): {t_fsum / t_np:.0f}×")

Times depend on the machine, but ratios are stable: in Python loops Kahan costs about twice recursive summation (here 2.2×2.2\times), less than the four-to-one operation ratio because much of the time is interpreter-loop overhead. The production comparison is the second: np.sum (compiled and pairwise) is over an order of magnitude faster than math.fsum (exact, but managing partial sums element by element). In compiled code the difference is structural: pairwise performs the same n−1n - 1 additions as recursive summation with independent branches, so vectorizes equally well; Kahan performs four operations per summand in a chain where each step needs the previous cc. Numerical libraries therefore choose pairwise by default and leave compensated summation for cases where it is needed.

Exponentials without overflow

The exponential is the most dangerous floating-point function: its argument has only a narrow viable interval. exe^x overflows when x>ln⁡(maˊx)x > \ln(\text{máx}), which is 709.78709.78 in float64, 88.7288.72 in float32 and bfloat16 and only 11.0911.09 in float16 (whose maximum is 6550465504). It rounds to 0 when xx is very negative: below −745.1-745.1 in float64, about −104-104 in float32 and −17.3-17.3 in float16 (where exe^x is below half the smallest subnormal). Neural networks constantly compute exponentials of logits.

The log-sum-exp trick

Function LSE⁡(x)=log⁡∑i=1nexi\operatorname{LSE}(\vb{x}) = \log\sum_{i=1}^n e^{x_i} is a smooth maximum (introduced as maximum smoothing): it satisfies max⁡ixi≤LSE⁡(x)≤max⁡ixi+log⁡n\max_i x_i \le \operatorname{LSE}(\vb{x}) \le \max_i x_i + \log n. Its value is perfectly reasonable even if every exie^{x_i} overflows. The problem is the formula, not the function.

With that shift all exponents are ≤0\le 0, so no exponential overflows, and the maximum term equals exactly e0=1e^0 = 1, so the sum lies in [1,n][1, n]: it is never 0 and the logarithm is never −∞-\infty. Terms rounded to 0 are far smaller than uu and would not change that 1 when added: losing them does not change the result.

Blanchard, Higham and Higham (2021) analyzed rounding error in these formulas. Their main conclusion is that shifted versions are as accurate as unshifted ones and can be used confidently; their recommended algorithm adds a detail, using log1p for the maximum term, LSE⁡(x)=m+log1p⁡(∑i≠kexi−m)\operatorname{LSE}(\vb{x}) = m + \operatorname{log1p}\big(\sum_{i \ne k} e^{x_i - m}\big) with kk the maximum index, avoiding information loss when the sum of other terms is small.

Softmax, log-softmax and cross-entropy

The same shift fixes softmax, because it is invariant to adding a constant to all logits:

softmax⁡(z)i=ezi∑jezj=ezi−m∑jezj−m,log⁡softmax⁡(z)i=(zi−m)−log⁡∑jezj−m.\softmax(\vb{z})_i = \frac{e^{z_i}}{\sum_j e^{z_j}} = \frac{e^{z_i - m}}{\sum_j e^{z_j - m}}, \qquad \log\softmax(\vb{z})_i = (z_i - m) - \log\sum_j e^{z_j - m}.

Blanchard and coauthors also compare two ways to calculate softmax: divide by the sum, as in the left formula, or calculate ezi−LSE⁡(z)e^{z_i - \operatorname{LSE}(\vb{z})} without division. They find the second has a worse error bound and larger errors in their experiments, and recommend division.

The second formula, log-softmax, is what training actually needs. Softmax cross-entropy for an example with class yy is

ℓ(z,y)=−log⁡softmax⁡(z)y=LSE⁡(z)−zy,\ell(\vb{z}, y) = -\log\softmax(\vb{z})_y = \operatorname{LSE}(\vb{z}) - z_y,

and is calculated this way from logits. Computing softmax first and then its logarithm is a classic mistake: if softmax⁡(z)y\softmax(\vb{z})_y is so small it rounds to 0 (normal early in training or for a very unlikely class), −log⁡0=∞-\log 0 = \infty, although the true loss is finite and its gradient well-defined.

InteractiveSoftmax at the limit
00.51NaNz₁ = 12.00p = 0.880z₂ = 10.00p = 0.120z₃ = 3.000p = 1.1e−40z₄ = −2.000p = 7.2e−70z₅ = −20.00p = 0
  • naive softmax ezi/T/∑jezj/Te^{z_i/T}/\sum_j e^{z_j/T} (hatched: NaN)
  • subtracting the maximum
  • float64 reference
Format
1.00
Target class yy
Logits
12.00
10.00
3.000
−2.000
−20.00
max⁡izi/T\max_i z_i / T12.000
exp overflow threshold in float1611.09
∑iezi/T\sum_i e^{z_i/T} (naive)∞
Max |error| of stable versus float64…
CE with −log⁡-\log of naive softmax∞
CE with −log⁡-\log of stable softmax∞
CE with log_softmax32.125
Reference CE (float64)32.1270
max⁡izi/T=12.00>ln⁡(max)=11.09\max_i z_i/T = 12.00 > \ln(\text{max}) = 11.09: ezi/Te^{z_i/T} overflows to ∞\infty in float16 and ∞/∞\infty/\infty = NaN. Subtracting the maximum makes the largest exponential e0=1e^0 = 1.
Five logits adjustable up to ±1000\pm 1000, a temperature TT and a format. Each operation (division, exponential, sum and logarithm) rounds to the chosen format. Red is naive softmax ezi/T/∑jezj/Te^{z_i/T}/\sum_j e^{z_j/T} (hatched for NaN); blue subtracts the maximum; the horizontal line over each blue bar is the float64 benchmark. Start in float16 with modest logits: e12e^{12} already does not fit. Look at the highlighted class's three cross-entropies: which survives? Then try low temperature, huge logits and very negative ones.

The figure shows three distinct failures and the shift fixes only two. Overflow (∞/∞\infty/\infty) and total underflow (0/00/0) disappear when subtracting the maximum. The third, log⁡0\log 0 in cross-entropy, remains even with correctly calculated softmax: only never forming the probability avoids it, as log_softmax does. Also notice stable-softmax error against float64: in float16 it is of order 10−410^{-4} to 10−310^{-3}, the size of uu in that format. Subtracting the maximum avoids disaster; it does not make an 11-bit format exact.

The sigmoid family

For binary classification the functions differ, but the principle is the same. With σ(x)=1/(1+e−x)\sigmoid(x) = 1/(1 + e^{-x}):

  • Softplus, softplus⁡(x)=log⁡(1+ex)\operatorname{softplus}(x) = \log(1 + e^x). For large xx, exe^x overflows; for very negative xx, 1+ex1 + e^x rounds to 1 and everything is lost. Stable form is softplus⁡(x)=max⁡(x,0)+log1p⁡(e−∣x∣)\operatorname{softplus}(x) = \max(x, 0) + \operatorname{log1p}(e^{-\abs{x}}), obtained by factoring out emax⁡(x,0)e^{\max(x, 0)}.
  • Log-sigmoid, log⁡σ(x)=−softplus⁡(−x)\log\sigmoid(x) = -\operatorname{softplus}(-x).
  • Binary cross-entropy from the logit. With p=σ(z)p = \sigmoid(z) and label y∈{0,1}y \in \{0, 1\}, −ylog⁡p−(1−y)log⁡(1−p)=softplus⁡(z)−yz-y\log p - (1 - y)\log(1 - p) = \operatorname{softplus}(z) - yz, whose stable form is max⁡(z,0)−yz+log1p⁡(e−∣z∣)\max(z, 0) - yz + \operatorname{log1p}(e^{-\abs{z}}). This is exactly what torch.nn.BCEWithLogitsLoss computes; its documentation says it is more stable than a sigmoid followed by BCELoss because it uses the log-sum-exp trick.
  • log⁡(1−e−a)\log(1 - e^{-a}) for a>0a > 0, appearing when subtracting probabilities on a log scale. Neither obvious formula works throughout. Mächler (2012) showed the good choice is log⁡(−expm1⁡(−a))\log(-\operatorname{expm1}(-a)) when a≤log⁡2a \le \log 2 and log1p⁡(−e−a)\operatorname{log1p}(-e^{-a}) when a>log⁡2a > \log 2. You will implement it in an exercise.

Minimal stable-function library

Implement the whole library in NumPy so it works in float16, float32 and float64 without converting formats, and compare it with SciPy.

[ ]Stable functions from scratchBrowser
import numpy as np

def logsumexp(z, axis=-1):
    z = np.asarray(z)
    m = np.max(z, axis=axis, keepdims=True)
    m = np.where(np.isfinite(m), m, 0)              # si todo es −inf, no restar −inf − (−inf) = NaN
    s = np.sum(np.exp(z - m), axis=axis, keepdims=True)
    return np.squeeze(m + np.log(s), axis=axis)

def log_softmax(z, axis=-1):
    z = np.asarray(z)
    m = np.max(z, axis=axis, keepdims=True)
    d = z - m
    return d - np.log(np.sum(np.exp(d), axis=axis, keepdims=True))

def softmax(z, axis=-1):
    z = np.asarray(z)
    e = np.exp(z - np.max(z, axis=axis, keepdims=True))
    return e / np.sum(e, axis=axis, keepdims=True)

def softplus(x):
    x = np.asarray(x)
    return np.maximum(x, 0) + np.log1p(np.exp(-np.abs(x)))

def log_sigmoid(x):
    return -softplus(-np.asarray(x))

def bce_con_logits(z, y):
    z = np.asarray(z)
    return np.maximum(z, 0) - y * z + np.log1p(np.exp(-np.abs(z)))

def ce_con_logits(z, y):
    """Entropía cruzada media de un lote: z de forma (B, K), y enteros de forma (B,)."""
    lp = log_softmax(z, axis=-1)
    return -np.mean(lp[np.arange(len(y)), y])

def log1mexp(a):
    a = np.asarray(a, dtype=float)
    return np.where(a <= np.log(2), np.log(-np.expm1(-a)), np.log1p(-np.exp(-a)))

z = np.array([[1000.0, 999.0, 990.0], [-1000.0, -1001.0, -1010.0], [0.5, 0.2, -0.3]])
y = np.array([0, 2, 1])
with np.errstate(all="ignore"):
    ingenuo = np.log(np.sum(np.exp(z), axis=1))
print("log Σ exp ingenuo:", ingenuo)
print("logsumexp estable:", logsumexp(z))
print("entropía cruzada media:", ce_con_logits(z, y))
print("softplus(±800):", softplus(np.array([800.0, -800.0])), "   log σ(−800):", log_sigmoid(-800.0))
print("BCE(z = 40, y = 0):", bce_con_logits(40.0, 0), "   ingenua:", -np.log(1 - 1 / (1 + np.exp(-40.0))))

Outputs show three failure modes and their fixes: naive log Σ exp gives inf in the first row and -inf in the second, while the shifted version gives finite values; cross-entropy is computed without forming a probability; and naive BCE with logit 40 gives inf because 1−σ(40)1 - \sigmoid(40) rounds to 0, when the correct value is 40. Now compare with SciPy in all three formats and sweep extreme inputs.

[ ]Against SciPy and a property testBrowser
import numpy as np
from scipy import special

rng = np.random.default_rng(3)
for dt in [np.float16, np.float32, np.float64]:
    z = (rng.normal(size=(200, 10)) * 30).astype(dt)
    ref = special.logsumexp(z.astype(np.float64), axis=1)
    err_lse = np.max(np.abs(logsumexp(z).astype(np.float64) - ref) / np.abs(ref).clip(1))
    ref_ls = special.log_softmax(z.astype(np.float64), axis=1)
    err_ls = np.max(np.abs(log_softmax(z).astype(np.float64) - ref_ls) / np.abs(ref_ls).clip(1))
    print(f"{np.dtype(dt).name:8s} error de logsumexp {err_lse:.1e}   de log_softmax {err_ls:.1e}   (u = {2.0**-(np.finfo(dt).nmant + 1):.1e})")

# Test de propiedades: entradas extremas en los tres formatos, nada de inf ni NaN
extremos = [0.0, 1e-8, -1e-8, 1.0, -1.0, 20.0, -20.0, 80.0, -80.0, 700.0, -700.0, 1e4, -1e4]
fallos = 0
for dt in [np.float16, np.float32, np.float64]:
    big = float(np.finfo(dt).max) / 4
    vals = np.array([v for v in extremos if abs(v) < big], dtype=dt)
    with np.errstate(over="ignore"):
        for i in range(len(vals)):
            for j in range(len(vals)):
                fila = np.array([vals[i], vals[j], vals[(i + j) % len(vals)]], dtype=dt)
                r = [logsumexp(fila), log_softmax(fila), softmax(fila), softplus(fila), log_sigmoid(fila),
                     bce_con_logits(fila, 1), ce_con_logits(fila[None, :], np.array([2]))]
                fallos += sum(int(not np.all(np.isfinite(v))) for v in r)
print("\nresultados no finitos en el barrido:", fallos)
a = np.array([1e-20, 1e-5, 0.5, np.log(2), 1.0, 10.0, 50.0, 700.0])
print("log1mexp:", log1mexp(a))

In all three formats error of logsumexp and log_softmax is of order uu for each format: the shifted version loses no precision, as Blanchard and coauthors predict. The property sweep finds no nonfinite result in any of the seven functions.

One-pass statistics

Return to the initial negative variance. For nn data points, population variance is σ2=S/n\sigma^2 = S/n with S=∑i(xi−xˉ)2S = \sum_i (x_i - \bar{x})^2, and identity S=∑ixi2−nxˉ2S = \sum_i x_i^2 - n\bar{x}^2 permits one-pass computation accumulating ∑xi\sum x_i and ∑xi2\sum x_i^2. This “textbook formula” subtracts two nearly equal numbers.

How nearly equal? Chan and Lewis (1979) defined the variance condition number,

κ=∥x∥2S=1+nxˉ2S,\kappa = \frac{\norm{\vb{x}}_2}{\sqrt{S}} = \sqrt{1 + \frac{n\bar{x}^2}{S}},

which measures how much larger data are than their dispersion. Even if both sums were calculated perfectly, rounding ∑xi2\sum x_i^2 once introduces absolute error up to u∑xi2=uκ2Su\sum x_i^2 = u\kappa^2 S: relative error uκ2u\kappa^2 in SS. Actual sums add factor nn (or log⁡2n\log_2 n if pairwise). For prices 10910^9 with standard deviation 1, κ2≈1018\kappa^2 \approx 10^{18} and uκ2≈111u\kappa^2 \approx 111: the result has no correct digits and its sign is luck.

The two-pass formula, first calculating xˉ\bar{x} and then ∑(xi−xˉ)2\sum(x_i - \bar{x})^2, avoids that subtraction: deviations xi−xˉx_i - \bar{x} are small and positive quantities are added. Its drawback is needing data twice, impossible with streaming data (market ticks, training metrics, a batch-normalization moving average).

Proof

The new mean satisfies mk−mk−1=δ/km_k - m_{k-1} = \delta/k, hence xk−mk=δ(k−1)/kx_k - m_k = \delta(k - 1)/k. It suffices to show Mk−Mk−1=k−1kδ2M_k - M_{k-1} = \frac{k - 1}{k}\delta^2, because that is δ(xk−mk)\delta(x_k - m_k). Write Mk=∑i≤k(xi−mk)2M_k = \sum_{i \le k}(x_i - m_k)^2 and, for the first k−1k - 1, use decomposition ∑i<k(xi−mk)2=Mk−1+(k−1)(mk−1−mk)2\sum_{i < k}(x_i - m_k)^2 = M_{k-1} + (k - 1)(m_{k-1} - m_k)^2, obtained by expanding the square and using ∑i<k(xi−mk−1)=0\sum_{i < k}(x_i - m_{k-1}) = 0. Then

Mk=Mk−1+(k−1)δ2k2+(k−1kδ)2=Mk−1+(k−1)δ2k2(1+k−1)=Mk−1+k−1kδ2.M_k = M_{k-1} + (k - 1)\frac{\delta^2}{k^2} + \Big(\frac{k - 1}{k}\delta\Big)^2 = M_{k-1} + \frac{(k - 1)\delta^2}{k^2}(1 + k - 1) = M_{k-1} + \frac{k - 1}{k}\delta^2.∎

Welford never forms ∑xi2\sum x_i^2: it works with deviations from the current mean, of the size of data dispersion. In the analysis of Chan, Golub and LeVeque (1983), this update algorithm’s error bounds grow with κ\kappa, versus κ2\kappa^2 for the one-pass formula; two-pass is better still, with a first-order term independent of κ\kappa.

InteractiveVariance that turns negative
  • naive
  • two passes
  • Welford
  • prediction u·M²/σ²
  • negative naive variance in …
  • zero error is drawn at 10−1810^{-18}; above 10410^4, clipped
M = 1.0e9
Format
Exact variance of stored data…
Naive x2‾−xˉ2\overline{x^2} - \bar{x}^2…
Two passes…
Welford…
Relative error, naive…
Relative error, Welford…
200 prices xi=fl⁡(M+zi)x_i = \operatorname{fl}(M + z_i) with zi∼N(0,1)z_i \sim \Normal(0, 1). Left: the series minus its level MM. Right: each method's relative error versus exact variance of stored data (integer arithmetic) across the range of MM, with naive-formula prediction uM2/σ2uM^2/\sigma^2. Start at M=109M = 10^9: naive variance is negative. Lower MM until the naive formula recovers digits and compare with the dashed line. Switch to float32: where does it begin to fail, and what happens to the data themselves at M=106M = 10^6?

The figure confirms the analysis: naive-formula error follows uM2/σ2uM^2/\sigma^2, slope 2 on a log scale, and no digits remain from M≈108M \approx 10^8 in float64 or M≈4000M \approx 4000 in float32; beyond that, naive variance is a multiple of double spacing near M2M^2 and negative at many swept values. Welford error grows with slope 1, like κ\kappa, while two-pass error barely moves until enormous MM values. In float32 two-pass loses this advantage: calculated mean carries error εm\eps_m of up to about nuMnuM units, and 1n∑(xi−m^)2=σ2+εm2\frac{1}{n}\sum(x_i - \hat{m})^2 = \sigma^2 + \eps_m^2 exactly, so that error enters squared. The “corrected” two-pass version analyzed by Chan, Golub and LeVeque subtracts term (∑i(xi−m^))2/n\big(\sum_i(x_i - \hat{m})\big)^2/n, estimating precisely nεm2n\eps_m^2. In float32 with M=106M = 10^6 a different phenomenon appears: data themselves have been quantized to multiples of 2−42^{-4}, because 10610^6 needs 20 of 24 bits. No algorithm recovers what was lost when storing data; subtract a reference level before converting to float32.

Batch merging

Parallel or block processing requires combining summaries (nA,mA,MA)(n_A, m_A, M_A) and (nB,mB,MB)(n_B, m_B, M_B). Chan, Golub and LeVeque (1979) gave the formula: with n=nA+nBn = n_A + n_B and δ=mB−mA\delta = m_B - m_A,

m=mA+δnBn,M=MA+MB+δ2nAnBn.m = m_A + \delta\frac{n_B}{n}, \qquad M = M_A + M_B + \delta^2\frac{n_An_B}{n}.

The proof uses the same decomposition: ∑i∈A(xi−m)2=MA+nA(mA−m)2\sum_{i \in A}(x_i - m)^2 = M_A + n_A(m_A - m)^2 and likewise for BB, with mA−m=−δnB/nm_A - m = -\delta n_B/n and mB−m=δnA/nm_B - m = \delta n_A/n, so the two extra terms sum to δ2(nAnB2+nBnA2)/n2=δ2nAnB/n\delta^2(n_An_B^2 + n_Bn_A^2)/n^2 = \delta^2 n_An_B/n. Applied on a binary tree of blocks, this is the authors’ pairwise algorithm, the variance analogue of pairwise summation. Covariance combines similarly, with C=CA+CB+δxδynAnB/nC = C_A + C_B + \delta_x\delta_y n_An_B/n, and updates observation by observation with Ck=Ck−1+(xk−mk−1x)(yk−mky)C_k = C_{k-1} + (x_k - m^x_{k-1})(y_k - m^y_k).

[ ]Welford and merging from scratchBrowser
import numpy as np

class Momentos:
    """Media, varianza y covarianza de pares (x, y) en una pasada, con fusión por lotes."""
    def __init__(self):
        self.n, self.mx, self.my, self.Mx, self.My, self.C = 0, 0.0, 0.0, 0.0, 0.0, 0.0

    def actualiza(self, x, y):
        self.n += 1
        dx = x - self.mx
        dy = y - self.my
        self.mx += dx / self.n
        self.my += dy / self.n
        self.Mx += dx * (x - self.mx)
        self.My += dy * (y - self.my)
        self.C += dx * (y - self.my)
        return self

    def fusiona(self, o):
        r = Momentos()
        r.n = self.n + o.n
        if r.n == 0:
            return r
        dx, dy = o.mx - self.mx, o.my - self.my
        f = self.n * o.n / r.n
        r.mx = self.mx + dx * o.n / r.n
        r.my = self.my + dy * o.n / r.n
        r.Mx = self.Mx + o.Mx + dx * dx * f
        r.My = self.My + o.My + dy * dy * f
        r.C = self.C + o.C + dx * dy * f
        return r

    def var_x(self): return self.Mx / self.n
    def cov(self): return self.C / self.n

rng = np.random.default_rng(4)
x, y = rng.normal(size=1000), rng.normal(size=1000)
y = 0.6 * x + 0.8 * y
uno = Momentos()
for a, b in zip(x, y):
    uno.actualiza(a, b)
bloques = []
for k in range(0, 1000, 128):                       # lotes de 128, fusionados al final
    m = Momentos()
    for a, b in zip(x[k:k + 128], y[k:k + 128]):
        m.actualiza(a, b)
    bloques.append(m)
total = Momentos()
for m in bloques:
    total = total.fusiona(m)
print("var: Welford", uno.var_x(), "  por lotes", total.var_x(), "  np.var", np.var(x))
print("cov: Welford", uno.cov(), "  por lotes", total.cov(), "  np.cov", np.cov(x, y, bias=True)[0, 1])

All three forms agree to the last digits. Now the motivating experiment: simulated asset returns and prices, processed in blocks as they might arrive from a feed.

[ ]Streaming prices and returnsBrowser
import numpy as np
from fractions import Fraction

def var_exacta(v):
    q = [Fraction(float(t)) for t in v]
    m = sum(q) / len(q)
    return float(sum((t - m) ** 2 for t in q) / len(q))

def var_ingenua(v):
    return np.mean(v * v) - np.mean(v) ** 2

def var_welford_bloques(v, tam=250):
    total = Momentos()
    for k in range(0, len(v), tam):
        m = Momentos()
        for a in v[k:k + tam]:
            m.actualiza(a, 0.0)
        total = total.fusiona(m)
    return total.var_x()

rng = np.random.default_rng(5)
r = rng.normal(5e-4, 0.01, size=2000)                   # rendimientos diarios
print("rendimientos: κ ≈", f"{np.sqrt(1 + np.mean(r)**2 / np.var(r)):.3f}")
ex = var_exacta(r)
for nombre, f in [("ingenua", var_ingenua), ("np.var", np.var), ("Welford por bloques", var_welford_bloques)]:
    print(f"   {nombre:20s} error relativo {abs(f(r) - ex) / ex:.1e}")

print("\nprecios M + ruido con σ = 1:")
print("     M       κ          ingenua     np.var      Welford por bloques")
z = rng.normal(0, 1, size=2000)
for M in [1e2, 1e4, 1e6, 1e8, 1e10]:
    p = M + z
    ex = var_exacta(p)
    kappa = np.sqrt(1 + np.mean(p) ** 2 / ex)
    errs = [abs(f(p) - ex) / ex for f in (var_ingenua, np.var, var_welford_bloques)]
    print(f"   1e{int(np.log10(M)):<3}  {kappa:.1e}   " + "   ".join(f"{e:.1e}" for e in errs))

For returns, κ=1.003\kappa = 1.003 (mean is far smaller than standard deviation) and all three formulas agree to the last digit: the naive formula is not always bad, but is bad when κ\kappa is large. For prices, each row multiplies MM and κ\kappa by 100, and naive-formula error multiplies by about 10410^4, i.e. κ2\kappa^2: 4.0×10−124.0\times 10^{-12} with M=102M = 10^2, 1.5×10−41.5\times 10^{-4} with M=106M = 10^6, no digits with M=108M = 10^8 and error 1.6×1041.6\times 10^4 times variance with M=1010M = 10^{10}. Block Welford grows like κ\kappa, about a hundredfold per row, from 8.6×10−168.6\times 10^{-16} to 2.9×10−72.9\times 10^{-7}, as Chan, Golub and LeVeque predict. np.var, which makes two passes, is most accurate: worst error 3.2×10−133.2\times 10^{-13} with M=1010M = 10^{10}. With all data use two passes; for streaming, Welford. Practically, if using the one-pass formula for price variances, volatility or network normalization, first subtract a reference level or use Welford.

Library functions that exist for this reason

All of this is already implemented and tested in libraries. Knowing that they exist and why is half the work.

FunctionWhat it avoids
np.log1p(x), np.expm1(x)forming 1+x1 + x or subtracting ex−1e^x - 1 when x≈0x \approx 0
np.hypot(x, y)overflow of x2+y2x^2 + y^2 in x2+y2\sqrt{x^2 + y^2}
scipy.special.logsumexpoverflow of ∑exi\sum e^{x_i}; supports weights and signs
scipy.special.xlogy(x, y), xlog1pyentropy’s NaN 0⋅log⁡0=0 \cdot \log 0 = (returns 0 if x=0x = 0)
scipy.special.log_softmax, log_expitlog⁡0\log 0 from first computing probability
torch.nn.functional.log_softmax, cross_entropythe same in PyTorch; cross_entropy accepts logits
torch.nn.functional.logsigmoid, softplus, BCEWithLogitsLosssigmoid followed by logarithm
math.fsum, np.sumrecursive summation (exact and pairwise respectively)
np.var, np.stdone-pass formula (they use two passes)
[ ]Library functions in actionBrowser
import numpy as np
from scipy import special

x = 1e-10
print("log(1 + x):", np.log(1 + x), "   log1p(x):", np.log1p(x), "   (exacto ≈ 9.9999999995e-11)")
print("exp(x) − 1:", np.exp(x) - 1, "   expm1(x):", np.expm1(x))
with np.errstate(all="ignore"):
    g = np.float64(1e200)
    print("sqrt(x² + y²) con x = y = 1e200:", np.sqrt(g * g + g * g), "   hypot:", np.hypot(g, g))
    print("0·log 0:", 0.0 * np.log(0.0), "   xlogy(0, 0):", special.xlogy(0.0, 0.0))
z = np.array([1000.0, 999.0, 990.0])
print("log_softmax de SciPy:", special.log_softmax(z), "   log_expit(−800):", special.log_expit(-800.0))

The same names exist in PyTorch, where they matter most because models are trained in float16 or bfloat16:

import torch
import torch.nn.functional as F

z = torch.tensor([[12.0, 10.0, 3.0, -2.0, -20.0]], dtype=torch.float16)
y = torch.tensor([4])
F.cross_entropy(z.float(), y)                  # recibe logits: internamente log_softmax + nll_loss
torch.log(torch.softmax(z, dim=-1))[0, 4]      # MAL: el softmax de la clase 4 se redondea a 0 y log 0 = -inf
F.log_softmax(z.float(), dim=-1)[0, 4]         # BIEN
F.binary_cross_entropy_with_logits(z[:, 0].float(), torch.ones(1))   # no sigmoid + BCELoss

Nonassociativity and reproducibility

In floating point, (a+b)+c(a + b) + c and a+(b+c)a + (b + c) are distinct operations with distinct roundings: addition is not associative. A sum of nn numbers has many possible orders and generally each gives a slightly different result. This directly affects parallel code.

A parallel reduction distributes the vector among pp threads, each summing its part, then combines partial sums. The tree depends on pp, block size and, if partials combine through atomic operations (atomicAdd in CUDA), the order in which threads finish, decided by the scheduler each run. Parallel reductions are correct algorithms, but floating-point results depend on the tree.

[ ]The same vector, another treeBrowser
import math
import numpy as np

print("(0.1 + 0.2) + 0.3 =", (0.1 + 0.2) + 0.3, "   0.1 + (0.2 + 0.3) =", 0.1 + (0.2 + 0.3))

rng = np.random.default_rng(6)
x = rng.normal(size=2**20).astype(np.float32)

def reduccion_paralela(x, hilos):
    parciales = np.cumsum(x.reshape(hilos, -1), axis=1)[:, -1]   # cada hilo suma su trozo en orden
    return np.cumsum(parciales)[-1]                              # y se combinan los parciales

resultados = {p: reduccion_paralela(x, p) for p in [1, 2, 4, 8, 16, 32, 64, 128, 256, 1024]}
for p, s in resultados.items():
    print(f"{p:5d} hilos: {s:.9g}")
distintos = len(set(float(s) for s in resultados.values()))
ulp = np.spacing(np.float32(abs(np.sum(x.astype(np.float64)))))
vals = np.array([float(s) for s in resultados.values()])
print("valores distintos:", distintos, "de", len(resultados), "   ulp del resultado:", ulp,
      "   dispersión:", round((vals.max() - vals.min()) / float(ulp)), "ulp")
exacta = math.fsum(x.astype(float))
print("error de 1 hilo y de 1024 hilos, en ulp:", round((float(resultados[1]) - exacta) / float(ulp)), round((float(resultados[1024]) - exacta) / float(ulp)),
      "   np.sum (por pares):", round((float(np.sum(x)) - exacta) / float(ulp)))
print("permutar los datos cambia la suma recursiva:", np.cumsum(rng.permutation(x))[-1] != np.cumsum(x)[-1])

# Acumular en float16: la suma de unos se estanca
unos = np.ones(5000, dtype=np.float16)
print("\nsuma de 5000 unos en float16:", np.cumsum(unos, dtype=np.float16)[-1], "   en float32:", np.cumsum(unos, dtype=np.float32)[-1])

The ten “thread counts” give ten different results for the same vector, spread over 280 ulps: one thread has error 7 ulps and 1024 has 27, while np.sum (pairwise) stays at 4. All are equally legitimate and within the bound, none matching another. On a GPU, with much more balanced reduction trees, differences usually remain in the last bits, but the phenomenon is the same. This is what happens when identical training runs diverge in the last bit and then, due to training’s chaotic nature, much more.

The last line is another warning: in float16 a sum of ones stops at 2048. From 2112^{11} onward float16 spacing is 2, so 2048+1=20492048 + 1 = 2049 lies exactly halfway between 2048 and 2050 and ties to even chooses 2048. In bfloat16 with 8 significand bits, stagnation occurs at 28=2562^8 = 256. Hence metrics, accumulated losses and accumulated gradients are stored in float32 even when the model computes at reduced precision.

Bitwise reproducibility is possible, but must be requested: fix reduction order (same thread and block count, no atomics), enable torch.use_deterministic_algorithms(True) in PyTorch (which raises an error if an operation lacks a deterministic version), and set CUBLAS_WORKSPACE_CONFIG with cuBLAS. See GPU nondeterminism and GPU reductions for detail.

Common mistakes

Exercises

NumericDigits lost in 1 − cos x
You compute 1−cos⁡(10−4)1 - \cos(10^{-4}) in float64 with correctly rounded cos⁡\cos. Approximately how many significant decimal digits are lost from float64's 16?
NumericBound for a million summands
You recursively sum n=106n = 10^6 float32 numbers. Calculate worst-case bound constant γn−1=(n−1)u/(1−(n−1)u)\gamma_{n-1} = (n - 1)u/(1 - (n - 1)u) with u=2−24u = 2^{-24}. Give three significant digits.
NumericThe stagnant accumulator
You repeatedly add 11 in a float16 accumulator (round to nearest, ties to even), starting at 0. At what value does it remain forever?
QuizThe small root
You want the smaller-magnitude root of x2+bx+cx^2 + bx + c with b=108b = 10^8 and c=1c = 1, in float64. Which expressions calculate it with relative error of a few uu?

More than one answer may be correct.

QuizWhere is there cancellation?
Which expressions lose many floating-point digits in the stated regime?

More than one answer may be correct.

QuizKahan with -ffast-math
You compile Kahan summation in C with -O3 -ffast-math and its error matches recursive summation. What happened?
QuizThe last GPU bit
You sum the same float32 tensor twice on a GPU with torch.sum and obtain results differing in the last bit. What is the most likely cause?
ProofBounds for recursive and pairwise summation
Prove: Recursive summation s^1=x1\hat{s}_1 = x_1, s^k=fl⁡(s^k−1+xk)\hat{s}_k = \operatorname{fl}(\hat{s}_{k-1} + x_k) of x1,…,xn∈Fx_1, \dots, x_n \in \mathbb{F} satisfies ∣s^n−sn∣≤γn−1∑i∣xi∣\abs{\hat{s}_n - s_n} \le \gamma_{n-1}\sum_i\abs{x_i} if (n−1)u<1(n - 1)u < 1; pairwise summation of n=2kn = 2^k numbers satisfies ∣s^−s∣≤γk∑i∣xi∣\abs{\hat{s} - s} \le \gamma_k\sum_i\abs{x_i}.
0
Use the standard model (without overflow or underflow) and lemma ∏i=1m(1+δi)=1+θm\prod_{i=1}^m(1 + \delta_i) = 1 + \theta_m, ∣θm∣≤γm\abs{\theta_m} \le \gamma_m.

Step 1 of 4. How do you write step kk under the standard model?

Codelog(1 − exp(−a)) across the range
Implement log1mexp(a) =log⁡(1−e−a)= \log(1 - e^{-a}) for a>0a > 0, accepting a scalar or NumPy array with relative error of a few uu throughout the range from a=10−20a = 10^{-20} to a=700a = 700. Use Mächler's rule: log⁡(−expm1⁡(−a))\log(-\operatorname{expm1}(-a)) if a≤log⁡2a \le \log 2 and log1p⁡(−e−a)\operatorname{log1p}(-e^{-a}) if a>log⁡2a > \log 2. Tests compare against a high-precision mpmath reference.
import numpy as np

def log1mexp(a):
  a = np.asarray(a, dtype=float)
  return np.log(1 - np.exp(-a))
Shift+Enter to run
CodeNeumaier versus Kahan
Implement neumaier(xs), Neumaier compensated summation over a list of Python floats (float64), and define caso_dificil, a list for which Kahan summation (provided as kahan) differs from math.fsum and yours equals math.fsum exactly. Hint for the case: Kahan's weakness is a summand whose magnitude exceeds the accumulated sum.
import math

def kahan(xs):
  s = c = 0.0
  for x in xs:
      y = x - c
      t = s + y
      c = (t - s) - y
      s = t
  return s

def neumaier(xs):
  # tu código: suma y corrección, comparando |s| con |x| en cada paso
  return sum(xs)

caso_dificil = [1.0, 2.0, 3.0]
Shift+Enter to run

Summary

Key idea
Each floating-point operation is exact up to factor (1+δ)(1 + \delta) with ∣δ∣≤u\abs{\delta} \le u; disasters come from formulas amplifying those errors. Cancellation, long sums and exponentials are addressed by rewriting formulas, not adding bits.
  • Standard model. fl⁡(x∘y)=(x∘y)(1+δ)\operatorname{fl}(x \circ y) = (x \circ y)(1 + \delta) with ∣δ∣≤u=2−p\abs{\delta} \le u = 2^{-p}; kk chained factors combine into 1+θk1 + \theta_k with ∣θk∣≤γk=ku/(1−ku)\abs{\theta_k} \le \gamma_k = ku/(1 - ku).
  • Catastrophic cancellation. Subtracting nearly equal numbers is exact (Sterbenz) but reveals existing errors: relative error multiplies by (∣a∣+∣b∣)/∣a−b∣(\abs{a} + \abs{b})/\abs{a - b}. Use identities: 2sin⁡2(x/2)2\sin^2(x/2), c/qc/q in the quadratic formula, log1p, expm1, (x−y)(x+y)(x - y)(x + y).
  • Sums. Recursive: γn−1∑∣xi∣\gamma_{n-1}\sum\abs{x_i}. Pairwise: γ⌈log⁡2n⌉∑∣xi∣\gamma_{\lceil\log_2 n\rceil}\sum\abs{x_i}, at the same cost (what np.sum does along the fast axis). Kahan and Neumaier: (2u+O(nu2))∑∣xi∣(2u + \bigO(nu^2))\sum\abs{x_i}. math.fsum: exact.
  • Exponentials. Subtract the maximum before exponentiation (log-sum-exp, softmax) and never form a probability only to take its logarithm: log_softmax, cross_entropy from logits, softplus and logsigmoid with max⁡(x,0)+log1p⁡(e−∣x∣)\max(x, 0) + \operatorname{log1p}(e^{-\abs{x}}).
  • Variance. x2‾−xˉ2\overline{x^2} - \bar{x}^2 loses log⁡10κ2\log_{10}\kappa^2 digits; Welford updates mean and centered sum of squares in one pass, and Chan, Golub and LeVeque merging combines batches.
  • Reproducibility. Addition is not associative; parallel reductions change last bits according to the tree. Accumulate in float32, compare with tolerances and fix order when identical results are required.

These ideas recur throughout the syllabus: attention softmax and its online FlashAttention version (online softmax) apply the log-sum-exp trick by blocks; cross-entropy is calculated from logits; log returns and portfolio variances suffer cancellation; and the next lesson, conditioning and backward stability, precisely separates issues caused by the problem from those caused by the algorithm.