Streaming Variance: Welford and Merge
Prerequisites: Numerical Stability Intro, Floating-Point Representation
A risk report shows the mean and variance of the day's AAPL trade prices while trades are still arriving. Build an accumulator that keeps three numbers per stream and stays accurate, then combine accumulators filled on different threads.
Two simpler methods fail. Keeping every price for a second pass needs memory that grows all day. The one-pass textbook formula, the mean of the squares minus the square of the mean, subtracts two large, nearly equal numbers: catastrophic cancellation, from the Numerical Stability article.
- Shard: one named accumulator, named by 1 to 8 lowercase letters or digits. A shard that has never received a price is empty.
- Population variance: the mean of the squared deviations from the mean,
((x1 - mean)^2 + ... + (xn - mean)^2) / n. It divides byn, notn - 1.
What to implement
process_commands(commands)takes one command per line and returns the printed lines in command order.- Prices are integer ticks, cents for
AAPL, as the course stores them:19010is $190.10. Their mean and variance are usually fractional, so those two values aredoubles. - On stdin, the first line is the number of commands, and each remaining line is one command.
- There are two parts. One solution must pass all nine tests.
| Command | Meaning | Prints |
|---|---|---|
ADD shard price | Add one trade price to shard | nothing |
STATS shard | Report shard's statistics | shard count mean variance, or shard EMPTY when it holds no prices |
MERGE dst src | Fold src into dst, then empty src (Part 2) | nothing |
In the STATS line, count is the number of prices in the shard and variance is the population variance. Print mean and variance with exactly six digits after the point, as printf("%.6f", v) in C++ and f"{v:.6f}" in Python do.
Part 1: Welford's update
Each shard stores n, how many prices it has seen; mean, their average so far; and M2, the total of each price's squared distance from that average. An empty shard has n = 0, mean = 0, and M2 = 0.
ADD shard x applies Welford's update:
n = n + 1
delta = x - mean // distance from the old mean
mean = mean + delta / n
M2 = M2 + delta * (x - mean) // this x - mean uses the new mean
STATS shard prints n, mean, and M2 / n.
The update never forms x * x. delta and x - mean are distances from the mean, a few ticks when prices are close together, so their product is small and no two large numbers cancel.
Limits and guarantees
- Prices are integers between 1 and 108. There are at most 105 commands.
- Every expected line was checked against the exact answer computed with rational arithmetic.
- Every printed value sits far from a point where rounding to six decimals could go either way. A correct double-precision solution prints the same digits even if its operation order differs a little from the reference.
Tests 1–4 cover this part. Tests 3 and 4 include prices of 10 to 20 million ticks (such as a $100,000 contract quoted in cents) that move by only a few ticks:
- The textbook formula
sum_sq / n - mean * meanfails them. Both terms are near 1014, where neighboring doubles are 1/64 apart. - On the second line of test 3 it prints
2.875000where the answer is2.888889.
Part 2: Merging shards
The feed handler fills one shard per thread, so its hot path takes no lock. At the end of an interval the desk combines the shards.
Adding up the raw sums of x and x * x would bring back the textbook formula, so combine the three-number states. For states (n_a, mean_a, M2_a) and (n_b, mean_b, M2_b), the pairwise combination, known as Chan's formula, is:
n = n_a + n_b delta = mean_b - mean_a mean = mean_a + delta * n_b / n M2 = M2_a + M2_b + delta * delta * n_a * n_b / n
MERGE dst srcreplaces the state ofdstwith the combination ofdst(asa) andsrc(asb), then emptiessrc. Every price is counted once, even ifsrckeeps receiving prices afterwards.- If
srcis empty,dstis unchanged. - If
dstis empty, it takes the three numbers ofsrcas they are. dstandsrcare always different names, and either may be a name not seen before.
Tests 5–9 cover this part. Tests 5, 7, and 8 also send every price to a shard named all, so a merged shard and all print the same line. Test 8 uses prices near 107 again, where merging raw sums fails.
9 ADD aapl 19010 STATS aapl ADD aapl 19012 STATS aapl ADD aapl 19011 STATS aapl ADD aapl 19015 ADD aapl 19009 STATS aapl
aapl 1 19010.000000 0.000000 aapl 2 19011.000000 1.000000 aapl 3 19011.000000 0.666667 aapl 5 19011.400000 4.240000
The first line is the command count. The first price sets mean to 19010 and leaves M2 at 0, so one sample has variance 0.
The second price gives delta = 2, mean = 19011, and M2 = 0 + 2 * (19012 - 19011) = 2, so the variance is 2 / 2 = 1.
The third price equals the mean, so delta = 0 and only n changes, giving 2 / 3 = 0.666667.
Then 19015 gives delta = 4, mean = 19012, and M2 = 2 + 4 * 3 = 14.
19009 gives delta = -3, mean = 19011.4, and M2 = 14 + (-3) * (-2.4) = 21.2. The last line prints 21.2 / 5 = 4.24.