Algorithm Search⌘K

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
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 n−1n - 1. In exact arithmetic it gives the same numbers as the two-pass formula. In floating point its error bound grows like nκun\kappa u, where κ\kappa is the condition number of the data, while the textbook formula ∑ixi2−nxˉ2\sum_i x_i^2 - n\bar x^2 has the bound nκ2un\kappa^2 u 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 x1,…,xnx_1, \ldots, x_n with n≥2n \ge 2, which may arrive one at a time with no way to read them again. The output is the mean xˉ=1n∑ixi\bar x = \frac1n\sum_i x_i, the sum of squared deviations SS=∑i(xi−xˉ)2\mathrm{SS} = \sum_i (x_i - \bar x)^2 and the sample variance S2=SS/(n−1)S^2 = \mathrm{SS}/(n-1). The divisor-nn variance is SS/n\mathrm{SS}/n. The memory may not grow with nn, and after any prefix the values for that prefix should be available.

The algorithm

  1. WELFORD(x_1, ..., x_n) ▷ n ≥ 2
  2. 1M ← 0, S ← 0
  3. 2for k ← 1 to n do
  4. 3d ← x_k - M ▷ distance from the old mean
  5. 4M ← M + d / k ▷ M is now the mean of x_1 .. x_k
  6. 5S ← S + d · (x_k - M) ▷ old distance times new distance
  7. 6V ← S / (n - 1) ▷ sample variance; S / n for divisor n
  8. 7return M, V, S

The invariant is that after iteration kk, MM is the mean of the first kk values and SS 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 dd, and their product equals k−1kd2\frac{k-1}{k}d^2, which is the amount by which the sum of squared deviations grows when xkx_k joins. Line L5 can also be written S←S+k−1kd2S \leftarrow S + \frac{k-1}{k} d^2; 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 k≥2k \ge 2.

Example

The data are x=(3,7,7,9,14)x = (3, 7, 7, 9, 14), in exact arithmetic.

kk xkx_k d=xk−Mk−1d = x_k - M_{k-1} MkM_k xk−Mkx_k - M_k SkS_k
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 xˉ=8\bar x = 8, SS=64\mathrm{SS} = 64 and V=64/4=16V = 64/4 = 16, the values on sample variance. Each SkS_k is the sum of squared deviations of the first kk values; for k=3k = 3, the values 3,7,73, 7, 7 have mean 17/317/3 and (8/3)2+2(4/3)2=96/9=32/3(8/3)^2 + 2(4/3)^2 = 96/9 = 32/3.

The same data, shifted. Add 10910^9 to each value. The spread is unchanged, so S2S^2 is still 16. In IEEE double precision, the textbook formula (∑ixi2−nxˉ2)/(n−1)(\sum_i x_i^2 - n\bar x^2)/(n-1) returns −256-256, a negative variance, when nxˉ2n\bar x^2 is computed as n⋅(∑ixi/n)2n \cdot (\sum_i x_i/n)^2, and 0 when it is computed as (∑ixi)2/n(\sum_i x_i)^2/n. Either way no digit of 16 is left, because ∑ixi2≈5×1018\sum_i x_i^2 \approx 5 \times 10^{18} 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 2.8×10−92.8 \times 10^{-9}.

Correctness

By induction on kk, after iteration kk, MM is the mean xˉk\bar x_k of the first kk values and SS is their sum of squared deviations SSk\mathrm{SS}_k. The mean update is xˉk=((k−1)xˉk−1+xk)/k\bar x_k = ((k-1)\bar x_{k-1} + x_k)/k. For the sum, write the old deviations around the new mean with the shift identity ∑i<k(xi−xˉk)2=SSk−1+(k−1)(xˉk−1−xˉk)2\sum_{i<k}(x_i - \bar x_k)^2 = \mathrm{SS}_{k-1} + (k-1)(\bar x_{k-1} - \bar x_k)^2, add the new term, and simplify with xˉk−xˉk−1=d/k\bar x_k - \bar x_{k-1} = d/k: the increase is k−1kd2=d (xk−xˉk)\frac{k-1}{k}d^2 = d\,(x_k - \bar x_k). 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 1≤k≤n1 \le k \le n write xˉk=1k∑i=1kxi\bar x_k = \frac1k \sum_{i=1}^k x_i for the mean of the first kk values and SSk=∑i=1k(xi−xˉk)2\mathrm{SS}_k = \sum_{i=1}^k (x_i - \bar x_k)^2 for their sum of squared deviations. MkM_k and SkS_k are the values of MM and SS after iteration kk of the loop of line L2, and M0=S0=0M_0 = S_0 = 0 are the values set in line L1.

