Created
February 15, 2022 18:24
-
-
Save smockle/60f261920fd6dbcb4f9909f8cc022824 to your computer and use it in GitHub Desktop.
Average and standard deviation functions
This file contains hidden or 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
// To use in the Node.js REPL: | |
// const { getAverage, getStandardDeviation } = await import("./stddev.mjs"); | |
// @ts-check | |
export function getAverage(...values) { | |
return values.reduce((sum, value) => sum + value, 0) / values.length; | |
} | |
export function getStandardDeviation(...values) { | |
const average = getAverage(...values); | |
const squaredDifferences = values.map((value) => | |
Math.pow(value - average, 2) | |
); | |
const variance = getAverage(...squaredDifferences); | |
return Number(Math.pow(variance, 0.5).toFixed(2)); | |
} | |
// Tests: | |
// getAverage(2, 1, 3, 2, 4) should be 2.40 | |
// getStandardDeviation(2, 1, 3, 2, 4) should be 1.01 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment