STREAMING STATISTICS · RUNNING SUMMARIES
Online variance: update a mean and spread one value at a time
Implement Welford’s running mean and variance in Squeak Smalltalk, trace every update, distinguish population from sample variance, and test exact and floating-point inputs.
Before you start
Open a Workspace in native Squeak 6.1. Each of the eight blocks below is a complete, independent expression. Select one whole block and choose Print it. Do not paste all checkpoints into a single evaluation or file the checkpoint collection in as a package. You need no add-on packages, network connection or saved classes. Review blocks and closures and exact Fractions if those ideas are unfamiliar.
Suppose measurements arrive one at a time and you want their mean and spread without storing the whole history. Keeping only the sum is enough for a mean, but not a variance. We will retain a count, a mean and the sum of squared distances from that mean, called M2. Our update consumes one finite real numeric value and produces a new three-element Array. The teaching implementation assumes a valid state and numeric input: it is not a parser, missing-data cleaner or concurrent accumulator.
Download the eight Workspace checkpoints, the direct assertion expression, or the complete native source kit. Start with the fixed inputs below before adapting it to measurements.
01 · Measure spread around a known mean
Start with the population {2, 4, 6, 8}. The mean is 5. Squared distances are 9, 1, 1 and 9: their sum M2 is 20. Divide by four for population variance, not for the sample estimate.
| values mean m2 |
values := #(2 4 6 8).
mean := values sum / values size.
m2 := (values collect: [:x | (x - mean) squared]) sum.
{mean. m2. m2 / values size}Check: Expect #(5 20 5). Variance has squared units: milliseconds become square milliseconds.

02 · Add the first value
Represent a running summary as {count. mean. M2}. Zero is an initialization placeholder, not the mean of an empty collection. The first update produces mean 2 and zero spread.
| update |
update := [:prior :x |
| n oldMean delta nextMean nextM2 |
n := prior first + 1. oldMean := prior second.
delta := x - oldMean.
nextMean := oldMean + (delta / n).
nextM2 := prior third + (delta * (x - nextMean)).
{n. nextMean. nextM2}].
update value: #(0 0 0) value: 2Check: Expect #(1 2 0). The block returns a new Array and leaves its input state untouched.

03 · Inspect the second update
Before 4 arrives, the mean is 2. Delta is 2; the new mean is 3. Multiply the distance to the old mean by the distance to the new mean: 2 times 1 adds 2 to M2.
| update first second |
update := [:prior :x |
| n oldMean delta nextMean nextM2 |
n := prior first + 1. oldMean := prior second.
delta := x - oldMean.
nextMean := oldMean + (delta / n).
nextM2 := prior third + (delta * (x - nextMean)).
{n. nextMean. nextM2}].
first := update value: #(0 0 0) value: 2.
second := update value: first value: 4.
{first. second}Check: Expect two states: #(1 2 0) and #(2 3 2). Reversing the update order would use the wrong mean.

04 · Consume a stream in one pass
Carry only the current state. Each do: iteration replaces it with the returned state. We use a literal Array as a convenient finite stand-in for observations arriving one at a time.
| update state |
update := [:prior :x |
| n oldMean delta nextMean nextM2 |
n := prior first + 1. oldMean := prior second.
delta := x - oldMean.
nextMean := oldMean + (delta / n).
nextM2 := prior third + (delta * (x - nextMean)).
{n. nextMean. nextM2}].
state := #(0 0 0).
#(2 4 6 8) do: [:x | state := update value: state value: x].
stateCheck: Expect #(4 5 20), agreeing exactly with the two-pass calculation.

Watch the summary grow

Download the native visual expression, open it as text, select the entire expression and Do it. Change stage := 0. to 1, 2 or 3 to reveal later observations. Close the previous window before opening another. The fixed 1000 × 480 layout has no timer or persistence. Hidden rows say “not received yet”; the running state is calculated by the same update block used in the lesson, not typed into the graphics.
05 · Choose the denominator deliberately
A population description divides M2 by n. The usual sample variance divides by n minus one. Under independent identically distributed sampling with finite variance, the latter is an unbiased estimator of population variance. It is not a correction to every possible data collection process.
| summarize |
summarize := [:prior |
| n |
n := prior first.
{n. (n = 0 ifTrue: [nil] ifFalse: [prior second]).
(n = 0 ifTrue: [nil] ifFalse: [prior third / n]).
(n < 2 ifTrue: [nil] ifFalse: [prior third / (n - 1)])}].
summarize value: #(4 5 20)Check: The four fields are count, mean, population variance, sample variance. Expect the last result as an exact Fraction 20/3.

06 · Give missing answers an honest value
An empty dataset has no mean or variance. A singleton has population variance zero but no sample variance. Returning nil makes these missing results explicit; it is not the number zero.
| summarize |
summarize := [:prior |
| n |
n := prior first.
{n. (n = 0 ifTrue: [nil] ifFalse: [prior second]).
(n = 0 ifTrue: [nil] ifFalse: [prior third / n]).
(n < 2 ifTrue: [nil] ifFalse: [prior third / (n - 1)])}].
{summarize value: #(0 0 0). summarize value: #(1 7 0)}Check: Expect nil for all empty statistics and for singleton sample variance. Branch before dividing.

07 · Keep exact fractions exact
Squeak integer division can produce Fractions. That lets us test the recurrence without floating-point rounding. It does not make arbitrary real measurements exact: decimal measurements may already be rounded.
| update state |
update := [:prior :x |
| n oldMean delta nextMean nextM2 |
n := prior first + 1. oldMean := prior second.
delta := x - oldMean.
nextMean := oldMean + (delta / n).
nextM2 := prior third + (delta * (x - nextMean)).
{n. nextMean. nextM2}].
state := #(0 0 0).
{1 / 2. 3 / 2. 5 / 2} do: [:x |
state := update value: state value: x].
stateCheck: Expect count 3, mean 3/2 and M2 2; population variance would be 2/3.

08 · Check floating-point results with a tolerance
Use a tolerance for approximate arithmetic rather than demanding identical low bits. A translated dataset should have the same spread mathematically. Here the finite test checks one moderate translation; it is not a universal error bound.
| update state |
update := [:prior :x |
| n oldMean delta nextMean nextM2 |
n := prior first + 1. oldMean := prior second.
delta := x - oldMean.
nextMean := oldMean + (delta / n).
nextM2 := prior third + (delta * (x - nextMean)).
{n. nextMean. nextM2}].
state := #(0 0 0).
#(1000000.0 1000002.0 1000004.0) do: [:x |
state := update value: state value: x].
{((state second - 1000002.0) abs < 0.000001).
((state third - 8.0) abs < 0.000001)}Check: Expect #(true true). Floating-point order, input scale and available precision still matter.

