# 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:

A formula for calculating an unbiased estimate of the population variance from a finite sample of *n* observations is:

Therefore a naive algorithm to calculate the estimated variance is given by the following written in Python programming language:

```
def naive_variance(data):
n = 0
Sum = 0
Sum_sqr = 0
for x in data:
n += 1
Sum += x
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.^{[1]}^{[2]} 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.

### Computing shifted data

We can use a property of the variance to avoid the catastrophic cancellation in this formula, namely the variance is invariant with respect to changes in a location parameter

with any constant, which leads to the new formula

the closer is to the mean value the more accurate will be the result, but just choosing a value inside the
samples range will guarantee the desired stability. If the values 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.^{[2]}

If we take just the first sample as the algorithm can be written in Python programming language as

```
def shifted_data_variance(data):
if len(data) == 0:
return 0
K = data[0]
n = 0
Sum = 0
Sum_sqr = 0
for x in data:
n = n + 1
Sum = Sum + (x - K)
Sum_sqr = Sum_sqr + (x - K) * (x - K)
variance = (Sum_sqr - (Sum * Sum)/n)/(n - 1)
# use n instead of (n-1) if want to compute the exact variance of the given data
# use (n-1) if data are samples of a larger population
return variance
```

this formula facilitates as well the incremental computation, that can be expressed as

```
K = 0
n = 0
Ex = 0
Ex2 = 0
def add_variable(x):
if (n == 0):
K = x
n = n + 1
Ex = Ex + (x - K)
Ex2 = Ex2 + (x - K) * (x - K)
def remove_variable(x):
n = n - 1
Ex = Ex - (x - K)
Ex2 = Ex2 - (x - K) * (x - K)
def get_meanvalue():
return K + Ex / n
def get_variance():
return (Ex2 - (Ex*Ex)/n) / (n-1)
```

## Two-pass algorithm

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

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

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.^{[1]}^{[3]} 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:^{[4]}

```
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

### Incremental algorithm

It is often useful to be able to compute the variance in a single pass, inspecting each value 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 . Here, *Template:Overline _{n}* denotes the sample mean of the first

*n*samples (

*x*

_{1}, ...,

*x*),

_{n}*s*

^{2}

_{n}their sample variance, and

*σ*

^{2}

_{N}their population variance.

It turns out that a more suitable quantity for updating is the sum of squares of differences from the (current) mean, , here denoted :

A numerically stable algorithm is given below. It also computes the mean.
This algorithm is due to Knuth,^{[5]} who cites Welford,^{[6]} and it has been thoroughly analyzed.^{[7]}^{[8]} It is also common to denote and .^{[9]}

```
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)
if (n < 2):
return 0
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.

### Decremental algorithm

Template:Section OR {{ safesubst:#invoke:Unsubst||$N=Unreferenced section |date=__DATE__ |$B= {{ safesubst:#invoke:Unsubst||$N=Unreferenced |date=__DATE__ |$B= {{#invoke:Message box|ambox}} }} }} According to incremental algorithm, removing a specific number out of the dataset is performed by executing reverse form of incremental algorithm to calculate mean and variance of new dataset. This function is used in calculating statistical information in a convolution operation. Here's The calculation:

a compound algorithm for add or remove member to a data is given below

```
n = 0
mean = 0
M2 = 0
def add_variable(x):
n = n + 1
delta = x - mean
mean = mean + delta/n
M2 = M2 + delta*(x - mean)
def remove_variable(x):
n = n - 1
delta = x - mean
mean = mean - delta/n
M2 = M2 - delta*(x - mean)
def update_variable(oldX,newX):
delta = newX - oldX
dold = oldX - mean
mean = mean + delta/n
dnew = newX - mean
M2 = M2 + delta*(dold + dnew)
def get_variance():
return M2/(n-1)
```

## 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)^{[10]} 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.^{[4]} note that the above online algorithm III is a special case of an algorithm that works for any partition of the sample into sets , :

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 and both are large, because the numerical error in is not scaled down in the way that it is in the case. In such cases, prefer .

## 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 (10^{8} + 4, 10^{8} + 7, 10^{8} + 13, 10^{8} + 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 (10^{9} + 4, 10^{9} + 7, 10^{9} + 13, 10^{9} + 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^{[11]} extends Chan's formulae to calculating the third and fourth central moments, needed for example when estimating skewness and kurtosis:

Here the are again the sums of powers of differences from the mean , giving

For the incremental case (i.e., ), this simplifies to:

By preserving the value , 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^{[12]}
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
^{[13]}
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:

where and represent the frequency and the relative frequency at bin and is the total area of the histogram. After this normalization, the raw moments and central moments of can be calculated from the relative histogram:

where the superscript indicates the moments are calculated from the histogram. For constant bin width these two expressions can be simplified using :

The second approach from Choi and Sweetman
^{[13]}
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.

If sets of statistical moments are known: for , then each can be expressed in terms of the equivalent raw moments:

where is generally taken to be the duration of the time-history, or the number of points if is constant.

The benefit of expressing the statistical moments in terms of is that the sets can be combined by addition, and there is no upper limit on the value of .

where the subscript represents the concatenated time-history or combined . These combined values of can then be inversely transformed into raw moments representing the complete concatenated time-history

Known relationships between the raw moments () and the central moments () 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:

## Covariance

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

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
```

