Algorithm Search⌘K

Algorithmadvanced

Chan-Golub-LeVeque parallel variance algorithm

Also called pairwise variance algorithm, parallel variance merge.

Merges the counts, means and sums of squared deviations of two partitions into those of their union, so that variance can be computed in parallel or by divide and conquer.

Time
Θ(n) worst · best
Space
Θ(log n) extra
Counts
depth Θ(log n) worstflops 10 n - 9 worst
Where
n = the number of data values, at least 2
Properties
deterministicexact in exact arithmeticofflineparallelrecursive
Origin
Tony F. Chan, Gene H. Golub, Randall J. LeVeque, 1979

The Chan-Golub-LeVeque algorithm combines the summaries (na,xˉa,SSa)(n_a, \bar x_a, \mathrm{SS}_a) and (nb,xˉb,SSb)(n_b, \bar x_b, \mathrm{SS}_b) of two disjoint parts of a data set, each a count, a mean and a sum of squared deviations, into the summary of their union, in a constant number of operations. Because the merge is exact and associative, the sample variance of nn values can be computed by any tree of merges: in parallel with span Θ(log⁡n)\Theta(\log n), or by the pairwise recursion, whose rounding error grows more slowly than that of a one-pass loop. Welford's algorithm is the special case in which the second part has one value.

In plain words

Split the data into two piles and give each pile to a different worker. Each worker reports three numbers: how many values it has, their average, and their total squared distance from that average. To get the same three numbers for all the data, add the counts, and take the average of the two averages weighted by the counts. The total squared distance is the two totals plus a correction for the gap between the two averages: the square of the gap, times the two counts multiplied together, divided by the total count.

Since piles can be merged in any order and grouping, the data can be cut into many piles and the results merged in a tree. Cutting the data in halves again and again and merging back up also makes the rounding errors smaller than in a loop over the values one at a time.

The problem

The merge. The input is two summaries a=(na,ma,Ma)a = (n_a, m_a, M_a) and b=(nb,mb,Mb)b = (n_b, m_b, M_b), where (na,ma,Ma)(n_a, m_a, M_a) are the count, the mean and the sum of squared deviations ∑(x−ma)2\sum (x - m_a)^2 of a nonempty multiset AA of reals, and likewise for BB. The output is the summary of A⊎BA \uplus B. The data themselves are not available.

The variance. The input is x1,…,xnx_1, \ldots, x_n with n≥2n \ge 2. The output is xˉ\bar x, SS=∑i(xi−xˉ)2\mathrm{SS} = \sum_i (x_i - \bar x)^2 and S2=SS/(n−1)S^2 = \mathrm{SS}/(n-1), computed by merges.

The algorithm

  1. COMBINE((n_a, m_a, M_a), (n_b, m_b, M_b)) ▷ n_a, n_b ≥ 1
  2. 1n ← n_a + n_b
  3. 2δ ← m_b - m_a ▷ gap between the means
  4. 3m ← m_a + δ · n_b / n
  5. 4M ← M_a + M_b + δ · δ · n_a · n_b / n ▷ between-part term
  6. 5return (n, m, M)
  7. PAIRWISE(x, lo, hi) ▷ summary of x[lo .. hi - 1], hi - lo ≥ 1
  8. 6if hi - lo = 1 then return (1, x[lo], 0)
  9. 7mid ← lo + ⌊(hi - lo) / 2⌋
  10. 8a ← PAIRWISE(x, lo, mid) ▷ lines L8 and L9 may run in parallel
  11. 9b ← PAIRWISE(x, mid, hi)
  12. 10return COMBINE(a, b)
  13. PAIRWISE-VARIANCE(x_1, ..., x_n) ▷ n ≥ 2
  14. 11(n, m, M) ← PAIRWISE(x, 0, n)
  15. 12return m, M / (n - 1), M

Line L3 moves the mean of AA toward the mean of BB by the fraction nb/nn_b/n of the gap. Line L4 adds the between-part sum of squares, na(ma−m)2+nb(mb−m)2n_a(m_a - m)^2 + n_b(m_b - m)^2, written in the form δ2nanb/n\delta^2 n_a n_b/n. Both lines use the difference δ\delta of two means, not the difference of two large sums of squares, so nothing in the merge cancels catastrophically.

