Algorithms for calculating variance play a major role in computational statistics. A key difficulty in the design of good algorithms for this problem is that formulas for the variance may involve sums of squares, which can lead to numerical instability as well as to arithmetic overflow when dealing with large values.
Naïve algorithm A formula for calculating the variance of an entire population of size N is:
σ2=(x−x¯)2‾=(x2)‾−x¯2=∑i=1Nxi2N−(∑i=1NxiN)2 Using Bessel's correction to calculate an unbiased estimate of the population variance from a finite sample of n observations, the formula is:
s2=(∑i=1nxi2n−(∑i=1nxin)2)⋅nn−1. Therefore, a naïve algorithm to calculate the estimated variance is given by the following:
This algorithm can easily be adapted to compute the variance of a finite population: simply divide by n instead of n − 1 on the last line. Because SumSq and (Sum×Sum)/n can be very similar numbers, cancellation can lead to the precision of the result to be much less than the inherent precision of the floating-point arithmetic used to perform the computation. Thus this algorithm should not be used in practice, and several alternate, numerically stable, algorithms have been proposed. This is particularly bad if the standard deviation is small relative to the mean.
Computing shifted data The variance is invariant with respect to changes in a location parameter, a property which can be used to avoid the catastrophic cancellation in this formula.
Var(X−K)=Var(X). with K any constant, which leads to the new formula
σ2=∑i=1n(xi−K)2−(∑i=1n(xi−K))2/nn−1. The closer K is to the mean value, the more accurate the result will be, but just choosing any value inside the sample range will provide the desired stability. If the values (xi−K) are small, then there are no problems with the sum of its squares; on the contrary, if they are large, it necessarily means that the variance is large as well. In any case the second term in the formula is always smaller than the first one, therefore no cancellation may occur. The algorithm can be written in Python programming language as
Two-pass algorithm An alternative approach, using a different formula for the variance, first computes the sample mean,
x¯=∑j=1nxjn, and then computes the sum of the squares of the differences from the mean,
sample variance=s2=∑i=1n(xi−x¯)2n−1, where s is the standard deviation. This is given by the following code:
This piece of code, if run on CPython 3.12 and newer, is always numerically stable. This is because these versions use Neumaier's compensated summation scheme for the sum() function, making it resistant to repeated roundoff error. Many numerically oriented languages provide similar constructs. This algorithm, if implemented with a naive addition sum = 0; for x in data: sum += x; mean = sum / n, would only be numerically stable if n is small because of repeated round-off when adding a small number to a much, much larger one.
Incremental algorithms It is often useful to be able to compute the variance in a single pass, inspecting each value xi only once; for example, when the data is being collected without enough storage to keep all the values, or when costs of memory access dominate those of computation. For such an online algorithm, a recurrence relation is required between quantities from which the required statistics can be calculated in a numerically stable fashion.
Incremental shifted data Our shifted-data algorithm from before includes the simple updating of data in a loop, which is naturally incremental. It can be expressed as:
Welford's online algorithm Analogous to the two-pass algorithm above, it remains desirable to use the actual mean of the data instead of just picking the first element. The following formulas can be used to update the mean and (estimated) variance of the sequence, for an additional element xn. Here, x‾n=1n∑i=1nxi denotes the sample mean of the first n samples (x1,…,xn), σn2=1n∑i=1n(xi−x‾n)2 their biased sample variance, and sn2=1n−1∑i=1n(xi−x‾n)2 their unbiased sample variance.
x¯n=(n−1)x¯n−1+xnn=x¯n−1+xn−x¯n−1n σn2=(n−1)σn−12+(xn−x¯n−1)(xn−x¯n)n=σn−12+(xn−x¯n−1)(xn−x¯n)−σn−12n. sn2=n−2n−1sn−12+(xn−x¯n−1)2n=sn−12+(xn−x¯n−1)2n−sn−12n−1,n>1 These formulas suffer from numerical instability, as they repeatedly subtract a small number from a big number which scales with n. A better quantity for updating is the sum of squares of differences from the current mean, ∑i=1n(xi−x¯n)2, here denoted M2,n:
M2,n=M2,n−1+(xn−x¯n−1)(xn−x¯n)σn2=M2,nnsn2=M2,nn−1 The following algorithm was found by Welford, and it has been thoroughly analyzed. It is also common to denote Mk=x¯k and Sk=M2,k. An example Python implementation for Welford's algorithm is given below, using the same framework as the above "shifted data" algorithm:
This algorithm is much less prone to loss of precision due to catastrophic cancellation, but might not be as efficient because of the division operation inside the loop. For a particularly robust two-pass algorithm for computing the variance, one can first compute and subtract an estimate of the mean, and then use this algorithm on the residuals. The parallel algorithm below illustrates how to merge multiple sets of statistics calculated online.
Weighted incremental algorithm The algorithm can be extended to handle unequal sample weights, replacing the simple counter n with the sum of weights seen so far. West (1979) suggests this incremental algorithm:
Parallel algorithm Chan et al. note that Welford's online algorithm detailed above is a special case of an algorithm that works for combining arbitrary sets A and B:
nAB=nA+nBδ=x¯B−x¯Ax¯AB=x¯A+δ⋅nBnABM2,AB=M2,A+M2,B+δ2⋅nAnBnAB. This may be useful when, for example, multiple processing units may be assigned to discrete parts of the input. Chan's method for estimating the mean is numerically unstable when nA≈nB and both are large, because the numerical error in δ=x¯B−x¯A is not scaled down in the way that it is in the nB=1 case. In such cases, prefer x¯AB=nAx¯A+nBx¯BnAB. Reusing the WelfordVariance class from above, we have:
This algorithm allows one to divide a dataset into several pieces, run them in parallel, and then merge the results together. This enables parallelization in any way, including AVX, with GPUs, and computer clusters. The algorithm can also be adapted for higher-order statistics as well as covariance.
… excerpt ends here. Continue reading the full article.