Created
December 23, 2022 05:34
-
-
Save cshanejennings/ca8d9c8c544e6352403953d662b0d4cf to your computer and use it in GitHub Desktop.
Standard Deviation snippets (terse & verbose)
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
// explained | |
function calculateStandardDeviation(numbers) { | |
// Calculate the mean of the array of numbers | |
const mean = numbers.reduce((a, b) => a + b, 0) / numbers.length; | |
// Calculate the differences between the numbers and the mean | |
const differences = numbers.map(num => num - mean); | |
// Square each of the differences | |
const squaredDifferences = differences.map(diff => diff ** 2); | |
// Add all of the squared differences together | |
const sumSquaredDifferences = squaredDifferences.reduce((a, b) => a + b, 0); | |
// Divide the sum of the squared differences by the total number of numbers in the array | |
const variance = sumSquaredDifferences / numbers.length; | |
// Take the square root of the variance to get the standard deviation | |
const standardDeviation = Math.sqrt(variance); | |
return standardDeviation; | |
} | |
const numbers = [0, 1, 1, 3, 2, 1, 0, 3, 6, 2, 2, 0]; | |
const standardDeviation = calculateStandardDeviation(numbers); | |
console.log(standardDeviation); // Output: 1.63 | |
//shortened | |
const std_dev = (numbers) => { | |
const avg = n=>n.reduce((a=0,b)=>a+b)/n.length, mean = avg(numbers); | |
return Math.sqrt(avg(numbers.map(n=>(n-mean)**2))); | |
} | |
console.log(std_dev([0, 1, 1, 3, 2, 1, 0, 3, 6, 2, 2, 0])); // Output: 1.63 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment