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:
Using Bessel's correction to calculate an unbiased estimate of the population variance from a finite sample of n observations, the formula is:
Therefore, a naïve algorithm to calculate the estimated variance is given by the following:
Let For each datum :
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 and 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.
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 any value inside the sample range will provide 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.
The algorithm can be written in Python programming language as def shifted_data_variance(data, K): if len(data) < 2: return 0.0 n = Ex = Ex2 = 0.0 for x in data: n += 1 Ex += x - K Ex2 += (x - K) ** 2 variance = (Ex2 - Ex**2 / 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
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 code:
def two_pass_variance(data): n = len(data) mean = sum(data) / n variance = sum((x - mean) ** 2 for x in data) / (n - 1) return variance
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. Metadata also listed at ACM Digital Library.
Incremental algorithms 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 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:
class ShiftDataVariance: def __init__(self): self.K = 0.0 self.n = 0 self.Ex = 0.0 self.Ex2 = 0.0
def add_variable(self, x: float): if self.n == 0: self.K = x self.n += 1 self.Ex += x - self.K self.Ex2 += (x - self.K) ** 2
def remove_variable(self, x: float): self.n -= 1 self.Ex -= x - self.K self.Ex2 -= (x - self.K) ** 2
def add_variables(self, xs: list[float]): # Python uses Neumaier's algorithm for the builtin sum() function, # which is more accurate than a simple loop. if self.n == 0 and xs: self.K = xs self.n += len(xs) self.Ex += sum(x - self.K for x in xs) self.Ex2 += sum((x - self.K) ** 2 for x in xs)
def get_mean(self) -> float: return self.K + self.Ex / self.n
def get_variance(self) -> float: return (self.Ex2 - self.Ex**2 / self.n) / (self.n - 1)
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, denotes the sample mean of the first n samples , their biased sample variance, and their unbiased sample 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 :
The following algorithm was found by Welford,Donald E. Knuth (1998). The Art of Computer Programming, volume 2: Seminumerical Algorithms, 3rd edn., p. 232. Boston: Addison-Wesley. and it has been thoroughly analyzed. It is also common to denote and . An example Python implementation for Welford's algorithm is given below, using the same framework as the above "shifted data" algorithm:
class WelfordVariance: def __init__(self): # Comparison to ShiftDataVariance: self.mean = 0.0 # = K + Ex / n self.count = 0 # = n self.M2 = 0.0 # = Ex2 - (Ex)^2 / n
def add_variable(self, x: float): self.count += 1 old_mean = self.mean self.mean += (x - self.mean) / self.count self.M2 += (x - old_mean) * (x - self.mean)
def remove_variable(self, x: float): self.count -= 1 new_mean = self.mean self.mean -= (x - self.mean) / self.count self.M2 -= (x - new_mean) * (x - self.mean)
def get_mean(self) -> float: return self.mean
def get_variance(self) -> float: return self.M2 / self.count
def get_sample_variance(self) -> float: return self.M2 / (self.count - 1)
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:
from collections import namedtuple WeightedVariances = namedtuple("WeightedVariances", "pop freq reli") def weighted_incremental_variance(data_weight_pairs): w_sum = w_sum2 = mean = S = 0
for x, w in data_weight_pairs: w_sum = w_sum + w w_sum2 = w_sum2 + w**2 mean_old = mean mean = mean_old + (w / w_sum) * (x - mean_old) S = S + w * (x - mean_old) * (x - mean)
population_variance = S / w_sum # Bessel's correction for weighted samples # Frequency weights sample_frequency_variance = S / (w_sum - 1)
# Reliability weights sample_reliability_variance = S / (w_sum - w_sum2 / w_sum) return WeightedVariances(population_variance, sample_frequency_variance, sample_reliability_variance)
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 and : . 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 . Reusing the WelfordVariance class from above, we have:
def merge(a: WelfordVariance, b: WelfordVariance) -> WelfordVariance: ab = WelfordVariance() ab.count = a.count + b.count delta = b.mean - a.mean ab.mean = (a.count * a.mean + b.count * b.mean) / ab.count ab.M2 = a.M2 + b.M2 + delta**2 * a.count * b.count / ab.count return ab
# example: ab = merge(a, b) print(ab.get_sample_variance())
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.
Example 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 (, , , ), 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 (, , , ). 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.
Higher-order statistics Terriberry 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 = 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**2 term1 = delta * delta_n * n1 mean = mean + delta_n M4 = M4 + term1 * delta_n2 * (n**2 - 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
# Note, you may also calculate variance using M2, and skewness using M3 # Caution: If all the inputs are the same, M2 will be 0, resulting in a division by 0. kurtosis = (n * M4) / (M2**2) - 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