Skip to content

Instantly share code, notes, and snippets.

@smockle
Created February 15, 2022 18:24
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 smockle/60f261920fd6dbcb4f9909f8cc022824 to your computer and use it in GitHub Desktop.
Save smockle/60f261920fd6dbcb4f9909f8cc022824 to your computer and use it in GitHub Desktop.
Average and standard deviation functions
// 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