From 7df83ac6b3bafcd3f983413f6bbc158d68ac432a Mon Sep 17 00:00:00 2001 From: atomiks Date: Wed, 13 Dec 2017 23:41:28 +1100 Subject: [PATCH] Add usePopulation flag param --- snippets/standard-deviation.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/snippets/standard-deviation.md b/snippets/standard-deviation.md index 0ae7f56af..a2b9a64fe 100644 --- a/snippets/standard-deviation.md +++ b/snippets/standard-deviation.md @@ -3,15 +3,15 @@ Use `Array.reduce()` to calculate the mean of the values, the variance of the values, and the sum of the variance of the values to determine the standard deviation of an array of numbers. -NOTE: This is **population standard deviation**. Use `/ (arr.length - 1)` at the end to -calculate **sample standard deviation**. +Since there are two types of standard deviation, population and sample, you can use a flag to switch to population (sample is default). ```js -const standardDeviation = arr => +const standardDeviation = (arr, usePopulation) => Math.sqrt( arr.reduce((acc, val) => acc.concat(Math.pow(val - arr.reduce((acc, val) => acc + val, 0) / arr.length, 2)), []) .reduce((acc, val) => acc + val, 0) - / arr.length + / (arr.length - (usePopulation ? 0 : 1)) ); -// standardDeviation([10,2,38,23,38,23,21]) -> 12.298996142875 +// standardDeviation([10,2,38,23,38,23,21]) -> 13.284434142114991 (sample) +// standardDeviation([10,2,38,23,38,23,21], true) -> 12.29899614287479 (population) ```