As for the variance, the covariance of two random variables is also shift-invariant, so given that and are whatever two constant values it can be written:

and again choosing a value inside the range of values will stabilize the formula against catastrophic cancellation as well as make it more robust against big sums. Taking the first value of each data set, the algorithm can be written as:

```
def shifted_data_covariance(dataX, dataY):
n = len(dataX)
if (n < 2):
return 0
Kx = dataX[0]
Ky = dataY[0]
Ex = 0
Ey = 0
Exy = 0
for i in range(n):
Ex += dataX[i] - Kx
Ey += dataY[i] - Ky
Exy += (dataX[i] - Kx) * (dataY[i] - Ky)
return (Exy - Ex * Ey / n) / n
```

The two-pass algorithm first computes the sample means, and then the covariance:

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 and *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 :

The apparent asymmetry in that last equation is due to the fact that , so both update terms are equal to . 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

Likewise, there is a formula for combining the covariances of two sets that can be used to parallelize the computation:

## See also

## References

- ↑
^{1.0}^{1.1}{{#invoke:citation/CS1|citation |CitationClass=book }} - ↑
^{2.0}^{2.1}{{#invoke:Citation/CS1|citation |CitationClass=journal }} - ↑ {{#invoke:citation/CS1|citation |CitationClass=book }}
- ↑
^{4.0}^{4.1}{{#invoke:citation/CS1|citation |CitationClass=citation }}. - ↑ Donald E. Knuth (1998).
*The Art of Computer Programming*, volume 2:*Seminumerical Algorithms*, 3rd edn., p. 232. Boston: Addison-Wesley. - ↑ B. P. Welford (1962)."Note on a method for calculating corrected sums of squares and products".
*Technometrics*4(3):419–420. - ↑ Chan, Tony F.; Golub, Gene H.; LeVeque, Randall J. (1983). Algorithms for Computing the Sample Variance: Analysis and Recommendations. The American Statistician 37, 242-247. http://www.jstor.org/stable/2683386
- ↑ Ling, Robert F. (1974). Comparison of Several Algorithms for Computing Sample Means and Variances. Journal of the American Statistical Association, Vol. 69, No. 348, 859-866. Template:Hide in printTemplate:Only in print
- ↑ http://www.johndcook.com/standard_deviation.html
- ↑ D. H. D. West (1979).
*Communications of the ACM*, 22, 9, 532-535:*Updating Mean and Variance Estimates: An Improved Method* - ↑ {{#invoke:citation/CS1|citation |CitationClass=citation }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=citation }}
- ↑
^{13.0}^{13.1}{{#invoke:citation/CS1|citation |CitationClass=citation }}