Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 2

Two-Pass Variance Calculation

Recommended resources

Hello! Welcome back.

In our previous lesson, we derived the single-pass "textbook" formula for variance. We saw that it was algebraically equivalent to the definition of variance and had the significant advantage of requiring only one pass over the data, making it seem ideal for large datasets or streaming computations.

Today, we'll shift our focus to the algorithm that directly implements the statistical definition of variance. The learning outcome for this lesson is to describe the two-pass algorithm for computing variance, which serves as a stable baseline. We'll explore why this seemingly less efficient method is considered the gold standard for accuracy, setting the stage for understanding the numerical pitfalls that we'll investigate next.

1. Revisiting the Definition: The Two-Pass Approach

Let's start by recalling the definitional formula for population variance () for a dataset :

A direct, literal implementation of this formula requires two distinct steps, or "passes," over the data:

  1. First Pass: Iterate through all the data points to compute their sum, , and then calculate the mean, .
  2. Second Pass: Iterate through all the data points a second time. In this pass, for each point , you calculate the squared difference and add it to a running total. Finally, you divide this sum by .

This method is straightforward and easy to understand as it directly follows the mathematical definition.

To see this formalized, let's turn to a clear description from Wikipedia.

Algorithms for calculating variance

The Wikipedia article on 'Algorithms for calculating variance' provides a concise description of the two-pass method. It lays out the steps and includes a simple Python implementation that makes the process very clear.

Please read the section titled 'Two-pass algorithm'. Focus on the formula and the accompanying Python code snippet. Notice how the code directly mirrors the two steps we just discussed.

As you can see, the logic is simple: compute the mean, then compute the sum of squared differences from that mean. The main drawback appears to be efficiency—you have to read your data twice. This can be costly if the data is very large and not stored in memory.


2. The Two-Pass Algorithm as a Stable Baseline

If the two-pass algorithm is less efficient, why do we care about it? Because it is numerically stable. It serves as a reliable benchmark for accuracy against which other algorithms are measured.

The stability comes from the fact that in the second pass, you are calculating differences from the true mean of the sample (). The magnitudes of these intermediate values are generally much smaller than the magnitudes of the original data points . This prevents a specific type of floating-point error that we will discuss in the next lesson.

A research paper from the SIGMOD Record provides an excellent overview of the practical performance and precision of various variance algorithms.

A Closer Look at Variance Implementations In Modern ...

To understand why the two-pass algorithm is considered a reliable standard, let's look at a research paper that analyzes various variance implementations. This paper compares several methods and highlights the properties of the two-pass approach.

Please review the following parts of the paper: Skim the 'Abstract' and 'Introduction' (first page) to see how the authors frame the problem and position the two-pass method as a precise baseline. Read Section 4.1 'Impact of Shift' and Section 4.2 'Impact of Data Size', and examine Figures 2a and 2b. Notice which line, labeled 'Two Pass', consistently shows the highest precision (i.e., the most correct decimal places).

The key takeaway from the paper is that across their experiments, the two-pass algorithm consistently delivered the most accurate results. The empirical evidence in Figures 2a and 2b is compelling: as the data becomes more challenging (by adding a large constant "shift" or by increasing the dataset size), the precision of other algorithms degrades, while the two-pass method remains highly accurate. This is why it's considered a stable baseline.


3. A Concrete Example of Stability

Let's make this abstract idea of stability more concrete. What does it look like when an algorithm is unstable? The Wikipedia article you read earlier provides a perfect example.

Algorithms for calculating variance

Let's see this stability in action. The same Wikipedia article provides a striking example that demonstrates how the naive (single-pass) algorithm can fail catastrophically while the two-pass algorithm remains accurate.

Please read the 'Example' section. Pay close attention to the two cases: when a large number like 10⁸ and then 10⁹ is added to each data point. Observe how the naive algorithm's result degrades, while the two-pass algorithm's result stays correct.

As the example shows, variance is invariant to shifting; adding a constant to every data point does not change the spread of the data, so the variance should remain the same. The two-pass algorithm correctly computes the variance as 30 in all cases.

However, the single-pass "textbook" algorithm we derived last lesson starts to lose precision and eventually fails spectacularly, producing a negative variance. This is mathematically impossible and highlights a critical flaw in how the single-pass formula behaves when implemented on a computer with finite-precision arithmetic. This type of error is known as catastrophic cancellation, a topic we will dissect in our next lesson.

Test your understanding!

Let's use the problematic dataset from the Wikipedia example: (10⁹ + 4, 10⁹ + 7, 10⁹ + 13, 10⁹ + 16). Manually trace the calculations of the two-pass algorithm.

  1. Pass 1: Calculate the exact mean ().
  2. Pass 2: Calculate the four values of . What do you notice about them?
  3. Use those values to compute the final sample variance. (Use in the denominator for sample variance, to match the article's example).
Show answer

The dataset is .

1. Pass 1: Calculate the mean ()

2. Pass 2: Calculate deviations

Notice that the large term completely disappears. The numbers we are working with are small and manageable, which is the key to the algorithm's stability.

3. Calculate sample variance


The result is correct and computed without manipulating large, problematic numbers in the critical step.


Conclusion

In this lesson, we have formally described the two-pass algorithm for variance and established why it's considered a stable baseline.

Key Takeaways:

  • The two-pass algorithm is a direct implementation of the definitional formula for variance, requiring one pass to compute the mean and a second pass to compute the sum of squared differences from that mean.
  • Its primary advantage is numerical stability. By computing differences from the sample's true mean, it avoids working with large intermediate values that can lead to significant floating-point errors.
  • Empirical evidence and concrete examples show that it produces accurate results even for datasets that cause the single-pass "textbook" formula to fail.
  • Its main disadvantage is the need to access the data twice, which can be inefficient for out-of-memory datasets or data streams.

We now have two competing algorithms: a fast but potentially unstable single-pass method, and a stable but potentially slow two-pass method. This sets up the perfect motivation for Welford's algorithm, which aims to give us the best of both worlds: single-pass efficiency and numerical stability.

Preview of the Next Lesson:

To fully appreciate why Welford's algorithm is needed, we must first understand the enemy. In the next lesson, we will dive into the concept of catastrophic cancellation, the specific floating-point arithmetic issue that causes the textbook single-pass formula to fail so dramatically.