Lemma 1 (shift). For k≥1k \ge 1 and every real cc,

∑i=1k(xi−c)2=SSk+k(xˉk−c)2.\sum_{i=1}^k (x_i - c)^2 = \mathrm{SS}_k + k(\bar x_k - c)^2.

Proof. Write xi−c=(xi−xˉk)+(xˉk−c)x_i - c = (x_i - \bar x_k) + (\bar x_k - c) and expand the square. The sum of the cross terms is 2(xˉk−c)∑i=1k(xi−xˉk)=2(xˉk−c)(kxˉk−kxˉk)=02(\bar x_k - c)\sum_{i=1}^k (x_i - \bar x_k) = 2(\bar x_k - c)(k\bar x_k - k\bar x_k) = 0, and the last terms add up to k(xˉk−c)2k(\bar x_k - c)^2. □\square

Lemma 2 (mean). Mk=xˉkM_k = \bar x_k for 1≤k≤n1 \le k \le n.

Proof. By induction on kk. For k=1k = 1, line L3 gives d=x1−0d = x_1 - 0 and line L4 gives M1=0+x1/1=x1=xˉ1M_1 = 0 + x_1/1 = x_1 = \bar x_1. For k≥2k \ge 2, assume Mk−1=xˉk−1M_{k-1} = \bar x_{k-1}. Lines L3 and L4 give

Mk=Mk−1+xk−Mk−1k=(k−1)xˉk−1+xkk=1k∑i=1kxi=xˉk.□M_k = M_{k-1} + \frac{x_k - M_{k-1}}{k} = \frac{(k-1)\bar x_{k-1} + x_k}{k} = \frac1k \sum_{i=1}^k x_i = \bar x_k. \qquad \square

Lemma 3 (one step). Let 2≤k≤n2 \le k \le n and d=xk−xˉk−1d = x_k - \bar x_{k-1}. Then

SSk=SSk−1+d (xk−xˉk)=SSk−1+k−1kd2.\mathrm{SS}_k = \mathrm{SS}_{k-1} + d\,(x_k - \bar x_k) = \mathrm{SS}_{k-1} + \frac{k-1}{k} d^2.

Proof. Lemma 1 for the first k−1k - 1 values with c=xˉkc = \bar x_k gives ∑i=1k−1(xi−xˉk)2=SSk−1+(k−1)(xˉk−1−xˉk)2\sum_{i=1}^{k-1}(x_i - \bar x_k)^2 = \mathrm{SS}_{k-1} + (k-1)(\bar x_{k-1} - \bar x_k)^2. Add the term i=ki = k:

SSk=SSk−1+(k−1)(xˉk−xˉk−1)2+(xk−xˉk)2.\mathrm{SS}_k = \mathrm{SS}_{k-1} + (k-1)(\bar x_k - \bar x_{k-1})^2 + (x_k - \bar x_k)^2.

The computation in Lemma 2 shows xˉk−xˉk−1=d/k\bar x_k - \bar x_{k-1} = d/k, so xk−xˉk=d−d/k=(k−1)d/kx_k - \bar x_k = d - d/k = (k-1)d/k. The two added terms are

(k−1)d2k2+(k−1)2d2k2=(k−1)d2k2 (1+k−1)=(k−1)d2k=d⋅(k−1)dk=d (xk−xˉk).□(k-1)\frac{d^2}{k^2} + \frac{(k-1)^2 d^2}{k^2} = \frac{(k-1)d^2}{k^2}\,(1 + k - 1) = \frac{(k-1)d^2}{k} = d \cdot \frac{(k-1)d}{k} = d\,(x_k - \bar x_k). \qquad \square

