Last active
January 29, 2024 23:22
-
-
Save petergi/3737387ebbdc780b2573e61ac4482c89 to your computer and use it in GitHub Desktop.
Calculates the standard deviation of an array of numbers
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
| /** | |
| * 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