Chan, Golub and LeVeque state the merge with the sums Ta=namaT_a = n_a m_a and Tb=nbmbT_b = n_b m_b in place of the means, as M=Ma+Mb+nanb n(nbnaTa−Tb)2M = M_a + M_b + \frac{n_a}{n_b\, n}\big(\frac{n_b}{n_a} T_a - T_b\big)^2 (their formula (1.5b)). Since nbnaTa−Tb=−nbδ\frac{n_b}{n_a}T_a - T_b = -n_b\delta, it is the same number in exact arithmetic. For equal halves, na=nb=hn_a = n_b = h, it reduces to M=Ma+Mb+(Ta−Tb)2/(2h)M = M_a + M_b + (T_a - T_b)^2/(2h) (their (1.6)).

Any other tree of merges gives the same exact result: one Welford accumulator per thread, or per block of a file, followed by a tree of COMBINE calls, is the usual parallel form.

Example

Take x=(3,7,7,9,14)x = (3, 7, 7, 9, 14), in exact arithmetic. PAIRWISE splits it at mid=2mid = 2 into (3,7)(3, 7) and (7,9,14)(7, 9, 14), and the second part at its middle into (7)(7) and (9,14)(9, 14).

merge aa bb δ\delta mm MM
(3)+(7)(3) + (7) (1,3,0)(1, 3, 0) (1,7,0)(1, 7, 0) 4 5 0+0+16⋅1⋅1/2=80 + 0 + 16 \cdot 1 \cdot 1/2 = 8
(9)+(14)(9) + (14) (1,9,0)(1, 9, 0) (1,14,0)(1, 14, 0) 5 23/223/2 25/225/2
(7)+(9,14)(7) + (9, 14) (1,7,0)(1, 7, 0) (2,23/2,25/2)(2, 23/2, 25/2) 9/29/2 10 25/2+814⋅23=2625/2 + \frac{81}{4}\cdot\frac{2}{3} = 26
(3,7)+(7,9,14)(3, 7) + (7, 9, 14) (2,5,8)(2, 5, 8) (3,10,26)(3, 10, 26) 5 8 8+26+25⋅6/5=648 + 26 + 25 \cdot 6/5 = 64

So xˉ=8\bar x = 8, SS=64\mathrm{SS} = 64 and S2=16S^2 = 16, as on sample variance. The last merge reads: δ=10−5=5\delta = 10 - 5 = 5, m=5+5⋅3/5=8m = 5 + 5 \cdot 3/5 = 8 and M=8+26+25⋅2⋅3/5=64M = 8 + 26 + 25 \cdot 2 \cdot 3/5 = 64.

Correctness

With mm the mean of the union, ma−m=−δnb/nm_a - m = -\delta n_b/n and mb−m=δna/nm_b - m = \delta n_a/n, so the term of line L4 equals na(ma−m)2+nb(mb−m)2n_a(m_a - m)^2 + n_b(m_b - m)^2. The shift identity ∑v∈A(v−m)2=Ma+na(ma−m)2\sum_{v \in A}(v - m)^2 = M_a + n_a(m_a - m)^2, applied to AA and to BB, then shows that MM is the sum of squared deviations of the union around its mean. So one merge is exact. The same identity, with the counts as weights, shows that merging three summaries in either grouping gives Ma+Mb+Mc+∑ini(mi−m)2M_a + M_b + M_c + \sum_i n_i(m_i - m)^2, so COMBINE is associative and commutative, and PAIRWISE is correct by induction on the length. The full proofs are below.

Proof: The merge formula is exact, associative and commutativefull

The arithmetic is exact. A summary is a triple (n,m,M)(n, m, M) with n>0n > 0. The summary of a nonempty finite list x1,…,xkx_1, \ldots, x_k is σ(x)=(k,xˉ,SS)\sigma(x) = (k, \bar x, \mathrm{SS}) with xˉ=1k∑ixi\bar x = \frac1k \sum_i x_i and SS=∑i(xi−xˉ)2\mathrm{SS} = \sum_i (x_i - \bar x)^2.

Lemma 1 (weighted shift). Let w1,…,wr>0w_1, \ldots, w_r > 0, W=∑jwjW = \sum_j w_j, real y1,…,yry_1, \ldots, y_r and μ=1W∑jwjyj\mu = \frac1W\sum_j w_j y_j. Then for every real cc,

∑j=1rwj(yj−c)2=∑j=1rwj(yj−μ)2+W(μ−c)2.\sum_{j=1}^r w_j (y_j - c)^2 = \sum_{j=1}^r w_j (y_j - \mu)^2 + W(\mu - c)^2.

Proof. Write yj−c=(yj−μ)+(μ−c)y_j - c = (y_j - \mu) + (\mu - c) and expand. The cross terms add up to 2(μ−c)∑jwj(yj−μ)=2(μ−c)(Wμ−Wμ)=02(\mu - c)\sum_j w_j(y_j - \mu) = 2(\mu - c)(W\mu - W\mu) = 0, and the last terms add up to W(μ−c)2W(\mu - c)^2. □\square

Lemma 2 (the merge in centred form). For summaries a=(na,ma,Ma)a = (n_a, m_a, M_a) and b=(nb,mb,Mb)b = (n_b, m_b, M_b), COMBINE (lines L1 to L5) returns (n,m,M)(n, m, M) with

n=na+nb,m=nama+nbmbn,M=Ma+Mb+na(ma−m)2+nb(mb−m)2.n = n_a + n_b, \qquad m = \frac{n_a m_a + n_b m_b}{n}, \qquad M = M_a + M_b + n_a (m_a - m)^2 + n_b (m_b - m)^2.

Proof. Line L1 gives nn. With δ=mb−ma\delta = m_b - m_a (line L2), line L3 gives m=ma+δnb/n=(nma+nbmb−nbma)/n=(nama+nbmb)/nm = m_a + \delta n_b/n = (n m_a + n_b m_b - n_b m_a)/n = (n_a m_a + n_b m_b)/n. Then ma−m=−δnb/nm_a - m = -\delta n_b/n and mb−m=δna/nm_b - m = \delta n_a/n, so

na(ma−m)2+nb(mb−m)2=δ2(nanb2+nbna2)n2=δ2nanb(na+nb)n2=δ2nanbn,n_a(m_a - m)^2 + n_b(m_b - m)^2 = \frac{\delta^2 (n_a n_b^2 + n_b n_a^2)}{n^2} = \frac{\delta^2 n_a n_b (n_a + n_b)}{n^2} = \frac{\delta^2 n_a n_b}{n},

which is the term that line L4 adds to Ma+MbM_a + M_b. □\square

Theorem 1 (merge). If a=σ(x)a = \sigma(x) and b=σ(y)b = \sigma(y) for nonempty lists xx and yy, then COMBINE(a,b)=σ(x⋅y)(a, b) = \sigma(x \cdot y), the summary of the concatenation.

Proof. Let (n,m,M)(n, m, M) = COMBINE(a,b)(a, b). The list x⋅yx \cdot y has na+nb=nn_a + n_b = n values with sum nama+nbmb=nmn_a m_a + n_b m_b = n m, so its mean is mm by Lemma 2. Its sum of squared deviations splits over the two parts:

∑v∈x⋅y(v−m)2=∑v∈x(v−m)2+∑v∈y(v−m)2=Ma+na(ma−m)2+Mb+nb(mb−m)2,\sum_{v \in x \cdot y}(v - m)^2 = \sum_{v \in x}(v - m)^2 + \sum_{v \in y}(v - m)^2 = M_a + n_a(m_a - m)^2 + M_b + n_b(m_b - m)^2,

by Lemma 1 with unit weights and c=mc = m, once for xx (mean mam_a, SS=Ma\mathrm{SS} = M_a) and once for yy. By Lemma 2 this is MM. □\square

Theorem 2 (associativity and commutativity). COMBINE is commutative, and associative on all summaries, not only on summaries of data.

Proof. Lemma 2 is symmetric in aa and bb, so COMBINE is commutative. For three summaries a,b,ca, b, c, let mabm_{ab} be the mean of COMBINE(a,b)(a, b) and mm the mean of the full merge, which is 1na+nb+nc(nama+nbmb+ncmc)\frac{1}{n_a + n_b + n_c}(n_a m_a + n_b m_b + n_c m_c) in either order. By Lemma 2 twice, the MM of COMBINE(COMBINE(a,b),c)(a, b), c) is

Ma+Mb+Mc+[na(ma−mab)2+nb(mb−mab)2+(na+nb)(mab−m)2]+nc(mc−m)2.M_a + M_b + M_c + \big[n_a(m_a - m_{ab})^2 + n_b(m_b - m_{ab})^2 + (n_a + n_b)(m_{ab} - m)^2\big] + n_c(m_c - m)^2.

Lemma 1 with weights na,nbn_a, n_b, points ma,mbm_a, m_b (whose weighted mean is mabm_{ab}) and c=mc = m turns the bracket into na(ma−m)2+nb(mb−m)2n_a(m_a - m)^2 + n_b(m_b - m)^2. So

M=Ma+Mb+Mc+∑i∈{a,b,c}ni(mi−m)2,M = M_a + M_b + M_c + \sum_{i \in \{a, b, c\}} n_i (m_i - m)^2,

which is symmetric in a,b,ca, b, c. The same expression results from COMBINE(a(a, COMBINE(b,c))(b, c)), so the two are equal. □\square

Hence the summaries with COMBINE form a commutative semigroup, and every tree of merges over a partition of the data into nonempty parts gives the same exact result σ(x)\sigma(x). Adding the triple (0,0,0)(0, 0, 0) as an identity, with the rule that COMBINE returns the other argument when one count is 0, makes it a commutative monoid.

Theorem 3 (PAIRWISE). For hi−lo≥1hi - lo \ge 1, PAIRWISE(x,lo,hi)(x, lo, hi) returns σ(x[lo…hi−1])\sigma(x[lo \ldots hi-1]).

Proof. By induction on ℓ=hi−lo\ell = hi - lo. For ℓ=1\ell = 1, line L6 returns (1,x[lo],0)(1, x[lo], 0), the summary of one value. For ℓ≥2\ell \ge 2, line L7 gives lo<mid<hilo < mid < hi, since 1≤⌊ℓ/2⌋<ℓ1 \le \lfloor \ell/2 \rfloor < \ell. Both calls of lines L8 and L9 have length between 1 and ℓ−1\ell - 1, so by induction they return σ(x[lo…mid−1])\sigma(x[lo \ldots mid-1]) and σ(x[mid…hi−1])\sigma(x[mid \ldots hi-1]). By Theorem 1, line L10 returns the summary of their concatenation, which is x[lo…hi−1]x[lo \ldots hi-1]. □\square

Corollary. For n≥2n \ge 2, PAIRWISE-VARIANCE returns the mean, SS/(n−1)\mathrm{SS}/(n - 1) and SS\mathrm{SS} of x1,…,xnx_1, \ldots, x_n. Each call on length ℓ≥2\ell \ge 2 makes two calls on strictly shorter lengths, so the recursion terminates.

Cost. The recursion tree has nn leaves and n−1n - 1 internal nodes, one COMBINE each. Counting the counts as integers, COMBINE does 10 floating-point operations: one subtraction in line L2; a multiplication, a division and an addition in line L3; and in line L4 the products δ⋅δ\delta \cdot \delta, ⋅ na\cdot\, n_a, ⋅ nb\cdot\, n_b, the division by nn and two additions. With the division of line L12 the total is 10(n−1)+1=10n−910(n - 1) + 1 = 10n - 9. The recursion depth is ⌈log⁡2n⌉\lceil \log_2 n \rceil, so the stack is Θ(log⁡n)\Theta(\log n). The two calls of lines L8 and L9 are independent, so with them run in parallel the span satisfies D(ℓ)=D(⌈ℓ/2⌉)+O(1)D(\ell) = D(\lceil \ell/2 \rceil) + O(1), which gives D(n)=Θ(log⁡n)D(n) = \Theta(\log n), with work Θ(n)\Theta(n). □\square

Complexity

PAIRWISE on nn values makes n−1n - 1 merges. Counting the counts as integers, each merge does 10 floating-point operations (one in line L2, three in line L3, six in line L4), and line L12 adds one division, so the count is exactly 10n−910n - 9. Chan, Golub and LeVeque count the sum form for nn a power of 2 as 2n2n multiplications and 4n4n additions; their form needs fewer operations per merge.

  • Work and span. In the work-span model with lines L8 and L9 in parallel, the work is Θ(n)\Theta(n) and the span is Θ(log⁡n)\Theta(\log n). With pp processors, each running Welford's algorithm on a block of n/pn/p values and then merging in a tree, the time is Θ(n/p+log⁡p)\Theta(n/p + \log p).
  • Space. The recursion is ⌈log⁡2n⌉\lceil \log_2 n \rceil deep, so the stack is Θ(log⁡n)\Theta(\log n). A bottom-up version that keeps one summary per level of a binary counter also uses Θ(log⁡n)\Theta(\log n) summaries and reads the data once, in order.

