Skip to content

Instantly share code, notes, and snippets.

@petergi
Last active January 29, 2024 23:22
Show Gist options
  • Select an option

  • Save petergi/3737387ebbdc780b2573e61ac4482c89 to your computer and use it in GitHub Desktop.

Select an option

Save petergi/3737387ebbdc780b2573e61ac4482c89 to your computer and use it in GitHub Desktop.
Calculates the standard deviation of an array of numbers
/**
* Calculates the standard deviation of an array of numbers.
*
* @param {Array} arr - The array of numbers.
* @param {Boolean} usePopulation - Optional. If true, the function uses the population standard deviation formula. Default is false, which uses the sample standard deviation formula.
* @return {Number} - The standard deviation of the array.
*/
const standardDeviation = (arr, usePopulation = false) => {
const n = arr.length
let sum = 0
let mean = 0
for (let i = 0; i < n; i++) {
sum += arr[i]
}
mean = sum / n
let sumOfSqDiff = 0
for (let i = 0; i < n; i++) {
sumOfSqDiff += (arr[i] - mean) ** 2
}
return Math.sqrt(sumOfSqDiff / (n - (usePopulation ? 0 : 1)))
}
// sample standard deviation
standardDeviation([10, 2, 38, 23, 38, 23, 21]) // 13.284434142114991
// population standard deviation
standardDeviation([10, 2, 38, 23, 38, 23, 21], true) // 12.29899614287479;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment