Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

0. Floating-point numbers, cancellation and compensated summation

School of Engineering, Nazarbayev University

On 25 February 1991 a Patriot air-defence battery at Dhahran failed to track an incoming Scud missile. The battery had been running for more than 100 hours; its clock counted tenths of a second in a 24-bit fixed-point register, and the chopped binary value of 0.1 had made the clock 0.34 s0.34\,\mathrm{s} late, enough to move the radar’s range gate about 687 m687\,\mathrm{m} away from the target (US General Accounting Office report IMTEC-92-26, 1992). In 1996 Ariane 5 Flight 501 was lost about 37 s37\,\mathrm{s} after lift-off when a 64-bit floating-point value was converted into a 16-bit signed integer that could not hold it. And in everyday laboratory code, the textbook variance formula x2‾−xˉ2\overline{x^2} - \bar{x}^2 applied to a 1 GPa1\,\mathrm{GPa} pressure signal that fluctuates by a few pascals returns −128 Pa2-128\,\mathrm{Pa^2} instead of +3 Pa2+3\,\mathrm{Pa^2}. This lecture covers Mental Moves 1–4 of engthink: inspecting the bit budget of a floating-point number, compensating the low-order bits lost in a sum (kahan_babuska_sum), keeping centred running moments (welford_streaming_stats) and shifting before exponentiating (stable_logsumexp).

Learning objectives

  1. Decompose 64-bit IEEE-754 floating-point numbers into sign, biased exponent, 52-bit mantissa, and unit-in-the-last-place spacing ulp(x)\mathrm{ulp}(x) via representation_scaling.ieee754_float64_inspect, explaining why floating-point addition violates associativity.

  2. Rescue tiny physical increments from numerical absorption using representation_scaling.kahan_babuska_sum and distinguish symmetric Neumaier/Babuška compensation from classical Kahan summation.

  3. Eliminate catastrophic cancellation in streaming mean and variance calculations across high-offset sensor baselines using representation_scaling.welford_streaming_stats and Chan’s parallel mergeable invariant.

  4. Prevent exponential overflow (inf) and underflow (0.0) in Boltzmann partition functions and softmax likelihoods via the max-shift invariant in representation_scaling.stable_logsumexp.

Time: about 60 min

1. The IEEE-754 binary64 Bit Budget & Breakdown of Associativity

1.1 Anatomy of a 64-Bit Floating-Point Number

A computer cannot store the real line R\mathbb{R} in 64 bits. The IEEE-754 binary64 (float64) standard partitions 64 bits into three fields:

  • 1 sign bit s∈{0,1}s \in \{0, 1\},

  • 11 biased exponent bits E∈{0,1,…,2047}E \in \{0, 1, \dots, 2047\} with bias 1023 (e=E−1023e = E - 1023 for normal numbers 1≤E≤20461 \le E \le 2046),

  • 52 explicit fraction/mantissa bits M∈{0,1,…,252−1}M \in \{0, 1, \dots, 2^{52}-1\} following an implicit leading 1.:

x=(−1)s(1+M252)2E−1023,ulp(x)=2e−52=εmach 2⌊log⁡2∣x∣⌋(1.1)x = (-1)^s \left(1 + \frac{M}{2^{52}}\right) 2^{E - 1023}, \qquad \mathrm{ulp}(x) = 2^{e - 52} = \varepsilon_{\mathrm{mach}}\,2^{\lfloor \log_2 |x| \rfloor} \tag{1.1}

