碎片時間學編程「365]:計算數(shù)字數(shù)組的標準差

計算數(shù)字數(shù)組的標準差。 使用 Array.prototype.reduce() 計算值的均值、方差和方差之和并確定標準差。 省略第二個參數(shù) usePopulation 來獲取樣本標準差,或?qū)⑵湓O置為 true 來獲取總體標準差。
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)) ?);};
示例:
standardDeviation([10, 2, 38, 23, 38, 23, 21]); // 13.284434142114991 (sample)standardDeviation([10, 2, 38, 23, 38, 23, 21], true);// 12.29899614287479 (population)
更多內(nèi)容請訪問:https://www.icoderoad.com
標簽: