z-Scores(standard deviation and mean) in PHP

前端 未结 5 1538
暖寄归人
暖寄归人 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));
    }
    
    0 讨论(0)
  • 2020-12-05 15:05

    The topic is pretty old, but actually I guess you can get the substitute of STDEV.P function from Excel easily using the function like below.

    function stdev_p($arr) {
        $arr2 = array();
        $mean = array_sum($arr)/count($arr);
        for ($x = 0; $x <count($arr); $x++) {
            $arr2[$x] = pow($arr[$x] - $mean,2);
        }
        return sqrt(array_sum($arr2)/count($arr));
    }
    
    0 讨论(0)
  • 2020-12-05 15:21
       function standard_deviation($aValues)
    {
        $fMean = array_sum($aValues) / count($aValues);
        //print_r($fMean);
        $fVariance = 0.0;
        foreach ($aValues as $i)
        {
            $fVariance += pow($i - $fMean, 2);
    
        }       
        $size = count($aValues) - 1;
        return (float) sqrt($fVariance)/sqrt($size);
    }
    
    0 讨论(0)
  • 2020-12-05 15:22

    How about using the built in statistics package like stats_standard_deviation and stats_harmonic_mean. I can't find a function for standard means, but if you know anything about statistics, I'm sure you can figure something out using the built-in functions.

    0 讨论(0)
  • 2020-12-05 15:27

    to calculate the mean you can do:

    $mean = array_sum($array)/count($array)
    

    standard deviation is like so:

    // Function to calculate square of value - mean
    function sd_square($x, $mean) { return pow($x - $mean,2); }
    
    // Function to calculate standard deviation (uses sd_square)    
    function sd($array) {
        // square root of sum of squares devided by N-1
        return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)-1) );
    }
    

    right off this page

    0 讨论(0)
提交回复
热议问题