Rounding error. With the condition number κ=1+nxˉ2/SS\kappa = \sqrt{1 + n\bar x^2/\mathrm{SS}} defined on Welford's algorithm, Table 1 of Chan, Golub and LeVeque gives the bound nκun\kappa u for the updating algorithms and κulog⁡n\kappa u \log n for the pairwise algorithm, with small constants dropped. They mark the pairwise bound as a conjecture, based on the bound for Youngs and Cramer's updating and on experiments. Barlow (1990) gave a rounding error analysis of the pairwise algorithm and proved that it is numerically stable. The same improvement from nn to log⁡n\log n is proved for plain sums by pairwise summation.

Measured errors. The relative error of S2S^2 in double precision against the exact value of the stored data, computed with fractions.Fraction, for data 106+Zi10^6 + Z_i with ZiZ_i standard normal (κ≈106\kappa \approx 10^6). The rows come from random.Random(1), one run each, drawn after the four rows of the table on Welford's algorithm, in the order 1000, 10410^4 (that table's third row), 10510^5.

nn textbook Welford pairwise
1000 2.9×10−32.9 \times 10^{-3} 1.4×10−111.4 \times 10^{-11} 3.7×10−123.7 \times 10^{-12}
10410^4 6.4×10−36.4 \times 10^{-3} 2.1×10−112.1 \times 10^{-11} 7.2×10−137.2 \times 10^{-13}
10510^5 2.4×10−22.4 \times 10^{-2} 4.5×10−124.5 \times 10^{-12} 3.1×10−133.1 \times 10^{-13}

These are single runs, not bounds. In each row the pairwise error is 4 to 30 times smaller than the Welford error, and both are far below their bounds. One run per row cannot show the growth in nn that the bounds describe; the Welford error at n=105n = 10^5 happens to be the smallest of its column.

Properties

  • Exact in exact arithmetic, for every split and every tree of merges.
  • Associative and commutative. The summaries form a commutative monoid with the identity (0,0,0)(0, 0, 0), if COMBINE returns the other argument when one count is 0. So the merge is a valid operator for a parallel reduction, a segment tree, or the combine step of MapReduce.
  • Order dependent in floating point. Different trees give results that differ in the last digits.
  • Constant size summaries. A part of any size is described by three numbers.

Variants and improvements

  • Welford's algorithm. COMBINE with b=(1,x,0)b = (1, x, 0) gives δ=x−ma\delta = x - m_a, m=ma+δ/nm = m_a + \delta/n and M=Ma+n−1nδ2M = M_a + \frac{n-1}{n}\delta^2, which is Welford's update.
  • Covariance. For pairs, merge the two means separately and the co-moment by C=Ca+Cb+δxδynanb/nC = C_a + C_b + \delta_x \delta_y n_a n_b/n; the vector version merges covariance matrices with the outer product δδT\delta\delta^{\mathsf T}.
  • Weights. Replace the counts by sums of weights; the formulas do not change.
  • Higher moments. The third and fourth central sums also merge in closed form, with more terms in δ\delta.
  • Removing a part. Solving the merge for aa given the union and bb removes a part, but it subtracts and can lose accuracy.
  • Corrected two-pass. When the data fit in memory, Chan, Golub and LeVeque recommend the corrected two-pass algorithm, SS=∑i(xi−xˉ)2−1n(∑i(xi−xˉ))2\mathrm{SS} = \sum_i (x_i - \bar x)^2 - \frac1n\big(\sum_i (x_i - \bar x)\big)^2, where the second term estimates the rounding error of the first.

When to use it

Use the merge whenever partial results must be combined: threads, GPU blocks, distributed workers, database partitions, or a stream summarized per time window and later rolled up. Use the pairwise recursion when the data are in memory and the accuracy of a one-pass method is not enough but a second pass is not wanted. When one pass over a stream on one processor is all that is needed, Welford's algorithm is simpler.

