Update standard-deviation.md

This commit is contained in:
Angelos Chalaris
2017-12-14 11:29:20 +02:00
committed by GitHub
parent cd43ed8b56
commit be8d285faf

View File

@ -1,17 +1,15 @@
### Standard deviation ### Standard deviation
Use `Array.reduce()` to calculate the mean of the values, the variance of the values, and the sum of the variance Use `Array.reduce()` to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then
of the values to determine the standard deviation of an array of numbers. determine the standard deviation.
You can omit the second argument to get the sample standard deviation or set it to `true` to get the population 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 ```js
const standardDeviation = (arr, usePopulation = false) => { const standardDeviation = (arr, usePopulation = false) => {
const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length; const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length;
return Math.sqrt( return Math.sqrt(
arr.reduce((acc, val) => acc.concat(Math.pow(val - mean, 2)), []) arr.reduce((acc, val) => acc.concat(Math.pow(val - mean, 2)), [])
.reduce((acc, val) => acc + val, 0) .reduce((acc, val) => acc + val, 0) / (arr.length - (usePopulation ? 0 : 1))
/ (arr.length - (usePopulation ? 0 : 1))
); );
} }
// standardDeviation([10,2,38,23,38,23,21]) -> 13.284434142114991 (sample) // standardDeviation([10,2,38,23,38,23,21]) -> 13.284434142114991 (sample)