Population vs sample standard deviation in JavaScript
Advanced · 4 min read
Two classes both average 70 on a test. In one, everyone scored between 65 and 75. In the other, scores ran from 20 to 100. The average hides that difference. Standard deviation shows it: it is a number for how spread out the values are. Spreadsheets, dashboards and quality checks use it all the time.
In this tutorial you will compute the population and sample standard deviation of [2, 4, 4, 4, 5, 5, 7, 9]. Then you will write the short one-pass formula from many textbooks, add a billion to every value, and watch it report a spread of zero. Finally you will fix it with a method called Welford's. You need to know reduce, Math.sqrt and arrow functions.
Variance and standard deviation
For [2, 4, 4, 4, 5, 5, 7, 9], the mean is 40 / 8 = 5. Now measure how far each value is from 5, and square it, so negatives don't cancel positives:
(2-5)² = 9, (4-5)² = 1 three times, (5-5)² = 0 twice, (7-5)² = 4, (9-5)² = 16
total = 9 + 3 + 0 + 4 + 16 = 32
The variance is the average of those squares: 32 / 8 = 4. The standard deviation (often "sd") is its square root, 2. Taking the root puts it back in the same units as the data.
Population or sample
If your numbers are the whole group you care about, divide by n. That is the population variance.
If they are a sample taken from a bigger group, divide by n - 1 instead. A sample's own mean sits a little closer to its values than the true mean of the whole group does, so the spread comes out too small. Dividing by one less makes up for it. For this data that gives 32 / 7.
Here is the exercise. Try it on your own first if you like, then read on and we will build it together.
94 Variance and standard deviation, and the formula that collapses
hardCompute the population and sample standard deviation of [2, 4, 4, 4, 5, 5, 7, 9]. Then implement the one-pass formula E[x squared] - E[x] squared, add a billion to every value, and see what each version says the variance is now.
Stuck? Three hints, smallest first
- 1. Population variance divides by
n, sample variance byn - 1. - 2. Adding a constant to every value cannot change the spread. Use that as a test.
- 3. The one-pass formula subtracts two huge, nearly equal numbers. That is where it dies.
Step 1: two passes
const add = (a, b) => a + b;
const mean = (xs) => xs.reduce(add, 0) / xs.length;
const populationVariance = (xs) => {
const m = mean(xs);
return xs.reduce((s, x) => s + (x - m) ** 2, 0) / xs.length;
};
const sampleVariance = (xs) => {
const m = mean(xs);
return xs.reduce((s, x) => s + (x - m) ** 2, 0) / (xs.length - 1);
};
const sample = [2, 4, 4, 4, 5, 5, 7, 9];
console.log(populationVariance(sample), Math.sqrt(populationVariance(sample))); // 4 2
console.log(sampleVariance(sample), Math.sqrt(sampleVariance(sample))); // 4.571428571428571 2.138089935299395
This is called the two-pass method: one pass over the data to find the mean, a second to add up the squared distances. The sample figure is always the bigger of the two, because it divides by a smaller number.
Step 2: the one-pass shortcut
Many textbooks give another formula: the mean of the squares minus the square of the mean. It needs only one pass, keeping two running totals.
const onePassVariance = (xs) => {
const n = xs.length;
const sum = xs.reduce(add, 0);
const sumSquares = xs.reduce((s, x) => s + x * x, 0);
return sumSquares / n - (sum / n) ** 2;
};
console.log(onePassVariance(sample)); // 4
On this data, it agrees: the mean of the squares is 29 and the square of the mean is 25.
Step 3: shift everything by a billion
Adding the same number to every value moves the whole group, but doesn't change how spread out it is. So the variance should still be 4.
const shifted = sample.map((x) => x + 1e9);
console.log(populationVariance(shifted)); // 4
console.log(onePassVariance(shifted)); // 0
The two-pass method still says 4. The one-pass formula says 0, as if every value were identical.
Here is why. Now both the mean of the squares and the square of the mean are about 1,000,000,010,000,000,000. They agree in their first 16 digits, and a JavaScript number only holds about 16 digits. Subtracting two nearly equal big numbers leaves nothing but rounding errors. This is called catastrophic cancellation, and it is a common bug in real reporting code.
Step 4: Welford's method
If you can only look at the data once, for example a stream of sensor readings, there is a safe one-pass method. Welford's method keeps a running mean, and adds up squared distances from that running mean as it goes, so it never builds a huge number.
const welfordVariance = (xs) => {
let n = 0;
let m = 0;
let m2 = 0;
for (const x of xs) {
n++;
const delta = x - m;
m += delta / n;
m2 += delta * (x - m);
}
return m2 / n;
};
console.log(welfordVariance(sample)); // 4
console.log(welfordVariance(shifted)); // 3.999999977648258
For each value, delta is how far it is from the old mean. The mean moves a little toward it, and m2 grows by the distance from the old mean times the distance from the new one. At the end, m2 / n is the variance.
On the shifted data it gives 3.999999977648258: off in the eighth digit, but nowhere near the 100% error of the one-pass formula. When you already have the whole array in memory, two passes is simpler and exact.
Step 5: scaling, and a single value
const scaled = sample.map((x) => x * 10);
console.log(populationVariance(scaled), Math.sqrt(populationVariance(scaled))); // 400 20
console.log(populationVariance([5]), sampleVariance([5])); // 0 NaN
Multiply every value by 10 and the sd grows by 10; the variance, being squared, grows by 100. A single value has a population variance of 0. Its sample variance is 0 / 0, which is NaN, and that is the right answer: one measurement tells you nothing about spread.
The full solution
The answer panel has the two-pass, one-pass and Welford versions, and prints the mean, both kinds of variance and sd, the shifted and scaled data and the single-value case. Press Run to see the output.
const add = (a, b) => a + b;
const mean = (xs) => xs.reduce(add, 0) / xs.length;
// Two passes: find the mean, then sum the squared deviations from it.
const populationVariance = (xs) => {
const m = mean(xs);
return xs.reduce((s, x) => s + (x - m) ** 2, 0) / xs.length;
};
const sampleVariance = (xs) => {
const m = mean(xs);
return xs.reduce((s, x) => s + (x - m) ** 2, 0) / (xs.length - 1);
};
// One pass, textbook, and dangerous.
const onePassVariance = (xs) => {
const n = xs.length;
const sum = xs.reduce(add, 0);
const sumSquares = xs.reduce((s, x) => s + x * x, 0);
return sumSquares / n - (sum / n) ** 2;
};
// One pass, done properly: update the mean as you go.
const welfordVariance = (xs) => {
let n = 0;
let m = 0;
let m2 = 0;
for (const x of xs) {
n++;
const delta = x - m;
m += delta / n;
m2 += delta * (x - m);
}
return m2 / n;
};
const sample = [2, 4, 4, 4, 5, 5, 7, 9];
const shifted = sample.map((x) => x + 1e9);
const scaled = sample.map((x) => x * 10);
console.log('mean :', mean(sample));
console.log('population var, sd :', populationVariance(sample), Math.sqrt(populationVariance(sample)));
console.log('sample var, sd :', sampleVariance(sample), Math.sqrt(sampleVariance(sample)));
console.log('one pass, small data :', onePassVariance(sample), 'Welford:', welfordVariance(sample));
console.log('shifted by 1e9, two-pass:', populationVariance(shifted));
console.log('shifted, one pass :', onePassVariance(shifted), '<- the spread did not change');
console.log('shifted, Welford :', welfordVariance(shifted));
console.log('scaled by 10 :', populationVariance(scaled));
console.log('a single value :', populationVariance([5]), sampleVariance([5]));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the mean is 5, the population variance 4, and the sd exactly 2', [mean(sample), populationVariance(sample), Math.sqrt(populationVariance(sample))], [5, 4, 2]);
test('dividing by n - 1 instead gives 32 / 7 and an sd of 2.138...', [sampleVariance(sample), sampleVariance(sample) === 32 / 7, Math.sqrt(sampleVariance(sample))], [4.571428571428571, true, 2.138089935299395]);
test('the sample figure is always the larger of the two', sampleVariance(sample) > populationVariance(sample), true);
test('on this data the one-pass formula and Welford both agree with two passes', [onePassVariance(sample), welfordVariance(sample)], [4, 4]);
test('adding a billion to every value cannot change the spread, and does not', populationVariance(shifted), 4);
test('but the one-pass formula returns exactly zero, having cancelled itself away', [onePassVariance(shifted), Object.is(onePassVariance(shifted), 0)], [0, true]);
test('Welford survives the shift, though not to the last bit', [welfordVariance(shifted), Math.abs(welfordVariance(shifted) - 4) < 1e-7], [3.999999977648258, true]);
test('scaling by 10 multiplies the variance by 100 and the sd by 10', [populationVariance(scaled), Math.sqrt(populationVariance(scaled))], [400, 20]);
test('one value has population variance 0 and no sample variance at all', [populationVariance([5]), Number.isNaN(sampleVariance([5]))], [0, true]);
E[x squared] - E[x] squared is algebraically identical to the two-pass formula and it is the version in most textbooks, because it needs one pass and two running totals. On this data it gives 4, same as everything else. Add a billion to every value — which changes nothing about the spread — and it returns exactly 0. The mean of the squares is about 1.000000010000000e+18 and the square of the mean is about the same, and subtracting two numbers that agree in their first sixteen digits leaves nothing but rounding noise. This is catastrophic cancellation, and it is the single most common numerical bug in real analytics code.
Welford's method is the one-pass version that works: keep a running mean and a running sum of squared deviations from that mean, and never form a large intermediate. It gives 3.999999977648258 on the shifted data — not exact, but wrong in the eighth digit rather than being wrong by 100%. Two passes over an array you already hold in memory is exact and simpler; Welford is for streams you only see once.
The n against n - 1 choice is statistics, not arithmetic. Divide by n when the numbers are the whole population; divide by n - 1 when they are a sample and you are estimating a wider population's spread, because the sample mean sits closer to the sample than the true mean does and the correction compensates. It follows that sample variance is always the larger, and that a single observation has no sample variance at all — 0 / 0 is NaN, which is the right answer rather than an error.
Common mistakes
- Using the one-pass shortcut on real data. When the values are large and close together, it cancels itself out. Use two passes, or Welford for streams.
- Mixing up
nandn - 1. Divide bynfor a whole population and byn - 1for a sample. - Forgetting the square root. Variance is in squared units. The sd is
Math.sqrtof it.
Try it yourself
- Add a
sampleSdfunction and check it gives 2.138089935299395 for the sample data. - Change
welfordVarianceto return the sample variance instead. - Shift the data by 1e6 instead of 1e9. Does the one-pass formula still give exactly 4?