From 3d7b322a9d9defaf99a3f3f27aec45857697156f Mon Sep 17 00:00:00 2001 From: atomiks Date: Wed, 13 Dec 2017 23:48:29 +1100 Subject: [PATCH] Cache the mean --- snippets/standard-deviation.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/snippets/standard-deviation.md b/snippets/standard-deviation.md index a2b9a64fe..b1dd0b9c6 100644 --- a/snippets/standard-deviation.md +++ b/snippets/standard-deviation.md @@ -6,12 +6,14 @@ of the values to determine the standard deviation of an array of numbers. 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, usePopulation) => - Math.sqrt( - arr.reduce((acc, val) => acc.concat(Math.pow(val - arr.reduce((acc, val) => acc + val, 0) / arr.length, 2)), []) +const standardDeviation = (arr, usePopulation) => { + const mean = arr.reduce((acc, val) => acc + val, 0); + return Math.sqrt( + arr.reduce((acc, val) => acc.concat(Math.pow(val - mean / arr.length, 2)), []) .reduce((acc, val) => acc + val, 0) / (arr.length - (usePopulation ? 0 : 1)) ); + } // standardDeviation([10,2,38,23,38,23,21]) -> 13.284434142114991 (sample) // standardDeviation([10,2,38,23,38,23,21], true) -> 12.29899614287479 (population) ```