Module 12 · Statistical Computing and Reproducibility Lesson 113 of 120

Stable Online Variance and Welford’s Algorithm

Updating variance as records arrive without unstable raw subtraction.

2:38 clip6:06:42–6:09:21 in the full courseWatch on YouTube

Transcript

17 sentences · select one to jump there

Check your understanding

Does ordinary Welford automatically expire the oldest rolling-window observation?

Choose one answer

Code lab

Run it yourself

The lesson source in 7 languages. Edit it, run TypeScript and Python right here, and compare with the expected output.

113-stable-online-variance-and-welfords-algorithm.ts
Start from GitHub
/**
 * Fintech Math Bootcamp · Lesson 113 of 120
 * Stable Online Variance and Welford’s Algorithm
 * Module 12: Statistical Computing and Reproducibility
 *
 * Scenario: Updating variance as records arrive without unstable raw subtraction
 * Rule:     n → mean → M₂; sample variance=M₂/(n−1)
 *
 * Try it:   Does ordinary Welford automatically expire the oldest rolling-window observation?
 *
 * Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/statistical-computing-and-reproducibility/stable-online-variance-and-welford-s-algorithm/
 * Free course:    https://courses.thefintechbuilder.com
 * Synthetic teaching example, not financial advice or a production library.
 */

export function lesson113() {
  const values=[1,2,3,4,5];
  let count=0,mean=0,m2=0;
  const states:{count:number;mean:number;m2:number}[]=[];
  for(const x of values){count++;const delta=x-mean;
    mean+=delta/count;m2+=delta*(x-mean);
    states.push({count,mean,m2});}
  const result={count,mean,m2,sampleVariance:m2/(count-1),states};
  return result;
}

export const checkedResult = {"count":5,"mean":3,"m2":10,"sampleVariance":2.5,"states":[{"count":1,"mean":1,"m2":0},{"count":2,"mean":1.5,"m2":0.5},{"count":3,"mean":2,"m2":2},{"count":4,"mean":2.5,"m2":5},{"count":5,"mean":3,"m2":10}]};

// Run this file directly: npx tsx lessons/12-statistical-computing-and-reproducibility/113-stable-online-variance-and-welfords-algorithm.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
  console.log(JSON.stringify(lesson113(), null, 2));
}

Your output

Press Run to execute the code in your browser.

Expected output

{
  "count": 5,
  "mean": 3,
  "m2": 10,
  "sampleVariance": 2.5,
  "states": [
    {
      "count": 1,
      "mean": 1,
      "m2": 0
    },
    {
      "count": 2,
      "mean": 1.5,
      "m2": 0.5
    },
    {
      "count": 3,
      "mean": 2,
      "m2": 2
    },
    {
      "count": 4,
      "mean": 2.5,
      "m2": 5
    },
    {
      "count": 5,
      "mean": 3,
      "m2": 10
    }
  ]
}

Prefer your own machine? Every file is in the course repository · open it in Codespaces.

Lesson notes

The rule

n → mean → M₂; sample variance=M₂/(n−1)