where machine epsilon is εmach=2−52≈2.2204×10−16\varepsilon_{\mathrm{mach}} = 2^{-52} \approx 2.2204 \times 10^{-16}. Notice the fundamental trade-off (Mental Move #1, Inspect the Bit Budget): floating-point spacing ulp(x)\mathrm{ulp}(x) is uniform only within each power-of-two binade [2e,2e+1)[2^e, 2^{e+1}) and doubles every time ∣x∣|x| crosses a power of two. Once ∣x∣=1016∈[253,254)|x| = 10^{16} \in [2^{53}, 2^{54}), ulp(1016)=253−52=2.0\mathrm{ulp}(10^{16}) = 2^{53 - 52} = 2.0, so adding 1.0 falls strictly at or below half an ulp and is absorbed (1e16 + 1.0 == 1e16); addition is then no longer associative, (a+b)+c≠a+(b+c)(a + b) + c \ne a + (b + c).


Demonstration 1: IEEE-754 bit inspection, ULP stairstep and non-associativity
=============================================================================
       Value |      Kind | Sign | Unbiased e |   ULP Spacing |    High Bits (s|exp|mant...)
--------------------------------------------------------------------------------------------
         0.1 |    normal |    0 |         -4 |    1.3878e-17 | 0|01111111011|100110011001...
         1.0 |    normal |    0 |          0 |    2.2204e-16 | 0|01111111111|000000000000...
       1e+16 |    normal |    0 |         53 |    2.0000e+00 | 0|10000110100|000111000011...
        -0.0 |      zero |    1 |      -1022 |   4.9407e-324 | 1|00000000000|000000000000...
      5e-324 | subnormal |    0 |      -1022 |   4.9407e-324 | 0|00000000000|000000000000...
         inf |       inf |    0 |       None |           nan | 0|11111111111|000000000000...

At x = 1e16: ulp(1e16) = 2.0 -> (1e16 + 1.0 == 1e16) is True
Associativity test: ((1e16 + -1e16) + 1.0) = 1.0  !=  (1e16 + (-1e16 + 1.0)) = 0.0
<Figure size 1265x462 with 2 Axes>

Figure 0.1. Spacing of float64 numbers. (a) The unit in the last place, ulp(x)\mathrm{ulp}(x), in units of εmach\varepsilon_{\mathrm{mach}}, doubles at every power of two, so the relative spacing ulp(x)/x\mathrm{ulp}(x)/x (dashed) saws between εmach/2\varepsilon_{\mathrm{mach}}/2 and εmach\varepsilon_{\mathrm{mach}}. (b) Over 33 decades the absolute spacing grows in proportion to ∣x∣|x|; it reaches 1 (dotted) at 252≈4.5×10152^{52} \approx 4.5 \times 10^{15} and 2 at 253, beyond which odd integers cannot be represented.

What Demonstration 1 shows.

  • Binade wobbling: In the left panel, absolute ulp(x)\mathrm{ulp}(x) jumps by 2×2\times at x=1,2,4,8x = 1, 2, 4, 8, causing relative spacing ulp(x)/x\mathrm{ulp}(x)/x to sawtooth between 12εmach\frac{1}{2}\varepsilon_{\mathrm{mach}} (just below a power of two) and εmach\varepsilon_{\mathrm{mach}} (just above a power of two).

  • Integer absorption ceiling: Above 253≈9.007×10152^{53} \approx 9.007 \times 10^{15}, ulp(x)≥2.0\mathrm{ulp}(x) \ge 2.0 — float64 cannot even represent odd integers. Accumulating millions of tiny time-step fluxes onto a large total inventory silently drops low-order bits unless we track the rounding error explicitly.


2. Recovering Lost Increments: Compensated Summation (kahan_babuska_sum)

Suppose we integrate NN small physical flux increments vkv_k atop a large background baseline. In naive left-to-right summation sk=fl(sk−1+vk)s_k = \mathrm{fl}(s_{k-1} + v_k), worst-case error grows as O(Nεmach)∑∣vk∣\mathcal{O}(N \varepsilon_{\mathrm{mach}}) \sum |v_k|. Mental Move #2, Compensate Lost Low-Order Bits (Kahan 1965; Neumaier 1974) recovers the exact rounded-off tail ckc_k using IEEE-754 arithmetic itself. In Neumaier’s symmetric compensated sum:

t=fl(s+vk),c←{c+((s−t)+vk)if ∣s∣≥∣vk∣,c+((vk−t)+s)if ∣s∣<∣vk∣,s←t(2.1)t = \mathrm{fl}(s + v_k), \qquad c \leftarrow \begin{cases} c + ((s - t) + v_k) & \text{if } |s| \ge |v_k|, \\ c + ((v_k - t) + s) & \text{if } |s| < |v_k|, \end{cases} \qquad s \leftarrow t \tag{2.1}

Why does Neumaier check ∣s∣≥∣vk∣|s| \ge |v_k|? Classical Kahan always assumes the running sum ∣s∣|s| is larger than the incoming term ∣vk∣|v_k|; if a giant cancelling term arrives after small increments (such as [1e16, pi, -1e16, e]), classical Kahan loses the low bits of π\pi, whereas Neumaier’s symmetric branch preserves them to machine precision.


Demonstration 2: Naive against Kahan against Neumaier/Babuška compensated summation
===================================================================================
Case A ([1e16] + 8000*[0.125] + [-1e16], exact = 1000.0):
  Naive sum    =     0.000000 (abs error = 1.00e+03)
  Neumaier sum =  1000.000000 (abs error = 0.00e+00)

Case B ([1e16, pi, -1e16, e], exact pi + e = 5.859874482048838):
  Naive sum    = 6.718281828459045 | error = 8.58e-01
  Kahan sum    = 6.718281828459045 | error = 8.58e-01 (fails when |-1e16| >> |s_prev - t|)
  Neumaier sum = 5.859874482048838 | error = 0.00e+00
<Figure size 836x451 with 1 Axes>

Figure 0.2. Relative error of a long sum of small increments on a large baseline, against the stream length NN. Naive left-to-right summation loses about 10-6 of the result; the Neumaier/Babuška compensated sum stays below machine epsilon (dotted) for every NN.

What Demonstration 2 shows.

  • Zero extra memory, O(1)\mathcal{O}(1) state: Neumaier summation adds just one scalar compensation register c_neu and four floating-point operations per sample, yet in Case A it recovers the exact sum 1000 where the naive sum returns 0.

  • Why symmetric branching matters: In Case B, classical Kahan lost 0.8584 (4−π4 - \pi) when -1e16 arrived, whereas Neumaier’s if abs(neu_s) >= abs(fv) check captured the exact rounding residual in c_neu and recovered π+e\pi + e to all printed digits.


3. Catastrophic Variance Cancellation vs. Welford’s Centered Invariant (welford_streaming_stats)

The one-pass identity is often recommended: σ2=x2‾−xˉ2=1N∑xk2−(1N∑xk)2\sigma^2 = \overline{x^2} - \bar{x}^2 = \frac{1}{N}\sum x_k^2 - \left(\frac{1}{N}\sum x_k\right)^2. Suppose an industrial pressure sensor measures small turbulent fluctuations δpk∼1 Pa\delta p_k \sim 1\,\mathrm{Pa} atop a static line pressure P0=109 PaP_0 = 10^9\,\mathrm{Pa} (1 GPa1\,\mathrm{GPa}). Squaring xk=P0+δpkx_k = P_0 + \delta p_k produces P02=1018 Pa2P_0^2 = 10^{18}\,\mathrm{Pa^2}, where ulp(1018)=128.0 Pa2\mathrm{ulp}(10^{18}) = 128.0\,\mathrm{Pa^2}. Every fluctuation δpk2∼1 Pa2\delta p_k^2 \sim 1\,\mathrm{Pa^2} is lost before the subtraction x2‾−xˉ2\overline{x^2} - \bar{x}^2 even happens, and worse, opposing round-to-even errors can make x2‾−xˉ2\overline{x^2} - \bar{x}^2 strictly negative.

Mental Move #4, Maintain Centered Running Moments (Welford 1962) updates the running mean μk\mu_k and sum of squared deviations M2,k=∑i=1k(xi−μk)2M_{2,k} = \sum_{i=1}^k (x_i - \mu_k)^2 in a single pass via the exact algebraic recurrence:

δk=xk−μk−1,μk=μk−1+δkk,M2,k=M2,k−1+δk(xk−μk)≥0(3.1)\delta_k = x_k - \mu_{k-1}, \qquad \mu_k = \mu_{k-1} + \frac{\delta_k}{k}, \qquad M_{2,k} = M_{2,k-1} + \delta_k (x_k - \mu_k) \ge 0 \tag{3.1}

Because (xk−μk−1)(x_k - \mu_{k-1}) and (xk−μk)=k−1k(xk−μk−1)(x_k - \mu_k) = \frac{k-1}{k}(x_k - \mu_{k-1}) always share the same sign, every increment added to M2,kM_{2,k} is guaranteed non-negative in IEEE-754 arithmetic.


Demonstration 3: Negative textbook variance (-128 Pa^2) against Welford streaming invariant
===========================================================================================
4-Sample 1 GPa Sensor Burst [1e9+8, 1e9+8, 1e9+8, 1e9+12] (Exact var_pop = +3.0 Pa^2):
  Textbook E[x^2] - E[x]^2 = -128.000000 Pa^2  <-- negative variance
  Welford streaming var_pop = +3.000000000000000 Pa^2

Baseline C [Pa] |    Naive var_pop |  Welford var_pop |  Naive RelErr | Welford RelErr
--------------------------------------------------------------------------------------
        1.0e+00 |         1.002000 |   1.002000000000 |      1.06e-14 |       3.55e-15
        1.0e+01 |         1.002000 |   1.002000000001 |      5.21e-14 |       5.11e-13
        1.0e+02 |         1.002000 |   1.001999999999 |      8.66e-12 |       4.92e-13
        1.0e+03 |         1.002000 |   1.001999999991 |      2.00e-09 |       8.67e-12
        1.0e+04 |         1.002000 |   1.002000000188 |      2.57e-08 |       1.88e-10
        1.0e+05 |         1.001999 |   1.002000002956 |      1.10e-06 |       2.95e-09
        1.0e+06 |         1.002563 |   1.002000019769 |      5.62e-04 |       1.97e-08
        1.0e+07 |         1.000000 |   1.001999577380 |      2.00e-03 |       4.22e-07
        1.0e+08 |        -2.000000 |   1.001999345055 |      3.00e+00 |       6.54e-07
        1.0e+09 |       896.000000 |   1.002000651853 |      8.93e+02 |       6.51e-07
<Figure size 836x451 with 1 Axes>

Figure 0.3. Relative error of the population variance when a constant offset CC is added to the data. The one-pass formula x2‾−xˉ2\overline{x^2} - \bar{x}^2 loses accuracy as κ2εmach\kappa^2 \varepsilon_{\mathrm{mach}}, with κ=C/σ\kappa = C/\sigma, and has no correct digit left at C=108 PaC = 10^8\,\mathrm{Pa}; Welford’s recurrence loses only as κεmach\kappa \varepsilon_{\mathrm{mach}}.

What Demonstration 3 shows.

  • Squared condition-number blowup: Adding baseline CC gives data condition number κ=C/σ\kappa = C / \sigma. Squaring the raw samples squares the condition number to κ2=(C/σ)2\kappa^2 = (C/\sigma)^2, losing 2log⁡10(C/σ)2 \log_{10}(C/\sigma) digits. At C=108 PaC = 10^8\,\mathrm{Pa}, 2×8=162 \times 8 = 16 digits are lost (the naive variance is -2, a relative error of 3), whereas Welford subtracts the running mean before multiplying, losing at most κεmach∼10−7\kappa \varepsilon_{\mathrm{mach}} \sim 10^{-7} at C=109 PaC = 10^9\,\mathrm{Pa}.


4. Overflow & Underflow Immunity via Max-Shift (stable_logsumexp)

In statistical mechanics (canonical partition function Z=∑ie−βEiZ = \sum_i e^{-\beta E_i}), Bayesian log-evidence, and neural-network cross-entropy, float64 math.exp(z) overflows to +inf for z>709.78z > 709.78 and underflows to 0.0 for z<−745.13z < -745.13. Mental Move #3, Shift Before You Exponentiate (representation_scaling.stable_logsumexp) factors out m=max⁡izim = \max_i z_i:

log⁡∑i=1nezi=m+log⁡∑i=1nezi−m,pi=ezi−m∑j=1nezj−m(4.1)\log \sum_{i=1}^n e^{z_i} = m + \log \sum_{i=1}^n e^{z_i - m}, \qquad p_i = \frac{e^{z_i - m}}{\sum_{j=1}^n e^{z_j - m}} \tag{4.1}

Because max⁡i(zi−m)=0\max_i (z_i - m) = 0, the largest exponential term is identically e0=1.0e^0 = 1.0, guaranteeing 1≤∑iezi−m≤n1 \le \sum_i e^{z_i - m} \le n — so neither overflow nor total underflow can ever occur.


Demonstration 4: Boltzmann partition functions and softmax under +/-1000 log-weight extremes
============================================================================================
   Shift c |  Naive log(sum(exp)) |     Stable LogSumExp |   LSE(z+c) - c Error |  Max |p - p_ref|
--------------------------------------------------------------------------------------------------
   -1200.0 |                 -inf |   -1198.378241722773 |             5.55e-14 |         1.02e-14
    -800.0 |                 -inf |    -798.378241722773 |             5.82e-14 |         1.02e-14
       0.0 |   1.6217582772270007 |       1.621758277227 |             0.00e+00 |         0.00e+00
     800.0 |                  inf |     801.621758277227 |             5.82e-14 |         1.02e-14
    1200.0 |                  inf |    1201.621758277227 |             5.55e-14 |         1.02e-14

Exact shift equivariance LSE(z + c) == c + LSE(z) and defensive guards verified

Inside the algorithm

We inspect the pure-Python/NumPy implementations of representation_scaling.kahan_babuska_sum and representation_scaling.welford_streaming_stats, and then build the parallel, mergeable variance update of Chan, Golub & LeVeque (1983) (manual_chan_parallel_welford). Sequential Welford processes one sample at a time, which looks inherently serial, yet Chan proved that two arbitrary summary tuples (nA,μA,M2,A)(n_A, \mu_A, M_{2,A}) and (nB,μB,M2,B)(n_B, \mu_B, M_{2,B}) computed independently on separate shards can be merged exactly, apart from rounding, via:

δ=μB−μA,μAB=μA+δ nBnA+nB,M2,AB=M2,A+M2,B+δ2 nAnBnA+nB(5.1)\delta = \mu_B - \mu_A, \qquad \mu_{AB} = \mu_A + \delta\,\frac{n_B}{n_A + n_B}, \qquad M_{2,AB} = M_{2,A} + M_{2,B} + \delta^2\,\frac{n_A n_B}{n_A + n_B} \tag{5.1}

Check against the library


Inside the algorithm: Kahan/Neumaier, Welford and Chan's parallel mergeable variance
====================================================================================
def kahan_babuska_sum(values: np.ndarray) -> dict:
    """Compare naive left-to-right float64 summation against Kahan (1965) and Neumaier/Babuska compensated sums."""
    arr = np.asarray(values, dtype=np.float64).ravel()

    naive_s = 0.0
    for v in arr:
        naive_s = float(naive_s + float(v))

    # Classical Kahan compensated summation:
    kahan_s = 0.0
    c_kahan = 0.0
    for v in arr:
        y = float(v) - c_kahan
        t = kahan_s + y
        c_kahan = (t - kahan_s) - y
        kahan_s = t

    # Neumaier (1974) / Babuska symmetric compensation (handles |v| > |sum| cleanly):
    neu_s = 0.0
    c_neu = 0.0
    for v in arr:
        fv = float(v)
        t = neu_s + fv
        if abs(neu_s) >= abs(fv):
            c_neu += (neu_s - t) + fv
        else:
            c_neu += (fv - t) + neu_s
        neu_s = t
    neumaier_total = neu_s + c_neu

    exact_ref = math.fsum(float(v) for v in arr)
    return {
        "naive_sum": naive_s,
        "kahan_sum": kahan_s,
        "neumaier_sum": neumaier_total,
        "exact_fsum": exact_ref,
        "naive_abs_error": abs(naive_s - exact_ref),
        "neumaier_abs_error": abs(neumaier_total - exact_ref),
    }

def welford_streaming_stats(values: np.ndarray) -> dict:
    """Compute single-pass Welford (1962) streaming mean/variance vs. cancellation-prone E[x^2] - E[x]^2."""
    arr = np.asarray(values, dtype=np.float64).ravel()
    if arr.size == 0:
        raise ValueError("Require at least one sample.")

    n = 0
    mean = 0.0
    m2 = 0.0
    sum_x = 0.0
    sum_x2 = 0.0
    for v in arr:
        fv = float(v)
        n += 1
        delta = fv - mean
        mean += delta / n
        delta2 = fv - mean
        m2 += delta * delta2
        sum_x += fv
        sum_x2 += fv * fv

    var_pop = m2 / n
    var_samp = m2 / (n - 1) if n > 1 else 0.0
    naive_mean = sum_x / n
    naive_var_pop = (sum_x2 / n) - (naive_mean * naive_mean)
    return {
        "count": n,
        "mean": mean,
        "variance_pop": var_pop,
        "variance_sample": var_samp,
        "std_sample": math.sqrt(max(0.0, var_samp)),
        "naive_formula_variance_pop": naive_var_pop,
    }

Full-stream Welford var_pop : 3.111889208691188
2-Shard Chan merged var_pop : 3.111889162103898
Textbook naive var_pop      : -704.000000000000000
Abs diff |Chan - Welford|   : 4.66e-08

Exercises

Worked solutions are in 00_solutions.ipynb. The cell below the list is a short self-check to start from.

  1. Verify a result. Prove via fractions.Fraction(0.1) that IEEE-754 0.1 exceeds 110\frac{1}{10} by exactly +2−55/5+2^{-55}/5, and compare cumulative clock error over 100 hours (3,600,0003{,}600{,}000 ticks of 0.1 s0.1\,\mathrm{s}) across Patriot’s 24-bit signed fixed-point register (1 sign bit + 23 fractional bits), float64 t += 0.1 accumulation, and integer tick counting k * 0.1.

  2. Find how it fails. Quantify catastrophic digit loss in the textbook quadratic root (−b−b2−4ac)/(2a)(-b - \sqrt{b^2 - 4ac})/(2a) for x2+bx+1=0x^2 + b x + 1 = 0 across b∈[−104,−109]b \in [-10^4, -10^9] relative to Vieta’s Citardauq invariant x2=c/(ax1)x_2 = c / (a x_1), and audit naive np.log(np.sum(np.exp(z))) at ±800\pm 800.

  3. Implement it yourself. Implement compensated_dot_and_pairwise_sum(a, b) returning np_dot, pairwise_dot, dot2_compensated, and exact_dot using recursive pairwise product summation and Ogita–Rump–Oishi’s error-free Dot2 transformation (two_prod via Veltkamp 227+12^{27}+1 splitting and Knuth two_sum). Verify on an ill-conditioned dot product with condition number κ>1013\kappa > 10^{13}.


Self-check for the exercises
============================
All checks passed.