Lably
Skip to content

Algorithms for calculating variance

Important algorithms in numerical statistics

  • 25 min read
  • 7 chapters

Related on Lably

Through Algorithm, Variance and Sampling (statistics)

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:

  • Let n ← 0, Sum ← 0, SumSq ← 0
  • For each datum x:
    • n ← n + 1
    • Sum ← Sum + x
    • SumSq ← SumSq + x × x
  • Var = (SumSq − (Sum × Sum) / n) / (n − 1)

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.

Sign in to keep reading

6 more chapters are free with a Lably account.

More in Topics in mathematics