z-Scores(standard deviation and mean) in PHP

前端 未结 5 1542
暖寄归人
暖寄归人 2020-12-05 14:47

I am trying to calculate Z-scores using PHP. Essentially, I am looking for the most efficient way to calculate the mean and standard deviation of a data set (PHP array). Any

5条回答
  •  北海茫月
    2020-12-05 15:04

    This is the same std dev code from the php pages mentioned in the top answer, but modernized a bit, without the one-line array magic and separate helper function:

    /**
     * Calculates the standard deviation of an array of numbers.
     * @param   array   $array  The array of numbers to calculate the standard deviation of.
     * @return  float   The standard deviation of the numbers in the given array.
     */
    function calculateStdDev(array $array): float
    {
        $size = count($array);
        $mean = array_sum($array) / $size;
        $squares = array_map(function ($x) use ($mean) {
            return pow($x - $mean, 2);
        }, $array);
    
        return sqrt(array_sum($squares) / ($size - 1));
    }
    

提交回复
热议问题