Skip to content

Instantly share code, notes, and snippets.

@juliarose
Created March 5, 2023 02:35
Show Gist options
  • Save juliarose/ec2d3bcabb2ce9a628a5bddff001bf4c to your computer and use it in GitHub Desktop.
Save juliarose/ec2d3bcabb2ce9a628a5bddff001bf4c to your computer and use it in GitHub Desktop.
Calculates standard deviation
/**
* Gets the standard deviation from a set of numbers.
* @example
* const { mean, stdv } = getStandardDeviation([10, 10, 10, 10, 5]);
* console.log(mean); // 9
* console.log(stdv); // 2
* @param {[number]} numbers - An array of numbers.
* @returns Object containing `mean` and `stdv`.
*/
function getStandardDeviation(numbers) {
// Calculates the mean of all numbers
function calcMean(numbers) {
if (numbers.length === 0) {
return 0;
}
return numbers.reduce((sum, number) => sum + number, 0) / numbers.length;
}
// Calculates the standard deviation of all numbers
function calcStandardDeviation(numbers, mean) {
const deviationsSum = numbers.reduce((sum, number) => {
const diff = number - mean;
return sum + (diff * diff);
}, 0);
return Math.sqrt(deviationsSum / numbers.length);
}
const mean = calcMean(numbers);
const stdv = calcStandardDeviation(numbers, mean);
return {
mean,
stdv,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment