Module 12 · Statistical Computing and Reproducibility Lesson 112 of 120

Stable Summation and Mean Calculation

Recovering low-order contributions during accumulation.

2:37 clip6:04:05–6:06:42 in the full courseWatch on YouTube

Transcript

18 sentences · select one to jump there

Check your understanding

Can compensated summation restore precision already absent from the input values?

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.

112-stable-summation-and-mean-calculation.ts
Start from GitHub
/**
 * Fintech Math Bootcamp · Lesson 112 of 120
 * Stable Summation and Mean Calculation
 * Module 12: Statistical Computing and Reproducibility
 *
 * Scenario: Recovering low-order contributions during accumulation
 * Rule:     compensated sum tracks information lost by rounding
 *
 * Try it:   Can compensated summation restore precision already absent from the input values?
 *
 * Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/statistical-computing-and-reproducibility/stable-summation-and-mean-calculation/
 * Free course:    https://courses.thefintechbuilder.com
 * Synthetic teaching example, not financial advice or a production library.
 */

export function lesson112() {
  const values=[1e16,1,-1e16,3];
  let sum=0,correction=0;
  // Neumaier (improved Kahan) compensation: also handles |x| > |sum|
  for(const x of values){const next=sum+x;
    correction+=Math.abs(sum)>=Math.abs(x)?(sum-next)+x:(x-next)+sum;
    sum=next;}
  const result={naive:values.reduce((s,x)=>s+x,0),
    compensated:sum+correction};
  return result;
}

export const checkedResult = {"naive":3,"compensated":4};

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

Your output

Press Run to execute the code in your browser.

Expected output

{
  "naive": 3,
  "compensated": 4
}

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

Lesson notes

The rule

compensated sum tracks information lost by rounding