# Difference between revisions of "Algorithms for calculating variance"

{{ safesubst:#invoke:Unsubst||$N=Merge from |date=__DATE__ |$B= Template:MboxTemplate:DMCTemplate:Merge partner }}

Algorithms for calculating variance play a major role in statistical computing. A key problem 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:

$\sigma ^{2}=\displaystyle {\frac {\sum _{i=1}^{N}x_{i}^{2}-(\sum _{i=1}^{N}x_{i})^{2}/N}{N}}.\!$ A formula for calculating an unbiased estimate of the population variance from a finite sample of n observations is:

$s^{2}=\displaystyle {\frac {\sum _{i=1}^{n}x_{i}^{2}-(\sum _{i=1}^{n}x_{i})^{2}/n}{n-1}}.\!$ Therefore a naive algorithm to calculate the estimated variance is given by the following:

def naive_variance(data):
n = 0
Sum = 0
Sum_sqr = 0

for x in data:
n = n + 1
Sum = Sum + x
Sum_sqr = Sum_sqr + x*x

variance = (Sum_sqr - (Sum*Sum)/n)/(n - 1)
return variance


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 Sum_sqr 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. This is particularly bad if the standard deviation is small relative to the mean. However, the algorithm can be improved by adopting the method of the assumed mean.

## Two-pass algorithm

An alternative approach, using a different formula for the variance, first computes the sample mean,

${\bar {x}}=\displaystyle {\frac {\sum _{j=1}^{n}x_{j}}{n}}$ ,

and then computes the sum of the squares of the differences from the mean,

${\mathrm {variance} }=s^{2}=\displaystyle {\frac {\sum _{i=1}^{n}(x_{i}-{\bar {x}})^{2}}{n-1}}\!$ ,

where s is the standard deviation. This is given by the following pseudocode:

def two_pass_variance(data):
n    = 0
sum1 = 0
sum2 = 0

for x in data:
n    = n + 1
sum1 = sum1 + x

mean = sum1/n

for x in data:
sum2 = sum2 + (x - mean)*(x - mean)

variance = sum2/(n - 1)
return variance


This algorithm is always numerically stable, unless n is large. Although it can be worse if much of the data is very close to but not precisely equal to the mean and some are quite far away from it{{ safesubst:#invoke:Unsubst||date=__DATE__ |\$B= {{#invoke:Category handler|main}}{{#invoke:Category handler|main}}[citation needed] }}.

The results of both of these simple algorithms (I and II) can depend inordinately on the ordering of the data and can give poor results for very large data sets due to repeated roundoff error in the accumulation of the sums. Techniques such as compensated summation can be used to combat this error to a degree.

### Compensated variant

The compensated-summation version of the algorithm above reads:

def compensated_variance(data):
n = 0
sum1 = 0
for x in data:
n = n + 1
sum1 = sum1 + x
mean = sum1/n

sum2 = 0
sum3 = 0
for x in data:
sum2 = sum2 + (x - mean)**2
sum3 = sum3 + (x - mean)
variance = (sum2 - sum3**2/n)/(n - 1)
return variance


## Online algorithm

It is often useful to be able to compute the variance in a single pass, inspecting each value $x_{i}$ only once; for example, when the data are 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.

The following formulas can be used to update the mean and (estimated) variance of the sequence, for an additional element $x_{\mathrm {new} }$ . Here, Template:Overlinen denotes the sample mean of the first n samples (x1, ..., xn), s2n their sample variance, and σ2N their population variance.

${\bar {x}}_{n}={\frac {(n-1)\,{\bar {x}}_{n-1}+x_{n}}{n}}={\bar {x}}_{n-1}+{\frac {x_{n}-{\bar {x}}_{n-1}}{n}}\!$ $s_{n}^{2}={\frac {(n-2)}{(n-1)}}\,s_{n-1}^{2}+{\frac {(x_{n}-{\bar {x}}_{n-1})^{2}}{n}},\quad n>1$ $\sigma _{N}^{2}={\frac {(N-1)\,\sigma _{N-1}^{2}+(x_{N}-{\bar {x}}_{N-1})(x_{N}-{\bar {x}}_{N})}{N}}.$ It turns out that a more suitable quantity for updating is the sum of squares of differences from the (current) mean, $\textstyle \sum _{i=1}^{n}(x_{i}-{\bar {x}}_{n})^{2}$ , here denoted $M_{2,n}$ :

$M_{2,n}\!=M_{2,n-1}+(x_{n}-{\bar {x}}_{n-1})(x_{n}-{\bar {x}}_{n})$ $s_{n}^{2}={\frac {M_{2,n}}{n-1}}$ $\sigma _{N}^{2}={\frac {M_{2,N}}{N}}$ A numerically stable algorithm is given below. It also computes the mean. This algorithm is due to Knuth, who cites Welford, and it has been thoroughly analyzed. It is also common to denote $M_{k}={\bar {x}}_{k}$ and $S_{k}=M_{2,k}$ .

def online_variance(data):
n = 0
mean = 0
M2 = 0

for x in data:
n = n + 1
delta = x - mean
mean = mean + delta/n
M2 = M2 + delta*(x - mean)

variance = M2/(n - 1)
return variance


This algorithm is much less prone to loss of precision due to massive 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, 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:

def weighted_incremental_variance(dataWeightPairs):
sumweight = 0
mean = 0
M2 = 0

for x, weight in dataWeightPairs:  # Alternatively "for x, weight in zip(data, weights):"
temp = weight + sumweight
delta = x - mean
R = delta * weight / temp
mean = mean + R
M2 = M2 + sumweight * delta * R  # Alternatively, "M2 = M2 + weight * delta * (x−mean)"
sumweight = temp

variance_n = M2/sumweight
variance = variance_n * len(dataWeightPairs)/(len(dataWeightPairs) - 1)


## Parallel algorithm

Chan et al. note that the above online algorithm III is a special case of an algorithm that works for any partition of the sample $X$ into sets $X_{A}$ , $X_{B}$ :

$\delta \!={\bar {x}}_{B}-{\bar {x}}_{A}$ ${\bar {x}}_{X}={\bar {x}}_{A}+\delta \cdot {\frac {n_{B}}{n_{X}}}$ $M_{2,X}=M_{2,A}+M_{2,B}+\delta ^{2}\cdot {\frac {n_{A}n_{B}}{n_{X}}}$ .

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 $n_{A}\approx n_{B}$ and both are large, because the numerical error in ${\bar {x}}_{B}-{\bar {x}}_{A}$ is not scaled down in the way that it is in the $n_{B}=1$ case. In such cases, prefer ${\bar {x}}_{X}={\frac {n_{A}{\bar {x}}_{A}+n_{B}{\bar {x}}_{B}}{n_{A}+n_{B}}}$ .

## Example

Assume that all floating point operations use the standard IEEE 754 double-precision arithmetic. Consider the sample (4, 7, 13, 16) from an infinite population. Based on this sample, the estimated population mean is 10, and the unbiased estimate of population variance is 30. Both Algorithm I and Algorithm II compute these values correctly. Next consider the sample (108 + 4, 108 + 7, 108 + 13, 108 + 16), which gives rise to the same estimated variance as the first sample. Algorithm II computes this variance estimate correctly, but Algorithm I returns 29.333333333333332 instead of 30. While this loss of precision may be tolerable and viewed as a minor flaw of Algorithm I, it is easy to find data that reveal a major flaw in the naive algorithm: Take the sample to be (109 + 4, 109 + 7, 109 + 13, 109 + 16). Again the estimated population variance of 30 is computed correctly by Algorithm II, but the naive algorithm now computes it as −170.66666666666666. This is a serious problem with Algorithm I and is due to catastrophic cancellation in the subtraction of two similar numbers at the final stage of the algorithm.

## Higher-order statistics

Terriberry extends Chan's formulae to calculating the third and fourth central moments, needed for example when estimating skewness and kurtosis:

$M_{3,X}=M_{3,A}+M_{3,B}+\delta ^{3}{\frac {n_{A}n_{B}(n_{A}-n_{B})}{n_{X}^{2}}}+3\delta {\frac {n_{A}M_{2,B}-n_{B}M_{2,A}}{n_{X}}}$ {\begin{aligned}M_{4,X}=M_{4,A}+M_{4,B}&+\delta ^{4}{\frac {n_{A}n_{B}\left(n_{A}^{2}-n_{A}n_{B}+n_{B}^{2}\right)}{n_{X}^{3}}}\\&+6\delta ^{2}{\frac {n_{A}^{2}M_{2,B}+n_{B}^{2}M_{2,A}}{n_{X}^{2}}}+4\delta {\frac {n_{A}M_{3,B}-n_{B}M_{3,A}}{n_{X}}}\\\end{aligned}} skewness: $g_{1}={\frac {{\sqrt {n}}M_{3}}{M_{2}^{3/2}}},$ kurtosis: $g_{2}={\frac {nM_{4}}{M_{2}^{2}}}-3.$ For the incremental case (i.e., $B=\{x\}$ ), this simplifies to:

$\delta \!=x-m$ $m'=m+{\frac {\delta }{n}}$ $M_{2}'=M_{2}+\delta ^{2}{\frac {n-1}{n}}$ $M_{3}'=M_{3}+\delta ^{3}{\frac {(n-1)(n-2)}{n^{2}}}-{\frac {3\delta M_{2}}{n}}$ $M_{4}'=M_{4}+{\frac {\delta ^{4}(n-1)(n^{2}-3n+3)}{n^{3}}}+{\frac {6\delta ^{2}M_{2}}{n^{2}}}-{\frac {4\delta M_{3}}{n}}$ By preserving the value $\delta /n$ , only one division operation is needed and the higher-order statistics can thus be calculated for little incremental cost.

An example of the online algorithm for kurtosis implemented as described is:

def online_kurtosis(data):
n = 0
mean = 0
M2 = 0
M3 = 0
M4 = 0

for x in data:
n1 = n
n = n + 1
delta = x - mean
delta_n = delta / n
delta_n2 = delta_n * delta_n
term1 = delta * delta_n * n1
mean = mean + delta_n
M4 = M4 + term1 * delta_n2 * (n*n - 3*n + 3) + 6 * delta_n2 * M2 - 4 * delta_n * M3
M3 = M3 + term1 * delta_n * (n - 2) - 3 * delta_n * M2
M2 = M2 + term1

kurtosis = (n*M4) / (M2*M2) - 3
return kurtosis


Pébay further extends these results to arbitrary-order central moments, for the incremental and the pairwise cases. One can also find there similar formulas for covariance.

Choi and Sweetman  offer two alternative methods to compute the skewness and kurtosis, each of which can save substantial computer memory requirements and CPU time in certain applications. The first approach is to compute the statistical moments by separating the data into bins and then computing the moments from the geometry of the resulting histogram, which effectively becomes a one-pass algorithm for higher moments. One benefit is that the statistical moment calculations can be carried out to arbitrary accuracy such that the computations can be tuned to the precision of, e.g., the data storage format or the original measurement hardware. A relative histogram of a random variable can be constructed in the conventional way: the range of potential values is divided into bins and the number of occurrences within each bin are counted and plotted such that the area of each rectangle equals the portion of the sample values within that bin:

$H(x_{k})={\frac {h(x_{k})}{A}}$ $m_{n}^{(h)}=\sum _{k=1}^{K}x_{k}^{n}\,H(x_{k})\Delta x_{k}={\frac {1}{A}}\sum _{k=1}^{K}x_{k}^{n}\,h(x_{k})\Delta x_{k}$ $\theta _{n}^{(h)}=\sum _{k=1}^{K}{\Big (}x_{k}-m_{1}^{(h)}{\Big )}^{n}\,H(x_{k})\Delta x_{k}={\frac {1}{A}}\sum _{k=1}^{K}{\Big (}x_{k}-m_{1}^{(h)}{\Big )}^{n}\,h(x_{k})\Delta x_{k}$ where the superscript $^{(h)}$ indicates the moments are calculated from the histogram. For constant bin width $\Delta x_{k}=\Delta x$ these two expressions can be simplified using $I=A/\Delta x$ :

$m_{n}^{(h)}={\frac {1}{I}}{\sum _{k=1}^{K}x_{k}^{n}\,h(x_{k})}$ $\theta _{n}^{(h)}={\frac {1}{I}}{\sum _{k=1}^{K}{\Big (}x_{k}-m_{1}^{(h)}{\Big )}^{n}\,h(x_{k})}$ The second approach from Choi and Sweetman  is an analytical methodology to combine statistical moments from individual segments of a time-history such that the resulting overall moments are those of the complete time-history. This methodology could be used for parallel computation of statistical moments with subsequent combination of those moments, or for combination of statistical moments computed at sequential times.

$\gamma _{n,q}=m_{n,q}\gamma _{0,q}\qquad \quad {\textrm {for}}\quad n=1,2,3,4\quad {\text{ and }}\quad q=1,2,\dots ,Q$ The benefit of expressing the statistical moments in terms of $\gamma$ is that the $Q$ sets can be combined by addition, and there is no upper limit on the value of $Q$ .

$\gamma _{n,c}=\sum _{q=1}^{Q}\gamma _{n,q}\quad \quad {\textrm {for}}\quad n=0,1,2,3,4$ where the subscript $_{c}$ represents the concatenated time-history or combined $\gamma$ . These combined values of $\gamma$ can then be inversely transformed into raw moments representing the complete concatenated time-history

$m_{n,c}={\frac {\gamma _{n,c}}{\gamma _{0,c}}}\quad {\textrm {for}}\quad n=1,2,3,4$ Known relationships between the raw moments ($m_{n}$ ) and the central moments ($\theta _{n}=E[(x-\mu )^{n}])$ ) are then used to compute the central moments of the concatenated time-history. Finally, the statistical moments of the concatenated history are computed from the central moments:

$\mu _{c}=m_{1,c}\ \ \ \ \ \sigma _{c}^{2}=\theta _{2,c}\ \ \ \ \ \alpha _{3,c}={\frac {\theta _{3,c}}{\sigma _{c}^{3}}}\ \ \ \ \ \alpha _{4,c}={\frac {\theta _{4,c}}{\sigma _{c}^{4}}}-3$ ## Covariance

Very similar algorithms can be used to compute the covariance. The naive algorithm is:

$\operatorname {Cov} (X,Y)=\displaystyle {\frac {\sum _{i=1}^{n}x_{i}y_{i}-(\sum _{i=1}^{n}x_{i})(\sum _{i=1}^{n}y_{i})/n}{n}}.\!$ For the algorithm above, one could use the following pseudocode:

def naive_covariance(data1, data2):
n = len(data1)
sum12 = 0
sum1 = sum(data1)
sum2 = sum(data2)

for i in range(n):
sum12 += data1[i]*data2[i]

covariance = (sum12 - sum1*sum2 / n) / n
return covariance


A more numerically stable two-pass algorithm first computes the sample means, and then the covariance:

${\bar {x}}=\displaystyle \sum _{i=1}^{n}x_{i}/n$ ${\bar {y}}=\displaystyle \sum _{i=1}^{n}y_{i}/n$ $\operatorname {Cov} (X,Y)=\displaystyle {\frac {\sum _{i=1}^{n}(x_{i}-{\bar {x}})(y_{i}-{\bar {y}})}{n}}.\!$ The two-pass algorithm may be written as:

def two_pass_covariance(data1, data2):
n = len(data1)

mean1 = sum(data1) / n
mean2 = sum(data2) / n

covariance = 0

for i in range(n):
a = data1[i] - mean1
b = data2[i] - mean2
covariance += a*b / n

return covariance


A slightly more accurate compensated version performs the full naive algorithm on the residuals. The final sums $\textstyle \sum x_{i}$ and $\textstyle \sum y_{i}$ should be zero, but the second pass compensates for any small error.

A stable one-pass algorithm exists, similar to the one above, that computes co-moment $\textstyle C_{n}=\sum _{i=1}^{n}(x_{i}-{\bar {x}}_{n})(y_{i}-{\bar {y}}_{n})$ :

${\bar {x}}_{n}={\bar {x}}_{n-1}+{\frac {x_{n}-{\bar {x}}_{n-1}}{n}}\!$ ${\bar {y}}_{n}={\bar {y}}_{n-1}+{\frac {y_{n}-{\bar {y}}_{n-1}}{n}}\!$ $C_{n}=C_{n-1}+(x_{n}-{\bar {x}}_{n})(y_{n}-{\bar {y}}_{n-1})=C_{n-1}+(y_{n}-{\bar {y}}_{n})(x_{n}-{\bar {x}}_{n-1})$ The apparent asymmetry in that last equation is due to the fact that $\textstyle (x_{n}-{\bar {x}}_{n})={\frac {n-1}{n}}(x_{n}-{\bar {x}}_{n-1})$ , so both update terms are equal to $\textstyle {\frac {n-1}{n}}(x_{n}-{\bar {x}}_{n-1})(y_{n}-{\bar {y}}_{n-1})$ . Even greater accuracy can be achieved by first computing the means, then using the stable one-pass algorithm on the residuals.

Thus we can compute the covariance as

{\begin{aligned}\operatorname {Cov} _{N}(X,Y)={\frac {C_{N}}{N}}&={\frac {\operatorname {Cov} _{N-1}(X,Y)\cdot (N-1)+(x_{n}-{\bar {x}}_{n})(y_{n}-{\bar {y}}_{n-1})}{N}}\\&={\frac {\operatorname {Cov} _{N-1}(X,Y)\cdot (N-1)+(y_{n}-{\bar {y}}_{n})(x_{n}-{\bar {x}}_{n-1})}{N}}\\&={\frac {\operatorname {Cov} _{N-1}(X,Y)\cdot (N-1)+{\frac {N-1}{N}}(x_{n}-{\bar {x}}_{n-1})(y_{n}-{\bar {y}}_{n-1})}{N}}.\end{aligned}} Likewise, there is a formula for combining the covariances of two sets that can be used to parallelize the computation:

$C_{X}=C_{A}+C_{B}+({\bar {x}}_{A}-{\bar {x}}_{B})({\bar {y}}_{A}-{\bar {y}}_{B})\cdot {\frac {n_{A}n_{B}}{n_{X}}}$ .