Last active
May 21, 2021 00:04
-
-
Save baakeydow/a36d33c4c8872ad0d5c82d1a29e30328 to your computer and use it in GitHub Desktop.
stddev with typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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