Skip to content

Instantly share code, notes, and snippets.

@baakeydow
Last active May 21, 2021 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baakeydow/a36d33c4c8872ad0d5c82d1a29e30328 to your computer and use it in GitHub Desktop.
Save baakeydow/a36d33c4c8872ad0d5c82d1a29e30328 to your computer and use it in GitHub Desktop.
stddev with typescript
const average = (arr: number[]): number => arr.reduce((p, c) => p + c, 0) / arr.length;
const standardDeviation = (values: number[]) => {
const avg = average(values);
const squareDiffs = values.map((value) => {
let diff = value - avg;
let sqrDiff = diff * diff;
return sqrDiff;
});
const avgSquareDiff = average(squareDiffs);
return Math.sqrt(avgSquareDiff);
};
const values = [{i: 2, x: '42'}, {i: 0, x: '21'}, {i: 3, x: '84'}, {i: 1, x: '168'}]
const stdDev = Number(standardDeviation(values.map((data) => Number(data.x)))).toFixed(3);
console.log(stdDev) // 56.300
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment