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

前端 未结 3 1273
天涯浪人
天涯浪人 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:05

    It's been awhile since statistics, so I could be off here - but here's a crack at it.

    function get_percentile($percentile, $array) {
        sort($array);
        $index = ($percentile/100) * count($array);
        if (floor($index) == $index) {
             $result = ($array[$index-1] + $array[$index])/2;
        }
        else {
            $result = $array[floor($index)];
        }
        return $result;
    }
    
    $scores = array(22.3, 32.4, 12.1, 54.6, 76.8, 87.3, 54.6, 45.5, 87.9);
    
    echo get_percentile(75, $scores);
    echo get_percentile(90, $scores);
    

提交回复
热议问题