ArticleslgStudy

computer science

Algorithms for calculating variance

Algorithms for calculating variance is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Algorithms for calculating variance rather than just read about it. In short: 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.

Key takeaways

  • Algorithms for calculating variance belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Algorithms for calculating variance to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Algorithms for calculating variance from memory before moving on to harder problems.

Reference excerpt

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:

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

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.

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.

Var⁡(X−K)=Var⁡(X). with K any constant, which leads to the new formula

σ2=∑i=1n(xi−K)2−(∑i=1n(xi−K))2/nn−1. The closer K 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 (xi−K) 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

Two-pass algorithm An alternative approach, using a different formula for the variance, first computes the sample mean,

x¯=∑j=1nxjn, and then computes the sum of the squares of the differences from the mean,

sample variance=s2=∑i=1n(xi−x¯)2n−1, where s is the standard deviation. This is given by the following code:

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.

Incremental algorithms It is often useful to be able to compute the variance in a single pass, inspecting each value xi 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:

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, x‾n=1n∑i=1nxi denotes the sample mean of the first n samples (x1,…,xn), σn2=1n∑i=1n(xi−x‾n)2 their biased sample variance, and sn2=1n−1∑i=1n(xi−x‾n)2 their unbiased sample variance.

x¯n=(n−1)x¯n−1+xnn=x¯n−1+xn−x¯n−1n σn2=(n−1)σn−12+(xn−x¯n−1)(xn−x¯n)n=σn−12+(xn−x¯n−1)(xn−x¯n)−σn−12n. sn2=n−2n−1sn−12+(xn−x¯n−1)2n=sn−12+(xn−x¯n−1)2n−sn−12n−1,n>1 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, ∑i=1n(xi−x¯n)2, here denoted M2,n:

M2,n=M2,n−1+(xn−x¯n−1)(xn−x¯n)σn2=M2,nnsn2=M2,nn−1 The following algorithm was found by Welford, and it has been thoroughly analyzed. It is also common to denote Mk=x¯k and Sk=M2,k. An example Python implementation for Welford's algorithm is given below, using the same framework as the above "shifted data" algorithm:

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:

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 A and B:

nAB=nA+nBδ=x¯B−x¯Ax¯AB=x¯A+δ⋅nBnABM2,AB=M2,A+M2,B+δ2⋅nAnBnAB. 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 nA≈nB and both are large, because the numerical error in δ=x¯B−x¯A is not scaled down in the way that it is in the nB=1 case. In such cases, prefer x¯AB=nAx¯A+nBx¯BnAB. Reusing the WelfordVariance class from above, we have:

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.

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Algorithms for calculating variance

Start with the simplest possible case. Write down what Algorithms for calculating variance claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Algorithms for calculating variance before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Algorithms for calculating variance ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Algorithms for calculating variance

In research
Algorithms for calculating variance appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Algorithms for calculating variance in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Algorithms for calculating variance is common in secondary-school and first-year university syllabi. It links to neighbouring topics Statistical algorithms, Statistical deviation and dispersion, so understanding it makes those chapters shorter.
In everyday life
Look for Algorithms for calculating variance outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Algorithms for calculating variance” →

How to study Algorithms for calculating variance in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Algorithms for calculating variance means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Algorithms for calculating variance out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Algorithms for calculating variance in simple terms?

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…

Why does Algorithms for calculating variance matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Algorithms for calculating variance?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Algorithms for calculating variance.

Tags

  • Statistical algorithms
  • Statistical deviation and dispersion

Keep exploring