Theorem. Let n≥2n \ge 2. After iteration kk of the loop, M=xˉkM = \bar x_k and S=SSkS = \mathrm{SS}_k, for k=1,…,nk = 1, \ldots, n. So WELFORD returns M=xˉnM = \bar x_n, S=SSnS = \mathrm{SS}_n and V=SSn/(n−1)V = \mathrm{SS}_n/(n-1), the sample variance S2S^2.

Proof. Mk=xˉkM_k = \bar x_k is Lemma 2. For SS, use induction on kk. For k=1k = 1, line L5 gives S1=0+d (x1−M1)=d⋅0=0=SS1S_1 = 0 + d\,(x_1 - M_1) = d \cdot 0 = 0 = \mathrm{SS}_1, since M1=x1M_1 = x_1. For k≥2k \ge 2, assume Sk−1=SSk−1S_{k-1} = \mathrm{SS}_{k-1}. In iteration kk, line L3 computes d=xk−Mk−1=xk−xˉk−1d = x_k - M_{k-1} = x_k - \bar x_{k-1} by Lemma 2, and line L5 computes Sk=Sk−1+d (xk−Mk)=SSk−1+d (xk−xˉk)S_k = S_{k-1} + d\,(x_k - M_k) = \mathrm{SS}_{k-1} + d\,(x_k - \bar x_k), which is SSk\mathrm{SS}_k by Lemma 3. The loop runs exactly nn times, so it ends with k=nk = n, and lines L6 and L7 return V=SSn/(n−1)V = \mathrm{SS}_n/(n - 1), which is defined because n≥2n \ge 2. □\square

Corollary (monotone and nonnegative). In exact arithmetic each increment of line L5 is k−1kd2≥0\frac{k-1}{k}d^2 \ge 0, so S1≤S2≤⋯≤SnS_1 \le S_2 \le \cdots \le S_n and V≥0V \ge 0. The textbook formula ∑ixi2−nxˉ2\sum_i x_i^2 - n\bar x^2 has the same value, but it is a difference, and in floating point it can be negative.

Termination and cost. The loop has nn 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 6n+16n + 1 operations, and the extra storage is the three numbers MM, SS and dd and the counter kk. □\square

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 6n+16n + 1 floating-point operations, for every input. The time is Θ(n)\Theta(n) and the extra space is Θ(1)\Theta(1): MM, SS, dd and kk.

For comparison, the textbook formula (∑ixi2−(∑ixi)2/n)/(n−1)(\sum_i x_i^2 - (\sum_i x_i)^2/n)/(n-1) costs about 3n3n operations in one pass, and the two-pass formula about 4n4n operations in two passes, with the data stored or read twice.

Rounding error. Let uu be the unit roundoff (2−532^{-53} in double precision). Chan, Golub and LeVeque measure the difficulty of the data by the condition number

κ=1+nxˉ2SS  ≥  1,\kappa = \sqrt{1 + \frac{n\bar x^2}{\mathrm{SS}}} \;\ge\; 1,

which is about ∣xˉ∣/s\lvert\bar x\rvert/s, the mean divided by the standard deviation, when that ratio is large. Their Table 1 lists bounds on the relative error of the computed SS\mathrm{SS}, with small constants and higher-order terms dropped:

algorithm error bound
textbook, one pass nκ2un\kappa^2 u
two-pass nu+n2κ2u2nu + n^2\kappa^2u^2
updating (Welford, West) nκun\kappa u
pairwise (Chan-Golub-LeVeque) κulog⁡n\kappa u \log n, conjectured

The bounds for the textbook and the updating algorithms are proved by Chan and Lewis (1979). So when κ\kappa is near u−1/2≈108u^{-1/2} \approx 10^8, the textbook bound exceeds 1 and the result can have no correct digit, while the bound for Welford's algorithm is nu1/2n u^{1/2}.

Measured errors. The table gives the relative error of S2S^2 in double precision against the exact value of the stored data, computed with Python's fractions.Fraction. The data are c+Zic + Z_i with ZiZ_i standard normal from random.Random(1), n=104n = 10^4, one run per row, the rows drawn in this order from one generator. The textbook column is (∑ixi2−(∑ixi)2/n)/(n−1)(\sum_i x_i^2 - (\sum_i x_i)^2/n)/(n-1), the two-pass column uses plain left-to-right sums, and the pairwise column is the recursive merge of the Chan-Golub-LeVeque algorithm.

