Standard deviation javascript

后端 未结 7 1148
感情败类
感情败类 2021-01-11 10:24

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/

7条回答
  •  臣服心动
    2021-01-11 10:49

    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

提交回复
热议问题