How can I calculate the nth percentile from an array of doubles in PHP?

前端 未结 3 1243
天涯浪人
天涯浪人 2021-01-05 17:12

I have a large array of doubles and I need to calculate the 75th and 90th percentile values for the array. What\'s the most efficient way to do this via a function?

3条回答
  •  执笔经年
    2021-01-05 18:01

    The answer above could throw an undefined index notice if you use the higher percent value (100) and does not return correct values according to Excel PERCENTILE function. You can see here an example of how it fails.

    I've written a function in PHP according the Wikipedia Second varitant, which is the one used in Excel. This function is also protected from a non percentual value (out of range).

    function getPercentile($array, $percentile)
    {
        $percentile = min(100, max(0, $percentile));
        $array = array_values($array);
        sort($array);
        $index = ($percentile / 100) * (count($array) - 1);
        $fractionPart = $index - floor($index);
        $intPart = floor($index);
    
        $percentile = $array[$intPart];
        $percentile += ($fractionPart > 0) ? $fractionPart * ($array[$intPart + 1] - $array[$intPart]) : 0;
    
        return $percentile;
    }
    

提交回复
热议问题