cc κ\kappa textbook two-pass Welford pairwise
10210^2 101 8.5×10−118.5 \times 10^{-11} 2.8×10−152.8 \times 10^{-15} 7.9×10−167.9 \times 10^{-16} 2.3×10−162.3 \times 10^{-16}
10410^4 9.96×1039.96 \times 10^3 1.5×10−71.5 \times 10^{-7} 3.3×10−153.3 \times 10^{-15} 2.4×10−132.4 \times 10^{-13} 3.8×10−143.8 \times 10^{-14}
10610^6 1.0×1061.0 \times 10^6 6.4×10−36.4 \times 10^{-3} 4.8×10−154.8 \times 10^{-15} 2.1×10−112.1 \times 10^{-11} 7.2×10−137.2 \times 10^{-13}
10810^8 9.9×1079.9 \times 10^7 7.45 8.3×10−158.3 \times 10^{-15} 2.9×10−92.9 \times 10^{-9} 1.7×10−101.7 \times 10^{-10}

These are single measured runs, not bounds. They follow the pattern of the bounds: the textbook error grows much faster with κ\kappa than the Welford error, which grows roughly in proportion to κ\kappa and stays far below nκun\kappa u; the two-pass error stays below 10−1410^{-14}. At c=108c = 10^8 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 nn is.
  • Exact in exact arithmetic. With rational inputs and exact arithmetic it returns exactly xˉ\bar x, SS\mathrm{SS} and S2S^2.
  • Nonnegative. In exact arithmetic every increment of SS is k−1kd2≥0\frac{k-1}{k}d^2 \ge 0. 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 wk>0w_k > 0, keep W=∑wkW = \sum w_k and use W←W+wkW \leftarrow W + w_k, M←M+(wk/W) dM \leftarrow M + (w_k/W)\,d and S←S+wk d (xk−M)S \leftarrow S + w_k\, d\,(x_k - M). This is West's (1979) weighted updating. With frequency weights, S/(W−1)S/(W - 1) is the sample variance of the expanded data.
  • Covariance. For pairs (xk,yk)(x_k, y_k), update both means and C←C+(xk−Mxold)(yk−Mynew)C \leftarrow C + (x_k - M_x^{\text{old}})(y_k - M_y^{\text{new}}). Then C/(n−1)C/(n-1) is the sample covariance; the vector form updates a covariance matrix by an outer product.
  • Merging. Two accumulators (na,Ma,Sa)(n_a, M_a, S_a) and (nb,Mb,Sb)(n_b, M_b, S_b) combine in O(1)O(1) operations. That is the Chan-Golub-LeVeque algorithm; Welford's update is its case nb=1n_b = 1.
  • Higher moments. The same approach updates the third and fourth central sums, for the skewness and the kurtosis of a stream.
  • Forgetting. Replacing 1/k1/k in line L4 by a fixed weight α\alpha gives the exponential moving average of the mean, which follows a drifting stream.
  • Shift first. Subtracting a rough estimate of the mean, for example x1x_1, from every value reduces κ\kappa; Chan, Golub and LeVeque show that a shift within SS/n\sqrt{\mathrm{SS}/n} of the mean gives κ<2\kappa < \sqrt 2 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 S←S+(xk−M)2S \leftarrow S + (x_k - M)^2 with the new MM adds too little: on the example it gives 1729/36≈48.031729/36 \approx 48.03 instead of 64. With the old mean in both factors, S←S+d2S \leftarrow S + d^2 adds d2/kd^2/k too much in each step. The two factors must use the old and the new mean.
  • Integer division. In a language where d/kd/k with integer operands truncates, line L4 is wrong for integer data. Convert to floating point first.
  • The divisor. Return S/(n−1)S/(n - 1) for the sample variance and S/nS/n for the divisor-nn variance, and say which one. For n=1n = 1, S/(n−1)S/(n-1) is undefined.
  • Not immune to bad conditioning. The error still grows with κ\kappa. 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.

stdist.pyI0RawGitHub
# 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 MkM_k and SkS_k 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 κ\kappa and recommended which to use.

References

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. 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)
  6. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of flops.worst
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example