Why the update works
Let n be the new count, m the old mean and x the new observation. The distance delta = x − m is the amount by which the new observation differs from the old center. The new mean is m′ = m + delta/n. This is the ordinary sum divided by count, rearranged so that the previous sum need not be stored.
Now the old observations are all measured relative to a slightly different center. Their squared-distance total changes, too; simply adding (x − m′) squared would miss that shift. The identity M2′ = M2 + delta × (x − m′) accounts for both the new observation and the movement of the center. One way to derive it is to expand every squared distance about m′ and use the fact that the old deviations from m sum to zero. It also gives M2′ = M2 + delta squared × (n − 1)/n.
Our invariant after each successful update is: count equals the number of observations, mean is their arithmetic mean, and M2 is their sum of squared deviations. Starting with count zero makes the first new mean x, so the new contribution to M2 is zero. Those statements are exact identities with exact arithmetic. Floating-point operations only approximate them, which is why a numerical test uses tolerances.
What this does—and does not—fix
A tempting formula is “mean of squares minus square of mean.” When observations have a large common offset but little spread, that subtracts nearly equal large floating-point values. The low-order information you want can be lost. Welford’s recurrence instead works with deviations from a running center, avoiding that particular large-sum subtraction. It is not a guarantee of exact floating-point variance.
Finite precision, very large counts, extreme magnitudes, order of arrival and values already rounded during measurement can still affect the answer. Infinity, NaN, complex values, missing values and user-entered text are outside this lab’s input contract. Decide whether to reject, skip or separately count missing measurements before adding a production input boundary; never silently treat them as zero. Do not clamp a surprising negative result to zero without understanding the numerical error and the application’s tolerance.
The Fraction checkpoint separates algebraic correctness from floating-point behavior. Fractions can grow large and become costly: keeping only three state slots does not imply that their integers occupy a fixed number of bytes. The native test demonstrates agreement on specified cases; it does not measure an accuracy advantage over every other variance implementation.
Check against a separate two-pass calculation
The downloadable test expression checks all eight exact published checkpoints. It then enumerates every ordered triple whose entries range from −2 through 2: 125 datasets. For each, it computes the mean and squared distances directly in two passes, and compares that state with our one-pass result. The test deliberately uses integer and Fraction arithmetic so equality is exact and rounding cannot hide an algebraic bug.
Three additional assertions check the empty summary, singleton summary and 100 identical negative observations. That makes 136 direct assertions, including the tolerance checks inside checkpoint eight. Open the tests as text, select the whole expression and Print it: expect 136, or an Error at a failed assertion. This is a direct assertion harness, not a SUnit test class. Passing the finite grid does not prove every possible input correct; the invariant supplies the accompanying argument.
Understand the storage trade-off
Each update performs a fixed number of arithmetic operations, and n observations require n updates. With fixed-width floating-point values this is O(n) work and O(1) retained numeric state. The implementation creates a fresh short Array per update, so it allocates O(n) Arrays over the entire run while retaining only the latest one. That choice keeps snapshots independent and makes the lesson easy to inspect; it is not a claim of zero allocation.
A saved trace intentionally keeps old states and therefore uses storage proportional to its length. Exact integer and Fraction operands have variable-size storage and arithmetic costs. To compare real performance, use the measurement workflow on a representative input and include allocation and rendering costs. An asymptotic operation count is not a measured speedup.
Turn the block into a useful object
- Extract the update into a class with count, mean and M2 instance variables. Add clear, add:, populationVariance and sampleVariance messages. Preserve explicit empty and singleton behavior.
- Write SUnit tests for translation and scaling: adding a constant should leave variance unchanged, while multiplying observations by k should multiply variance by k squared. Use exact values first, then chosen float tolerances.
- Connect a small input form to the object and display both variance labels. Do not replace the count with the total of a sliding window: removing old observations needs additional logic. A ring buffer retains recent data but does not automatically make these all-history statistics windowed.
This is different from reservoir sampling: a reservoir preserves a random subset, while this accumulator summarizes every supplied observation. Neither technique is a substitute for an explicit data-quality policy.
Sources and next steps
B. P. Welford’s original 1962 paper, Note on a Method for Calculating Corrected Sums of Squares and Products, is the historical reference. The publisher’s bibliographic record was checked; no claim of full-text access is made. The PartMC project’s own running-statistics source provides a primary implementation reference and cites Welford. Both references were consulted on 28 October 2026. This lesson’s Smalltalk blocks, tests and native visual presentation are original.
Continue with collection transformations, the dice probability lab and exact fractions. The official Squeak documentation covers the environment. Keep the statistical question—population description or sample estimation—separate from the algorithm that accumulates the numbers.