Pitfalls

  • Merging variances instead of sums. Averaging the two variances, even weighted by counts, ignores the between-part term δ2nanb/n\delta^2 n_a n_b/n. For (3,7)(3, 7) and (7,9,14)(7, 9, 14) the parts have SS\mathrm{SS} 8 and 26, which add to 34, while the union has 64.
  • The divisor. Merge the sums of squared deviations MM, not S2S^2 or σ^2\hat\sigma^2, and divide only at the end by n−1n - 1 or nn, saying which one.
  • Integer overflow. In a language with fixed-width integers, nanbn_a n_b can overflow; compute it in floating point.
  • Empty parts. Line L3 divides by nn, so two empty parts cannot be merged; treat a part with count 0 as the identity.
  • Textbook parts. If each part computes its MM by the textbook formula ∑x2−nama2\sum x^2 - n_a m_a^2, the merge inherits that cancellation. Compute the parts with Welford's algorithm or by pairwise merging.

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.

chan_parallel_variance.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chan-parallel-variance/. The authors are listed in prov/EJXH8E.jsonl.

from collections.abc import Sequence
from typing import NamedTuple


class Summary(NamedTuple):
    """Count n, mean and sum of squared deviations m2 of a nonempty part."""

    n: int
    mean: float
    m2: float


def combine(a: Summary, b: Summary) -> Summary:
    """Return the summary of the union of the parts summarized by a and b.

    Precondition: a.n >= 0, b.n >= 0; a part with n = 0 is the identity.
    Cost: 10 arithmetic operations. Exact for Fraction means and sums.
    """
    if a.n == 0:
        return b
    if b.n == 0:
        return a
    n = a.n + b.n  # @line L1
    delta = b.mean - a.mean  # @line L2
    mean = a.mean + delta * b.n / n  # @line L3
    m2 = a.m2 + b.m2 + delta * delta * a.n * b.n / n  # @line L4
    return Summary(n, mean, m2)  # @line L5


def summarize(xs: Sequence[float], lo: int = 0, hi: int | None = None) -> Summary:
    """Summary of xs[lo:hi] by pairwise merging. Precondition: hi - lo >= 1.

    Cost: Theta(hi - lo) operations and Theta(log(hi - lo)) recursion depth.
    """
    if hi is None:
        hi = len(xs)
    if hi - lo == 1:  # @line L6
        return Summary(1, xs[lo], 0 * xs[lo])
    mid = lo + (hi - lo) // 2  # @line L7
    a = summarize(xs, lo, mid)  # @line L8
    b = summarize(xs, mid, hi)  # @line L9
    return combine(a, b)  # @line L10


def chan_parallel_variance(xs: Sequence[float]) -> tuple[float, float, float]:
    """Return (mean, sample variance with divisor n - 1, sum of squared deviations).

    Precondition: len(xs) >= 2. Cost: 10 n - 9 arithmetic operations.
    """
    if len(xs) < 2:
        raise ValueError("need at least two values")
    n, mean, m2 = summarize(xs, 0, len(xs))  # @line L11
    return mean, m2 / (n - 1), m2  # @line L12
test_chan_parallel_variance.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chan-parallel-variance/. The authors are listed in prov/EJXH8E.jsonl.

import math
import random
from fractions import Fraction

from chan_parallel_variance import Summary, chan_parallel_variance, combine, summarize


def exact_summary(xs):
    """Oracle: the two-pass formula in exact arithmetic."""
    n = len(xs)
    m = sum(xs, Fraction(0)) / n
    return Summary(n, m, sum(((x - m) ** 2 for x in xs), Fraction(0)))


def welford(xs):
    """Welford's one-value update, written out independently."""
    k, m, s = 0, Fraction(0), Fraction(0)
    for x in xs:
        k += 1
        d = x - m
        m += d / k
        s += d * (x - m)
    return Summary(k, m, s)


def random_tree_merge(rng, parts):
    """Merge a list of summaries in a random order and a random tree shape."""
    parts = list(parts)
    while len(parts) > 1:
        i = rng.randrange(len(parts) - 1)
        a, b = parts[i], parts[i + 1]
        if rng.random() < 0.5:
            a, b = b, a
        parts[i:i + 2] = [combine(a, b)]
    return parts[0]


def test_running_example():
    a = exact_summary([Fraction(3), Fraction(7)])
    b = exact_summary([Fraction(7), Fraction(9), Fraction(14)])
    assert a == (2, 5, 8) and b == (3, 10, 26)
    assert combine(a, b) == (5, 8, 64)
    assert chan_parallel_variance([Fraction(v) for v in (3, 7, 7, 9, 14)]) == (8, 16, 64)


