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 late, enough to move the radar’s range gate about away from the target (US General Accounting Office report IMTEC-92-26, 1992). In 1996 Ariane 5 Flight 501 was lost about 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 applied to a pressure signal that fluctuates by a few pascals returns instead of . 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¶
Decompose 64-bit IEEE-754 floating-point numbers into sign, biased exponent, 52-bit mantissa, and unit-in-the-last-place spacing via
representation_scaling.ieee754_float64_inspect, explaining why floating-point addition violates associativity.Rescue tiny physical increments from numerical absorption using
representation_scaling.kahan_babuska_sumand distinguish symmetric Neumaier/Babuška compensation from classical Kahan summation.Eliminate catastrophic cancellation in streaming mean and variance calculations across high-offset sensor baselines using
representation_scaling.welford_streaming_statsand Chan’s parallel mergeable invariant.Prevent exponential overflow (
inf) and underflow (0.0) in Boltzmann partition functions and softmax likelihoods via the max-shift invariant inrepresentation_scaling.stable_logsumexp.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))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 in 64 bits. The IEEE-754 binary64 (float64) standard partitions 64 bits into three fields:
1 sign bit ,
11 biased exponent bits with bias 1023 ( for normal numbers ),
52 explicit fraction/mantissa bits following an implicit leading
1.:
where machine epsilon is . Notice the fundamental trade-off (Mental Move #1, Inspect the Bit Budget): floating-point spacing is uniform only within each power-of-two binade and doubles every time crosses a power of two. Once , , 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, .
heading("Demonstration 1: IEEE-754 bit inspection, ULP stairstep and non-associativity")
probe_vals = [0.1, 1.0, 1.0e16, -0.0, 2.0 ** (-1074), math.inf]
print(f"{'Value':>12s} | {'Kind':>9s} | {'Sign':>4s} | {'Unbiased e':>10s} | {'ULP Spacing':>13s} | {'High Bits (s|exp|mant...)':>28s}")
print("-" * 92)
for val in probe_vals:
info = representation_scaling.ieee754_float64_inspect(val)
b64 = info["bitstring_64"]
pretty_bits = f"{b64[0]}|{b64[1:12]}|{b64[12:24]}..."
e_str = str(info["unbiased_exponent"])
print(f"{str(val):>12s} | {info['kind']:>9s} | {info['sign_bit']:4d} | {e_str:>10s} | {info['ulp']:13.4e} | {pretty_bits:>28s}")
# Demonstrate absorption at 1e16 (where ulp = 2.0) and violation of (a + b) + c == a + (b + c):
ulp_1e16 = representation_scaling.ieee754_float64_inspect(1.0e16)["ulp"]
lhs_assoc = (1.0e16 + (-1.0e16)) + 1.0
rhs_assoc = 1.0e16 + (-1.0e16 + 1.0)
print(f"\nAt x = 1e16: ulp(1e16) = {ulp_1e16:.1f} -> (1e16 + 1.0 == 1e16) is {1.0e16 + 1.0 == 1.0e16}")
print(f"Associativity test: ((1e16 + -1e16) + 1.0) = {lhs_assoc:.1f} != (1e16 + (-1e16 + 1.0)) = {rhs_assoc:.1f}")
x_dense = np.linspace(0.5, 8.0, 600)
ulps_dense = np.array([representation_scaling.ieee754_float64_inspect(float(v))["ulp"] for v in x_dense])
x_wide = 10.0 ** np.linspace(-15, 18, 200)
ulps_wide = np.array([representation_scaling.ieee754_float64_inspect(float(v))["ulp"] for v in x_wide])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.2))
ax1.step(x_dense, ulps_dense / (2.0 ** -52), where="post", color="#2166AC", lw=2.1, label=r"$\mathrm{ulp}(x) / \varepsilon_{\mathrm{mach}}$")
ax1.plot(x_dense, ulps_dense / x_dense / (2.0 ** -52), color="#C0392B", lw=1.6, ls="--", label=r"Relative spacing $(\mathrm{ulp}(x)/x)/\varepsilon_{\mathrm{mach}}$")
ax1.set_xlabel(r"Magnitude $x$")
ax1.set_ylabel(r"Normalized spacing (units of $\varepsilon_{\mathrm{mach}} = 2^{-52}$)")
ax1.set_title("Spacing of float64 numbers near 1")
ax1.legend(fontsize=8.2)
ax2.loglog(x_wide, ulps_wide, color="#2E8B57", lw=2.2, label=r"Exact $\mathrm{ulp}(x)$")
ax2.axhline(1.0, color="gray", ls=":", lw=1.4, label=r"Unit gap $\mathrm{ulp} = 1.0$ ($|x| \approx 4.5 \times 10^{15}$)")
ax2.set_xlabel(r"Magnitude $|x|$")
ax2.set_ylabel(r"Absolute gap $\mathrm{ulp}(x)$")
ax2.set_title("Absolute spacing over 33 decades")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
assert ulp_1e16 == 2.0
assert lhs_assoc == 1.0 and rhs_assoc == 0.0
assert representation_scaling.ieee754_float64_inspect(2.0 ** -1074)["kind"] == "subnormal"
assert representation_scaling.ieee754_float64_inspect(-0.0)["sign_bit"] == 1
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 0.1. Spacing of float64 numbers. (a) The unit in the last place, , in units of , doubles at every power of two, so the relative spacing (dashed) saws between and . (b) Over 33 decades the absolute spacing grows in proportion to ; it reaches 1 (dotted) at and 2 at 253, beyond which odd integers cannot be represented.
What Demonstration 1 shows.
Binade wobbling: In the left panel, absolute jumps by at , causing relative spacing to sawtooth between (just below a power of two) and (just above a power of two).
Integer absorption ceiling: Above , —
float64cannot 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 small physical flux increments atop a large background baseline. In naive left-to-right summation , worst-case error grows as . Mental Move #2, Compensate Lost Low-Order Bits (Kahan 1965; Neumaier 1974) recovers the exact rounded-off tail using IEEE-754 arithmetic itself. In Neumaier’s symmetric compensated sum:
Why does Neumaier check ? Classical Kahan always assumes the running sum is larger than the incoming term ; if a giant cancelling term arrives after small increments (such as [1e16, pi, -1e16, e]), classical Kahan loses the low bits of , whereas Neumaier’s symmetric branch preserves them to machine precision.
heading("Demonstration 2: Naive against Kahan against Neumaier/Babuška compensated summation")
# Case A: 8,000 tiny 0.125 increments sandwiched between +1e16 and -1e16 (exact sum = 1000.0):
stream_swallowed = np.array([1.0e16] + [0.125] * 8000 + [-1.0e16], dtype=np.float64)
res_swal = representation_scaling.kahan_babuska_sum(stream_swallowed)
print("Case A ([1e16] + 8000*[0.125] + [-1e16], exact = 1000.0):")
print(f" Naive sum = {res_swal['naive_sum']:12.6f} (abs error = {res_swal['naive_abs_error']:.2e})")
print(f" Neumaier sum = {res_swal['neumaier_sum']:12.6f} (abs error = {res_swal['neumaier_abs_error']:.2e})")
# Case B: Sudden large cancellation [1e16, pi, -1e16, e] where |v_k| >> |c| breaks classical Kahan:
stream_sudden = np.array([1.0e16, math.pi, -1.0e16, math.e], dtype=np.float64)
res_sud = representation_scaling.kahan_babuska_sum(stream_sudden)
kahan_err_sud = abs(res_sud["kahan_sum"] - res_sud["exact_fsum"])
print(f"\nCase B ([1e16, pi, -1e16, e], exact pi + e = {res_sud['exact_fsum']:.15f}):")
print(f" Naive sum = {res_sud['naive_sum']:.15f} | error = {res_sud['naive_abs_error']:.2e}")
print(f" Kahan sum = {res_sud['kahan_sum']:.15f} | error = {kahan_err_sud:.2e} (fails when |-1e16| >> |s_prev - t|)")
print(f" Neumaier sum = {res_sud['neumaier_sum']:.15f} | error = {res_sud['neumaier_abs_error']:.2e}")
# Case C: Error growth across stream lengths N for an ill-conditioned oscillatory flux integral:
n_sizes = np.array([200, 1000, 5000, 20000, 80000])
err_naive_list, err_neu_list = [], []
rng = np.random.default_rng(42)
for n_len in n_sizes:
half = n_len // 2
big_blocks = rng.uniform(1.0e7, 2.0e7, size=half)
tiny_drift = rng.uniform(1.0e-5, 2.0e-5, size=half)
interleaved = np.empty(n_len, dtype=np.float64)
interleaved[0::2] = big_blocks + tiny_drift
interleaved[1::2] = -big_blocks
r_n = representation_scaling.kahan_babuska_sum(interleaved)
err_naive_list.append(max(r_n["naive_abs_error"] / r_n["exact_fsum"], 1.0e-17))
err_neu_list.append(max(r_n["neumaier_abs_error"] / r_n["exact_fsum"], 1.0e-17))
fig, ax = plt.subplots(figsize=(7.6, 4.1))
ax.loglog(n_sizes, err_naive_list, "o-", color="#C0392B", lw=2.1, label="Naive left-to-right sum")
ax.loglog(n_sizes, err_neu_list, "s--", color="#2E8B57", lw=2.1, label="Neumaier / Babuška compensated sum")
ax.axhline(2.0 ** -52, color="gray", ls=":", label=r"Machine epsilon $\varepsilon_{\mathrm{mach}} = 2^{-52}$")
ax.set_xlabel(r"Stream length $N$ [samples]")
ax.set_ylabel("Relative summation error")
ax.set_title("Summation error against stream length")
ax.legend(fontsize=8.5)
plt.show()
assert res_swal["naive_sum"] == 0.0 and res_swal["neumaier_sum"] == 1000.0
assert kahan_err_sud > 0.5 and res_sud["neumaier_abs_error"] < 1.0e-15
assert err_naive_list[-1] > 1.0e5 * err_neu_list[-1]
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 0.2. Relative error of a long sum of small increments on a large baseline, against the stream length . 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 .
What Demonstration 2 shows.
Zero extra memory, state: Neumaier summation adds just one scalar compensation register
c_neuand 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 () when
-1e16arrived, whereas Neumaier’sif abs(neu_s) >= abs(fv)check captured the exact rounding residual inc_neuand recovered to all printed digits.
3. Catastrophic Variance Cancellation vs. Welford’s Centered Invariant (welford_streaming_stats)¶
The one-pass identity is often recommended: . Suppose an industrial pressure sensor measures small turbulent fluctuations atop a static line pressure (). Squaring produces , where . Every fluctuation is lost before the subtraction even happens, and worse, opposing round-to-even errors can make strictly negative.
Mental Move #4, Maintain Centered Running Moments (Welford 1962) updates the running mean and sum of squared deviations in a single pass via the exact algebraic recurrence:
Because and always share the same sign, every increment added to is guaranteed non-negative in IEEE-754 arithmetic.
heading("Demonstration 3: Negative textbook variance (-128 Pa^2) against Welford streaming invariant")
# 4-sample 1 GPa pressure burst with exact population variance = +3.0 Pa^2:
p_burst = np.array([1.0e9 + 8.0, 1.0e9 + 8.0, 1.0e9 + 8.0, 1.0e9 + 12.0], dtype=np.float64)
burst_stats = representation_scaling.welford_streaming_stats(p_burst)
print("4-Sample 1 GPa Sensor Burst [1e9+8, 1e9+8, 1e9+8, 1e9+12] (Exact var_pop = +3.0 Pa^2):")
print(f" Textbook E[x^2] - E[x]^2 = {burst_stats['naive_formula_variance_pop']:+.6f} Pa^2 <-- negative variance")
print(f" Welford streaming var_pop = {burst_stats['variance_pop']:+.15f} Pa^2")
# Sweep DC baseline offset C from 10^0 to 10^9 Pa on a deterministic unit-scale turbulent signal:
x0 = np.linspace(-math.sqrt(3.0), math.sqrt(3.0), 1001)
var_ref = representation_scaling.welford_streaming_stats(x0)["variance_pop"]
offsets = 10.0 ** np.arange(0, 10, dtype=float)
rel_err_naive, rel_err_welford = [], []
print(f"\n{'Baseline C [Pa]':>15s} | {'Naive var_pop':>16s} | {'Welford var_pop':>16s} | {'Naive RelErr':>13s} | {'Welford RelErr':>14s}")
print("-" * 86)
for c_off in offsets:
st = representation_scaling.welford_streaming_stats(c_off + x0)
en = max(abs(st["naive_formula_variance_pop"] - var_ref) / var_ref, 1.0e-17)
ew = max(abs(st["variance_pop"] - var_ref) / var_ref, 1.0e-17)
rel_err_naive.append(en)
rel_err_welford.append(ew)
print(f"{c_off:15.1e} | {st['naive_formula_variance_pop']:16.6f} | {st['variance_pop']:16.12f} | {en:13.2e} | {ew:14.2e}")
fig, ax = plt.subplots(figsize=(7.6, 4.1))
ax.loglog(offsets, rel_err_naive, "o-", color="#C0392B", lw=2.2, label=r"Textbook $\overline{x^2} - \bar{x}^2$ (scales as $\kappa^2 \varepsilon_{\mathrm{mach}}$)")
ax.loglog(offsets, rel_err_welford, "s--", color="#2166AC", lw=2.2, label=r"Welford centered recurrence (scales as $\kappa \varepsilon_{\mathrm{mach}}$)")
ax.axhline(1.0, color="k", ls=":", lw=1.3, label="100% error ( zero significant digits left )")
ax.set_xlabel(r"Sensor DC offset baseline $C$ [Pa]")
ax.set_ylabel("Relative error in population variance")
ax.set_title("Variance error against the offset of the data")
ax.legend(fontsize=8.3)
plt.show()
assert burst_stats["naive_formula_variance_pop"] == -128.0
assert np.isclose(burst_stats["variance_pop"], 3.0, rtol=1e-15)
assert rel_err_naive[-1] > 1.0 and rel_err_welford[-1] < 1.0e-6
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 0.3. Relative error of the population variance when a constant offset is added to the data. The one-pass formula loses accuracy as , with , and has no correct digit left at ; Welford’s recurrence loses only as .
What Demonstration 3 shows.
Squared condition-number blowup: Adding baseline gives data condition number . Squaring the raw samples squares the condition number to , losing digits. At , digits are lost (the naive variance is -2, a relative error of 3), whereas Welford subtracts the running mean before multiplying, losing at most at .
4. Overflow & Underflow Immunity via Max-Shift (stable_logsumexp)¶
In statistical mechanics (canonical partition function ), Bayesian log-evidence, and neural-network cross-entropy, float64 math.exp(z) overflows to +inf for and underflows to 0.0 for . Mental Move #3, Shift Before You Exponentiate (representation_scaling.stable_logsumexp) factors out :
Because , the largest exponential term is identically , guaranteeing — so neither overflow nor total underflow can ever occur.
heading("Demonstration 4: Boltzmann partition functions and softmax under +/-1000 log-weight extremes")
z_base = np.array([-2.0, -0.5, 0.0, 1.2], dtype=np.float64)
shifts = np.array([-1200.0, -800.0, 0.0, 800.0, 1200.0])
ref_res = representation_scaling.stable_logsumexp(z_base)
print(f"{'Shift c':>10s} | {'Naive log(sum(exp))':>20s} | {'Stable LogSumExp':>20s} | {'LSE(z+c) - c Error':>20s} | {'Max |p - p_ref|':>16s}")
print("-" * 98)
for c_sh in shifts:
z_shifted = z_base + c_sh
with np.errstate(over="ignore", divide="ignore", invalid="ignore"):
naive_exp = np.exp(z_shifted)
naive_lse = float(np.log(np.sum(naive_exp)))
st_res = representation_scaling.stable_logsumexp(z_shifted)
shift_inv_err = abs((st_res["log_sum_exp"] - c_sh) - ref_res["log_sum_exp"])
prob_err = float(np.max(np.abs(st_res["probabilities"] - ref_res["probabilities"])))
print(f"{c_sh:10.1f} | {str(naive_lse):>20s} | {st_res['log_sum_exp']:20.12f} | {shift_inv_err:20.2e} | {prob_err:16.2e}")
assert shift_inv_err < 1.0e-12
assert prob_err < 1.0e-12
assert np.isclose(np.sum(st_res["probabilities"]), 1.0, atol=1e-15)
# Verify defensive input guards across representation_scaling functions:
for fn, bad_in in [
(representation_scaling.welford_streaming_stats, (np.array([]),)),
(representation_scaling.stable_logsumexp, (np.array([]),)),
(representation_scaling.stable_logsumexp, (np.array([1.0, np.inf]),)),
]:
caught = False
try:
fn(*bad_in)
except ValueError:
caught = True
assert caught
print("\nExact shift equivariance LSE(z + c) == c + LSE(z) and defensive guards verified")
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 and computed independently on separate shards can be merged exactly, apart from rounding, via:
Check against the library¶
heading("Inside the algorithm: Kahan/Neumaier, Welford and Chan's parallel mergeable variance")
print(show_source(representation_scaling.kahan_babuska_sum))
print(show_source(representation_scaling.welford_streaming_stats))
def _chan_summary_single(chunk: np.ndarray) -> tuple[int, float, float]:
"""Compute (n, mean, M2) on one shard via Welford's recurrence."""
st = representation_scaling.welford_streaming_stats(chunk)
return st["count"], st["mean"], st["variance_pop"] * st["count"]
def manual_chan_parallel_welford(chunk_a: np.ndarray, chunk_b: np.ndarray) -> dict:
"""Merge two high-offset sensor shards via Chan's parallel centered-moment invariant."""
na, mua, m2a = _chan_summary_single(np.asarray(chunk_a, dtype=np.float64))
nb, mub, m2b = _chan_summary_single(np.asarray(chunk_b, dtype=np.float64))
nab = na + nb
delta = mub - mua
mu_ab = mua + delta * (nb / nab)
m2_ab = m2a + m2b + (delta * delta) * (na * nb / nab)
return {
"count": nab,
"mean": mu_ab,
"variance_pop": m2_ab / nab,
"variance_sample": m2_ab / (nab - 1),
}
rng_in = np.random.default_rng(101)
high_offset_signal = 5.0e8 + rng_in.normal(loc=2.5, scale=1.75, size=2400)
shard_left, shard_right = high_offset_signal[:950], high_offset_signal[950:]
chan_res = manual_chan_parallel_welford(shard_left, shard_right)
welf_ref = representation_scaling.welford_streaming_stats(high_offset_signal)
print(f"Full-stream Welford var_pop : {welf_ref['variance_pop']:.15f}")
print(f"2-Shard Chan merged var_pop : {chan_res['variance_pop']:.15f}")
print(f"Textbook naive var_pop : {welf_ref['naive_formula_variance_pop']:.15f}")
print(f"Abs diff |Chan - Welford| : {abs(chan_res['variance_pop'] - welf_ref['variance_pop']):.2e}")
assert np.isclose(chan_res["mean"], welf_ref["mean"], rtol=1e-15)
assert np.isclose(chan_res["variance_pop"], welf_ref["variance_pop"], rtol=1e-7)
assert np.isclose(chan_res["variance_sample"], welf_ref["variance_sample"], rtol=1e-7)
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.
Verify a result. Prove via
fractions.Fraction(0.1)that IEEE-7540.1exceeds by exactly , and compare cumulative clock error over 100 hours ( ticks of ) across Patriot’s 24-bit signed fixed-point register (1 sign bit + 23 fractional bits),float64t += 0.1accumulation, and integer tick countingk * 0.1.Find how it fails. Quantify catastrophic digit loss in the textbook quadratic root for across relative to Vieta’s Citardauq invariant , and audit naive
np.log(np.sum(np.exp(z)))at .Implement it yourself. Implement
compensated_dot_and_pairwise_sum(a, b)returningnp_dot,pairwise_dot,dot2_compensated, andexact_dotusing recursive pairwise product summation and Ogita–Rump–Oishi’s error-freeDot2transformation (two_prodvia Veltkamp splitting and Knuthtwo_sum). Verify on an ill-conditioned dot product with condition number .
heading("Self-check for the exercises")
assert representation_scaling.ieee754_float64_inspect(1.0)["ulp"] == 2.0 ** -52
assert res_swal["neumaier_sum"] == 1000.0 and res_swal["naive_sum"] == 0.0
assert burst_stats["naive_formula_variance_pop"] < 0.0 and np.isclose(burst_stats["variance_pop"], 3.0)
assert np.isclose(chan_res["variance_pop"], welf_ref["variance_pop"], rtol=1e-7)
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.