I am trying to get the standard deviation of a user input string. I have as follows, but it returns the wrong value for SD. The calculation should go as follows: Sum values/
This ES6 implementation matches Excel's built in STDEV.P and STDEV.S (.S is the default when STDEV is called). Passing in the true flag for usePopulation here will match Excel's STDEV.P
const standardDeviation = (arr, usePopulation = false) => {
const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length;
return Math.sqrt(
arr.reduce((acc, val) => acc.concat((val - mean) ** 2), []).reduce((acc, val) => acc + val, 0) /
(arr.length - (usePopulation ? 0 : 1))
);
};
console.log('STDEV.S =>',
standardDeviation([
10, 2, 38, 23, 38, 23, 21
])
);
console.log('STDEV.P =>',
standardDeviation([
10, 2, 38, 23, 38, 23, 21
], true)
);
Original Source