Algorithmcore
Welford's algorithm
Also called Welford's online algorithm, running variance algorithm, online variance algorithm.
Computes the mean and variance of a stream in one pass, updating the mean and the sum of squared deviations per item. It avoids the cancellation of the textbook formula.
- Time
- Θ(n) worst · best
- Space
- Θ(1) extra
- Counts
- flops 6 n + 1 worst
- Where
- n = the number of data values, at least 2
- Properties
- deterministicexact in exact arithmeticone passonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- B. P. Welford, 1962
Welford's algorithm computes the mean and the sum of squared deviations of a sequence of numbers in one pass and constant memory, by updating both each time a value arrives; the sample variance is the sum divided by . In exact arithmetic it gives the same numbers as the two-pass formula. In floating point its error bound grows like , where is the condition number of the data, while the textbook formula has the bound and can lose every digit to catastrophic cancellation. The update of two partial results, not one value, is the Chan-Golub-LeVeque algorithm.
In plain words
Keep three numbers: how many values you have seen, their average, and a running total of squared distances from the average. When a new value comes, measure how far it is from the old average. Move the average toward it by that distance divided by the new count. Then add to the total the old distance times the distance from the new average. The two distances point the same way, so the total only grows. At the end, the total divided by the count minus one is the sample variance.
The textbook shortcut adds up the squares of the values and subtracts the square of their sum, divided by the count. When the values are large and close together, the two big numbers almost cancel, and what is left is mostly rounding error. Welford's update works with distances from the average, which stay small.
The problem
The input is a sequence of real numbers with , which may arrive one at a time with no way to read them again. The output is the mean , the sum of squared deviations and the sample variance . The divisor- variance is . The memory may not grow with , and after any prefix the values for that prefix should be available.
The algorithm
WELFORD(x_1, ..., x_n) ▷ n ≥ 2- 1
M ← 0, S ← 0 - 2
for k ← 1 to n do - 3
d ← x_k - M ▷ distance from the old mean - 4
M ← M + d / k ▷ M is now the mean of x_1 .. x_k - 5
S ← S + d · (x_k - M) ▷ old distance times new distance - 6
V ← S / (n - 1) ▷ sample variance; S / n for divisor n - 7
return M, V, S
The invariant is that after iteration , is the mean of the first values and is their sum of squared deviations. Line L5 multiplies the distance from the old mean by the distance from the new one. Both have the sign of , and their product equals , which is the amount by which the sum of squared deviations grows when joins. Line L5 can also be written ; Chan, Golub and LeVeque write the update in that form as (1.3), and say that the methods of Welford, West and Hanson are virtually identical for unweighted data.
For a stream, lines L3 to L5 are the update and line L6 is a query that can be asked after any .
Example
The data are , in exact arithmetic.
| 1 | 3 | 3 | 3 | 0 | 0 |
| 2 | 7 | 4 | 5 | 2 | 8 |
| 3 | 7 | 2 | 17/3 | 4/3 | 32/3 |
| 4 | 9 | 10/3 | 13/2 | 5/2 | 19 |
| 5 | 14 | 15/2 | 8 | 6 | 64 |
So , and , the values on sample variance. Each is the sum of squared deviations of the first values; for , the values have mean and .
The same data, shifted. Add to each value. The spread is unchanged, so is still 16. In IEEE double precision, the textbook formula returns , a negative variance, when is computed as , and 0 when it is computed as . Either way no digit of 16 is left, because is stored with a spacing of 1024 between neighbouring doubles. The two-pass formula returns 16.0 and Welford's algorithm returns 16.000000044703484, a relative error of .
Correctness
By induction on , after iteration , is the mean of the first values and is their sum of squared deviations . The mean update is . For the sum, write the old deviations around the new mean with the shift identity , add the new term, and simplify with : the increase is . The full proof is below. It is a statement about exact arithmetic; the floating-point behaviour is in the next sections.
Proof: Welford's algorithm returns the mean and the sum of squared deviationsfull
The arithmetic is exact. For write for the mean of the first values and for their sum of squared deviations. and are the values of and after iteration of the loop of line L2, and are the values set in line L1.
Lemma 1 (shift). For and every real ,
Proof. Write and expand the square. The sum of the cross terms is , and the last terms add up to .
Lemma 2 (mean). for .
Proof. By induction on . For , line L3 gives and line L4 gives . For , assume . Lines L3 and L4 give
Lemma 3 (one step). Let and . Then
Proof. Lemma 1 for the first values with gives . Add the term :
The computation in Lemma 2 shows , so . The two added terms are
Theorem. Let . After iteration of the loop, and , for . So WELFORD returns , and , the sample variance .
Proof. is Lemma 2. For , use induction on . For , line L5 gives , since . For , assume . In iteration , line L3 computes by Lemma 2, and line L5 computes , which is by Lemma 3. The loop runs exactly times, so it ends with , and lines L6 and L7 return , which is defined because .
Corollary (monotone and nonnegative). In exact arithmetic each increment of line L5 is , so and . The textbook formula has the same value, but it is a difference, and in floating point it can be negative.
Termination and cost. The loop has iterations, and each iteration runs lines L3 to L5 once: one subtraction in L3, one division and one addition in L4, and one subtraction, one multiplication and one addition in L5, so 6 arithmetic operations. Line L6 adds one division. The total is operations, and the extra storage is the three numbers , and and the counter .
Complexity
Each iteration does one subtraction in line L3, a division and an addition in line L4, and a subtraction, a multiplication and an addition in line L5. With the division of line L6, the count is exactly floating-point operations, for every input. The time is and the extra space is : , , and .
For comparison, the textbook formula costs about operations in one pass, and the two-pass formula about operations in two passes, with the data stored or read twice.
Rounding error. Let be the unit roundoff ( in double precision). Chan, Golub and LeVeque measure the difficulty of the data by the condition number
which is about , the mean divided by the standard deviation, when that ratio is large. Their Table 1 lists bounds on the relative error of the computed , with small constants and higher-order terms dropped:
| algorithm | error bound |
|---|---|
| textbook, one pass | |
| two-pass | |
| updating (Welford, West) | |
| pairwise (Chan-Golub-LeVeque) | , conjectured |
The bounds for the textbook and the updating algorithms are proved by Chan and Lewis (1979). So when is near , the textbook bound exceeds 1 and the result can have no correct digit, while the bound for Welford's algorithm is .
Measured errors. The table gives the relative error of in double precision against the exact value of the stored data, computed with Python's fractions.Fraction. The data are with standard normal from random.Random(1), , one run per row, the rows drawn in this order from one generator. The textbook column is , the two-pass column uses plain left-to-right sums, and the pairwise column is the recursive merge of the Chan-Golub-LeVeque algorithm.
| textbook | two-pass | Welford | pairwise | ||
|---|---|---|---|---|---|
| 101 | |||||
| 7.45 |
These are single measured runs, not bounds. They follow the pattern of the bounds: the textbook error grows much faster with than the Welford error, which grows roughly in proportion to and stays far below ; the two-pass error stays below . At the textbook error is 7.45 times the true value.
Properties
- One pass and online. Each value is used once, in order, and the mean and variance of every prefix are available.
- Constant memory. Three numbers and a counter, whatever is.
- Exact in exact arithmetic. With rational inputs and exact arithmetic it returns exactly , and .
- Nonnegative. In exact arithmetic every increment of is . The textbook formula is a difference and can be negative in floating point, as the example shows.
- Order dependent in floating point. Feeding the same values in another order changes the last digits of the result.
Variants and improvements
- Weights. For weights , keep and use , and . This is West's (1979) weighted updating. With frequency weights, is the sample variance of the expanded data.
- Covariance. For pairs , update both means and . Then is the sample covariance; the vector form updates a covariance matrix by an outer product.
- Merging. Two accumulators and combine in operations. That is the Chan-Golub-LeVeque algorithm; Welford's update is its case .
- Higher moments. The same approach updates the third and fourth central sums, for the skewness and the kurtosis of a stream.
- Forgetting. Replacing in line L4 by a fixed weight gives the exponential moving average of the mean, which follows a drifting stream.
- Shift first. Subtracting a rough estimate of the mean, for example , from every value reduces ; Chan, Golub and LeVeque show that a shift within of the mean gives for the shifted data, after which even the textbook formula is accurate.
When to use it
Use Welford's algorithm when the data come as a stream, are too large to store, or must be summarized after every value, as in monitoring and in online learning. If the data fit in memory, the two-pass formula is simpler and more accurate. If the data are small integers, the textbook formula in exact integer arithmetic has no rounding error until the final division. To summarize parts in parallel, use one Welford accumulator per part and merge them with the Chan-Golub-LeVeque algorithm.
Pitfalls
- The new mean in both factors. The update with the new adds too little: on the example it gives instead of 64. With the old mean in both factors, adds too much in each step. The two factors must use the old and the new mean.
- Integer division. In a language where with integer operands truncates, line L4 is wrong for integer data. Convert to floating point first.
- The divisor. Return for the sample variance and for the divisor- variance, and say which one. For , is undefined.
- Not immune to bad conditioning. The error still grows with . For data with a huge mean and a tiny spread, shift the data first.
- Removing values. Running the update backwards removes a value from the accumulator, for a sliding window, but it subtracts and can lose the accuracy that the forward update keeps.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.
The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""
import math
from statistics import NormalDist
_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000
def norm_cdf(x: float) -> float:
"""P(Z <= x) for a standard normal Z."""
return 0.5 * math.erfc(-x / math.sqrt(2.0))
def norm_sf(x: float) -> float:
"""P(Z > x), computed with erfc, so it is accurate for large x."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def norm_ppf(p: float) -> float:
"""The lower p-quantile z_p of the standard normal, 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
return _STD.inv_cdf(p)
def _gamma_tails(a: float, x: float) -> tuple[float, float]:
"""(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
if a <= 0.0 or x < 0.0:
raise ValueError("need a > 0 and x >= 0")
if x == 0.0:
return 0.0, 1.0
if math.isinf(x):
return 1.0, 0.0
front = math.exp(-x + a * math.log(x) - math.lgamma(a))
if x < a + 1.0:
# Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
ap, term = a, 1.0 / a
total = term
for _ in range(_MAXIT):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * _EPS:
break
p = front * total
return p, 1.0 - p
# Continued fraction for Q, modified Lentz.
b = x + 1.0 - a
c = 1.0 / _TINY
d = 1.0 / b
h = d
for i in range(1, _MAXIT):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < _TINY:
d = _TINY
c = b + an / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
q = front * h
return 1.0 - q, q
def gamma_p(a: float, x: float) -> float:
"""Regularized lower incomplete gamma P(a, x)."""
return _gamma_tails(a, x)[0]
def gamma_q(a: float, x: float) -> float:
"""Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
return _gamma_tails(a, x)[1]
def _beta_cf(a: float, b: float, x: float) -> float:
"""The continued fraction of I_x(a, b), modified Lentz."""
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
if abs(d) < _TINY:
d = _TINY
d = 1.0 / d
h = d
for m in range(1, _MAXIT):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
return h
def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
"""(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.
y is 1 - x; pass it when it is known more accurately than 1 - x.
"""
if a <= 0.0 or b <= 0.0:
raise ValueError("need a > 0 and b > 0")
if y is None:
y = 1.0 - x
if x <= 0.0:
return 0.0, 1.0
if y <= 0.0:
return 1.0, 0.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
+ a * math.log(x) + b * math.log(y)
)
if x < (a + 1.0) / (a + b + 2.0):
low = front * _beta_cf(a, b, x) / a
return low, 1.0 - low
# Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
up = front * _beta_cf(b, a, y) / b
return 1.0 - up, up
def beta_inc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b)."""
return _beta_tails(a, b, x)[0]
def chi2_cdf(x: float, k: float) -> float:
"""P(X <= x) for X chi-square with k > 0 degrees of freedom."""
return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)
def chi2_sf(x: float, k: float) -> float:
"""P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)
def t_sf(x: float, k: float) -> float:
"""P(T > x) for T Student t with k > 0 degrees of freedom."""
if math.isfinite(x):
s = k + x * x
half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0] # P(|T| > |x|) / 2
else:
half = 0.0
return half if x >= 0.0 else 1.0 - half
def t_cdf(x: float, k: float) -> float:
"""P(T <= x) for T Student t with k degrees of freedom."""
return t_sf(-x, k)
def f_cdf(x: float, k1: float, k2: float) -> float:
"""P(F <= x) for F with (k1, k2) degrees of freedom."""
if x <= 0.0:
return 0.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]
def f_sf(x: float, k1: float, k2: float) -> float:
"""P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
if x <= 0.0:
return 1.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]
def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
"""The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).
lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
"""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
if p <= 0.5:
g = lambda x: cdf(x) - p # increasing in x
else:
q = 1.0 - p
g = lambda x: q - sf(x) # increasing in x, and no cancellation in sf
while g(hi) < 0.0:
lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
for _ in range(400):
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
break
if g(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def chi2_ppf(p: float, k: float) -> float:
"""The lower p-quantile chi^2_(k, p)."""
return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))
def t_ppf(p: float, k: float) -> float:
"""The lower p-quantile t_(k, p)."""
if p == 0.5:
return 0.0
if p < 0.5:
return -t_ppf(1.0 - p, k)
return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)
def f_ppf(p: float, k1: float, k2: float) -> float:
"""The lower p-quantile F_(k1, k2, p)."""
return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
welford_algorithm.py 55 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/welford-algorithm/. The authors are listed in prov/3F3F57.jsonl.
from collections.abc import Iterable, Sequence
def welford_algorithm(xs: Sequence[float]) -> tuple[float, float, float]:
"""Return (M, V, S) for the data xs in one pass.
M is the mean, S the sum of squared deviations from M, and V = S / (n - 1)
the sample variance. Precondition: len(xs) >= 2. Cost: 6 n + 1 arithmetic
operations and O(1) extra memory. Exact for Fraction inputs.
"""
n = len(xs)
if n < 2:
raise ValueError("need at least two values")
m, s = 0 * xs[0], 0 * xs[0] # @line L1
for k in range(1, n + 1): # @line L2
x = xs[k - 1]
d = x - m # @line L3
m = m + d / k # @line L4
s = s + d * (x - m) # @line L5
v = s / (n - 1) # @line L6
return m, v, s # @line L7
class RunningVariance:
"""Welford's update as an online accumulator.
push costs O(1) time; the object holds three numbers. After k pushes,
mean is the mean of the k values and ss their sum of squared deviations.
"""
def __init__(self) -> None:
self.count = 0
self.mean: float = 0 # an int 0 keeps Fraction inputs exact
self.ss: float = 0
def push(self, x: float) -> None:
"""Add one value."""
self.count += 1
d = x - self.mean
self.mean = self.mean + d / self.count
self.ss = self.ss + d * (x - self.mean)
def extend(self, xs: Iterable[float]) -> None:
"""Add every value of xs, in order."""
for x in xs:
self.push(x)
def variance(self, ddof: int = 1) -> float:
"""Return ss / (count - ddof): ddof = 1 gives S^2, ddof = 0 the divisor-n variance."""
if self.count - ddof <= 0:
raise ValueError("too few values for this divisor")
return self.ss / (self.count - ddof)
test_stdist.py 60 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
import math
from stdist import (
beta_inc, chi2_cdf, chi2_ppf, chi2_sf, f_cdf, f_ppf, f_sf, gamma_p, gamma_q,
norm_cdf, norm_ppf, norm_sf, t_cdf, t_ppf, t_sf,
)
XS = [0.001, 0.01, 0.1, 0.3, 0.5, 1.0, 1.7, 2.5, 4.0, 7.0, 12.0, 30.0, 80.0]
def test_chi2_two_degrees_of_freedom() -> None:
for x in XS:
assert abs(chi2_cdf(x, 2) - (1.0 - math.exp(-x / 2.0))) < 1e-13
assert abs(chi2_sf(x, 2) - math.exp(-x / 2.0)) <= 1e-12 * math.exp(-x / 2.0)
def test_t_one_and_two_degrees_of_freedom() -> None:
for x in XS + [-v for v in XS] + [0.0]:
assert abs(t_cdf(x, 1) - (0.5 + math.atan(x) / math.pi)) < 1e-13
assert abs(t_cdf(x, 2) - (0.5 + x / (2.0 * math.sqrt(2.0 + x * x)))) < 1e-13
assert abs(t_cdf(x, 3) + t_sf(x, 3) - 1.0) < 1e-14
def test_f_is_square_of_t() -> None:
for k in [1, 2, 3, 5, 10, 30]:
for x in XS:
two_sided = 2.0 * t_sf(math.sqrt(x), k)
assert abs(f_sf(x, 1, k) - two_sided) < 1e-13
assert abs(f_cdf(x, 1, k) + f_sf(x, 1, k) - 1.0) < 1e-14
def test_gamma_and_beta_identities() -> None:
for a in [0.5, 1.0, 2.5, 10.0, 50.0]:
for x in XS:
assert abs(gamma_p(a, x) + gamma_q(a, x) - 1.0) < 1e-14
# P(1, x) = 1 - e^(-x); I_x(a, 1) = x^a; I_x(1, b) = 1 - (1 - x)^b.
for x in [0.05, 0.3, 0.5, 0.8, 0.99]:
assert abs(gamma_p(1.0, x) - (1.0 - math.exp(-x))) < 1e-14
for a in [0.5, 2.0, 7.0]:
assert abs(beta_inc(a, 1.0, x) - x**a) < 1e-13
assert abs(beta_inc(1.0, a, x) - (1.0 - (1.0 - x) ** a)) < 1e-13
def test_upper_tails_do_not_cancel() -> None:
assert abs(norm_sf(10.0) / 7.619853024160527e-24 - 1.0) < 1e-12
assert abs(chi2_sf(200.0, 2) / math.exp(-100.0) - 1.0) < 1e-12
assert norm_cdf(-30.0) > 0.0
def test_quantiles() -> None:
assert abs(norm_ppf(0.975) - 1.959963985) < 1e-8
assert abs(chi2_ppf(0.95, 1) - 3.841458821) < 1e-8
assert abs(t_ppf(0.975, 10) - 2.228138852) < 1e-8
for p in [1e-6, 0.01, 0.2, 0.5, 0.8, 0.99, 1.0 - 1e-6]:
for k in [1, 4, 25]:
assert abs(chi2_cdf(chi2_ppf(p, k), k) - p) < 1e-12
assert abs(t_cdf(t_ppf(p, k), k) - p) < 1e-12
assert abs(f_cdf(f_ppf(p, k, 7), k, 7) - p) < 1e-12
test_welford_algorithm.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/welford-algorithm/. The authors are listed in prov/3F3F57.jsonl.
import math
import random
from fractions import Fraction
from stdist import chi2_cdf, chi2_ppf
from welford_algorithm import RunningVariance, welford_algorithm
U = 2.0 ** -53
def two_pass(xs):
"""Oracle: the mean, then the sum of squared deviations, in exact arithmetic."""
n = len(xs)
m = sum(xs, Fraction(0)) / n
s = sum(((x - m) ** 2 for x in xs), Fraction(0))
return m, s / (n - 1), s
def test_running_example_trace():
acc = RunningVariance()
trace = []
for x in (3, 7, 7, 9, 14):
acc.push(Fraction(x))
trace.append((acc.mean, acc.ss))
assert trace == [
(3, 0), (5, 8), (Fraction(17, 3), Fraction(32, 3)), (Fraction(13, 2), 19), (8, 64),
]
assert welford_algorithm([Fraction(x) for x in (3, 7, 7, 9, 14)]) == (8, 16, 64)
assert acc.variance() == 16 and acc.variance(ddof=0) == Fraction(64, 5)
def test_exact_against_two_pass_on_random_inputs():
rng = random.Random(20261114)
for _ in range(600):
n = rng.randint(2, 12)
xs = [Fraction(rng.randint(-50, 50), rng.randint(1, 9)) for _ in range(n)]
assert welford_algorithm(xs) == two_pass(xs)
acc = RunningVariance()
acc.extend(xs)
m, v, s = two_pass(xs)
assert acc.count == n and acc.mean == m and acc.ss == s
for k in range(1, n + 1):
pre = RunningVariance()
pre.extend(xs[:k])
mk = sum(xs[:k], Fraction(0)) / k
assert pre.mean == mk
assert pre.ss == sum(((x - mk) ** 2 for x in xs[:k]), Fraction(0))
def test_float_error_is_small_on_shifted_data():
rng = random.Random(7)
for c in (0.0, 1e3, 1e6):
for n in (2, 10, 300):
xs = [c + rng.gauss(0.0, 1.0) for _ in range(n)]
_, v_exact, s_exact = two_pass([Fraction(x) for x in xs])
m, v, s = welford_algorithm(xs)
kappa = math.sqrt(1 + n * float(sum(map(Fraction, xs)) / n) ** 2 / float(s_exact))
rel = abs(Fraction(v) - v_exact) / v_exact
assert rel <= 50 * n * kappa * U
def test_textbook_formula_cancels_but_welford_does_not():
xs = [1e9 + t for t in (3, 7, 7, 9, 14)]
n = len(xs)
textbook = (sum(x * x for x in xs) - n * (sum(xs) / n) ** 2) / (n - 1)
assert textbook == -256.0
_, v, _ = welford_algorithm(xs)
assert abs(v - 16) <= 1e-6 * 16
def test_short_inputs():
acc = RunningVariance()
acc.push(5.0)
assert acc.mean == 5.0 and acc.ss == 0.0 and acc.variance(ddof=0) == 0.0
for bad in ([], [1.0]):
try:
welford_algorithm(bad)
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
def test_chi_square_law_monte_carlo():
# (n - 1) S^2 / sigma^2 is chi-square with n - 1 degrees of freedom for normal data.
rng = random.Random(12345)
n, sigma, r = 5, 2.0, 2000
stats = []
for _ in range(r):
xs = [1000.0 + sigma * rng.gauss(0.0, 1.0) for _ in range(n)]
_, v, _ = welford_algorithm(xs)
stats.append((n - 1) * v / sigma ** 2)
for p in (0.1, 0.5, 0.9):
q = chi2_ppf(p, n - 1)
assert abs(chi2_cdf(q, n - 1) - p) < 1e-9
emp = sum(1 for t in stats if t <= q) / r
assert abs(emp - p) <= 4 * math.sqrt(p * (1 - p) / r)
History
Welford (1962) gave a method for computing corrected sums of squares and products in one pass, by updating them one observation at a time. Knuth gives the recurrence for and in Section 4.2.2 of The Art of Computer Programming. Chan and Lewis (1979) analysed the rounding error of the textbook and updating algorithms, West (1979) gave the weighted version, and Chan, Golub and LeVeque (1983) compared the known algorithms, bounded their errors in terms of and recommended which to use.
References
- B. P. Welford, Note on a method for calculating corrected sums of squares and products, Technometrics 4(3), 1962, pp. 419 to 420 (updating the mean and the corrected sum of squares one observation at a time)
- Donald E. Knuth, The Art of Computer Programming, Volume 2, Seminumerical Algorithms, third edition, Addison-Wesley, 1997, Section 4.2.2 (the recurrences for M_k and S_k)
- Tony F. Chan, Gene H. Golub and Randall J. LeVeque, Algorithms for computing the sample variance, analysis and recommendations, The American Statistician 37(3), 1983, pp. 242 to 247 (the updating formulas (1.3), the condition number (2.1) and the error bounds of Table 1)
- Tony F. Chan and John Gregg Lewis, Computing standard deviations, accuracy, Communications of the ACM 22(9), 1979, pp. 526 to 531 (rounding error analysis of the textbook and the updating algorithms)
- D. H. D. West, Updating mean and variance estimates, an improved method, Communications of the ACM 22(9), 1979, pp. 532 to 535 (the weighted updating algorithm)
- Nicholas J. Higham, Accuracy and Stability of Numerical Algorithms, second edition, SIAM, 2002, Section 1.9 (computing the sample variance)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 3F3F57 Edit this page History Report an error Markdown