def test_split_and_pairwise_equal_two_pass():
    rng = random.Random(1983)
    for _ in range(600):
        n = rng.randint(2, 14)
        xs = [Fraction(rng.randint(-40, 40), rng.randint(1, 7)) for _ in range(n)]
        cut = rng.randint(1, n - 1)
        whole = exact_summary(xs)
        assert combine(exact_summary(xs[:cut]), exact_summary(xs[cut:])) == whole
        assert summarize(xs) == whole
        assert welford(xs) == whole
        m, v, s = chan_parallel_variance(xs)
        assert (m, s) == (whole.mean, whole.m2) and v == whole.m2 / (n - 1)


def test_any_tree_of_merges_gives_the_same_result():
    rng = random.Random(77)
    for _ in range(500):
        n = rng.randint(2, 12)
        xs = [Fraction(rng.randint(-20, 20)) for _ in range(n)]
        cuts = sorted(rng.sample(range(1, n), rng.randint(0, n - 1)))
        bounds = [0] + cuts + [n]
        parts = [exact_summary(xs[i:j]) for i, j in zip(bounds, bounds[1:])]
        assert random_tree_merge(rng, parts) == exact_summary(xs)


def test_associative_and_commutative_on_arbitrary_summaries():
    rng = random.Random(5)

    def rand_summary():
        return Summary(rng.randint(1, 9), Fraction(rng.randint(-30, 30), rng.randint(1, 5)),
                       Fraction(rng.randint(0, 50), rng.randint(1, 5)))

    for _ in range(500):
        a, b, c = rand_summary(), rand_summary(), rand_summary()
        assert combine(a, b) == combine(b, a)
        assert combine(combine(a, b), c) == combine(a, combine(b, c))


def test_welford_is_the_case_of_one_new_value():
    rng = random.Random(11)
    for _ in range(500):
        k = rng.randint(1, 20)
        a = Summary(k, Fraction(rng.randint(-50, 50), 3), Fraction(rng.randint(0, 99), 7))
        x = Fraction(rng.randint(-50, 50), 2)
        d = x - a.mean
        merged = combine(a, Summary(1, x, Fraction(0)))
        assert merged.mean == a.mean + d / (k + 1)
        assert merged.m2 == a.m2 + d * (x - merged.mean) == a.m2 + Fraction(k, k + 1) * d * d


def test_identity_and_short_input():
    a = Summary(3, Fraction(2), Fraction(5))
    empty = Summary(0, Fraction(0), Fraction(0))
    assert combine(a, empty) == a and combine(empty, a) == a
    try:
        chan_parallel_variance([1.0])
    except ValueError:
        pass
    else:
        raise AssertionError("expected ValueError")


def test_float_error_on_shifted_data():
    rng = random.Random(3)
    u = 2.0 ** -53
    for c in (0.0, 1e4, 1e6):
        for n in (2, 17, 1000):
            xs = [c + rng.gauss(0.0, 1.0) for _ in range(n)]
            whole = exact_summary([Fraction(x) for x in xs])
            _, v, _ = chan_parallel_variance(xs)
            kappa = math.sqrt(1 + n * float(whole.mean) ** 2 / float(whole.m2))
            rel = abs(Fraction(v) - whole.m2 / (n - 1)) / (whole.m2 / (n - 1))
            assert rel <= 50 * kappa * u * max(1.0, math.log2(n))

History

Chan, Golub and LeVeque gave the formula for combining two samples and the pairwise algorithm in a Stanford report in 1979 and surveyed the algorithms for the sample variance in The American Statistician in 1983, with error bounds in terms of the condition number κ\kappa. Their bound for the pairwise algorithm was stated as a conjecture. Barlow (1990) proved, by a rounding error analysis, that the pairwise algorithm is numerically stable.

References

  1. 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 formulas (1.5) and (1.6) for combining two samples, the pairwise algorithm, Table 1 of error bounds, and Section 4 on parallel use)
  2. Updating formulae and a pairwise algorithm for computing sample variances, the whole report (the first presentation of the pairwise algorithm)
  3. Jesse L. Barlow, Error analysis of a pairwise summation algorithm to compute the sample variance, Numerische Mathematik 58(6), 1990, pp. 583 to 590 (the rounding error analysis that proves the pairwise algorithm stable)
  4. Nicholas J. Higham, Accuracy and Stability of Numerical Algorithms, second edition, SIAM, 2002, Section 1.9 (computing the sample variance)

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 depth.worst
  • 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