Algorithms for calculating variance
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.
- 1 Naïve algorithm
- 2 Two-pass algorithm
- 3 Welford's Online algorithm
- 4 Weighted incremental algorithm
- 5 Parallel algorithm
- 6 Example
- 7 Higher-order statistics
- 8 Covariance
- 9 See also
- 10 References
- 11 External links
A formula for calculating the variance of an entire population of size N is:
Therefore, a naive 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. However, the algorithm can be improved by adopting the method of the assumed mean.
Computing shifted data
with any constant, which leads to the new formula
the closer is to the mean value the more accurate the result will be, 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.
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) < 2: return 0.0 K = data n = Ex = Ex2 = 0.0 for x in data: n = n + 1 Ex += x - K Ex2 += (x - K) * (x - K) variance = (Ex2 - (Ex * Ex)/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 = n = Ex = Ex2 = 0.0 def add_variable(x): if (n == 0): K = x n = n + 1 Ex += x - K Ex2 += (x - K) * (x - K) def remove_variable(x): n = n - 1 Ex -= (x - K) Ex2 -= (x - K) * (x - K) def get_meanvalue(): return K + Ex / n def get_variance(): return (Ex2 - (Ex*Ex)/n) / (n-1)
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 = sum1 = sum2 = 0 for x in data: n += 1 sum1 += x mean = sum1 / n for x in data: sum2 += (x - mean)*(x - mean) variance = sum2 / (n - 1) return variance
This algorithm is numerically stable if n is small. However, the results of both of these simple algorithms ("Naïve" and "Two-pass") 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.
Welford's Online 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 xn. Here, xn denotes the sample mean of the first n samples (x1, ..., xn), s2n their sample variance, and σ2n their population variance.
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, , here denoted :
An example Python implementation for Welford's algorithm is given below.
# for a new value newValue, compute the new count, new mean, the new M2. # mean accumulates the mean of the entire dataset # M2 aggregates the squared distance from the mean # count aggregates the number of samples seen so far def update(existingAggregate, newValue): (count, mean, M2) = existingAggregate count += 1 delta = newValue - mean mean += delta / count delta2 = newValue - mean M2 += delta * delta2 return (count, mean, M2) # retrieve the mean, variance and sample variance from an aggregate def finalize(existingAggregate): (count, mean, M2) = existingAggregate (mean, variance, sampleVariance) = (mean, M2/count, M2/(count - 1)) if count < 2: return float('nan') else: return (mean, variance, sampleVariance)
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
def weighted_incremental_variance(dataWeightPairs): wSum = wSum2 = mean = S = 0 for x, w in dataWeightPairs: # Alternatively "for x, w in zip(data, weights):" wSum = wSum + w wSum2 = wSum2 + w*w meanOld = mean mean = meanOld + (w / wSum) * (x - meanOld) S = S + w * (x - meanOld) * (x - mean) population_variance = S / wSum # Bessel's correction for weighted samples # Frequency weights sample_frequency_variance = S / (wSum - 1) # Reliability weights sample_reliability_variance = S / (wSum - wSum2/wSum)
Chan et al. note that the above "On-line" algorithm 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 .
def parallel_variance(avg_a, count_a, var_a, avg_b, count_b, var_b): delta = avg_b - avg_a m_a = var_a * (count_a - 1) m_b = var_b * (count_b - 1) M2 = m_a + m_b + delta ** 2 * count_a * count_b / (count_a + count_b) return M2 / (count_a + count_b - 1)
Assume that all floating point operations use 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 the naïve algorithm and two-pass algorithm 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. The two-pass algorithm computes this variance estimate correctly, but the naïve algorithm returns 29.333333333333332 instead of 30.
While this loss of precision may be tolerable and viewed as a minor flaw of the naïve algorithm, further increasing the offset makes the error catastrophic. Consider the sample (109 + 4, 109 + 7, 109 + 13, 109 + 16). Again the estimated population variance of 30 is computed correctly by the two-pass algorithm, but the naïve algorithm now computes it as −170.66666666666666. This is a serious problem with naïve algorithm and is due to catastrophic cancellation in the subtraction of two similar numbers at the final stage of the algorithm.
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 = mean = M2 = M3 = 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ébaÿ further extends these results to arbitrary-order central moments, for the incremental and the pairwise cases, and subsequently Pébaÿ et al. for weighted and compound moments. 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:
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  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:
Very similar algorithms can be used to compute the covariance.
The naïve algorithm is:
For the algorithm above, one could use the following Python code:
def naive_covariance(data1, data2): n = len(data1) sum12 = 0 sum1 = sum(data1) sum2 = sum(data2) for i1, i2 in zip(data1, data2): sum12 += i1*i2 covariance = (sum12 - sum1*sum2 / n) / n return covariance
With estimate of the mean
As for the variance, the covariance of two random variables is also shift-invariant, so given any two constant values and 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 ky = dataY Ex = Ey = Exy = 0 for ix, iy in zip(dataX, dataY): Ex += ix - kx Ey += iy - ky Exy += (ix - kx) * (iy - 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 i1, i2 in zip(data1, data2): a = i1 - mean1 b = i2 - 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 online algorithm for computing the variance, 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
def online_covariance(data1, data2): meanx = meany = C = n = 0 for x, y in zip(data1, data2): n += 1 dx = x - meanx meanx += dx / n meany += (y - meany) / n C += dx * (y - meany) population_covar = C / n # Bessel's correction for sample variance sample_covar = C / (n - 1)
We can also make a small modification to compute the weighted covariance:
def online_weighted_covariance(data1, data2, data3): meanx = meany = 0 wsum = wsum2 = 0 C = 0 for x, y, w in zip(data1, data2, data3): wsum += w wsum2 += w*w dx = x - meanx meanx += (w / wsum) * dx meany += (w / wsum) * (y - meany) C += w * dx * (y - meany) population_covar = C / wsum # Bessel's correction for sample variance # Frequency weights sample_frequency_covar = C / (wsum - 1) # Reliability weights sample_reliability_covar = C / (wsum - wsum2 / wsum)
Likewise, there is a formula for combining the covariances of two sets that can be used to parallelize the computation:
Weighted batched version
A version of the weighted online algorithm that does batched updated also exists : let denote the weights, we can write
The covariance can then be computed as
- Bo Einarsson (1 August 2005). Accuracy and Reliability in Scientific Computing. SIAM. p. 47. ISBN 978-0-89871-584-2. Retrieved 17 February 2013.
- T.F.Chan, G.H. Golub and R.J. LeVeque (1983). ""Algorithms for computing the sample variance: Analysis and recommendations", The American Statistician, 37" (PDF): 242–247.
- Schubert, Erich; Gertz, Michael (2018-07-09). "Numerically stable parallel computation of (co-)variance". ACM: 10. doi:10.1145/3221269.3223036. ISBN 9781450365055.
- Higham, Nicholas (2002). Accuracy and Stability of Numerical Algorithms (2 ed) (Problem 1.10). SIAM.
- B. P. Welford (1962)."Note on a method for calculating corrected sums of squares and products". Technometrics 4(3):419–420.
- Donald E. Knuth (1998). The Art of Computer Programming, volume 2: Seminumerical Algorithms, 3rd edn., p. 232. Boston: Addison-Wesley.
- 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. https://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. doi:10.2307/2286154
- D. H. D. West (1979). Communications of the ACM, 22, 9, 532-535: Updating Mean and Variance Estimates: An Improved Method
- Chan, Tony F.; Golub, Gene H.; LeVeque, Randall J. (1979), "Updating Formulae and a Pairwise Algorithm for Computing Sample Variances." (PDF), Technical Report STAN-CS-79-773, Department of Computer Science, Stanford University.
- Terriberry, Timothy B. (2007), Computing Higher-Order Moments Online
- Pébaÿ, Philippe (2008), "Formulas for Robust, One-Pass Parallel Computation of Covariances and Arbitrary-Order Statistical Moments" (PDF), Technical Report SAND2008-6212, Sandia National Laboratories
- Pébaÿ, Philippe; Terriberry, Timothy; Kolla, Hemanth; Bennett, Janine (2016), "Numerically Stable, Scalable Formulas for Parallel and Online Computation of Higher-Order Multivariate Central Moments with Arbitrary Weights", Computational Statistics, Springer
- Choi, Myoungkeun; Sweetman, Bert (2010), "Efficient Calculation of Statistical Moments for Structural Health Monitoring", Journal of Structural Health Monitoring, 9 (1)