简体   繁体   中英

PHP function to calculate percentiles of array - doesn't give the correct result

I'm using this function (from https://stackoverflow.com/a/46227341/10495991 ) to calculate the 25th percentile of an arrary:

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;
}

I'm applying the function to this array

Array ( [0] => 9814106112 [1] => 0 [2] => 5692473344 [3] => 360448 [4] => 8514641920 [5] => 5228150784 [6] => 11731894272 [7] => 7707688960 [8] => 11325239296 [9] => 360448 [10] => 13382311936 [11] => 11934347264 [12] => 7919140864 [13] => 7370223616 [14] => 46461620224 [15] => 360448 )

In Excel, the 25 percentile should be 3921203200, but the function returns 13020320768 which is way higher than Excel.

I have absolutely no clue why the result is wrong. Any help is appreciated.

I'm getting the expected result using:

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;
}

$array = [9814106112,0,5692473344,360448,8514641920,5228150784,11731894272,7707688960,11325239296,360448,13382311936,11934347264,7919140864,7370223616,46461620224,360448];
$percentile = 25;
$result = getPercentile($array, $percentile);
var_dump($result); //float(3921203200) 

Are you giving your function the right arguments?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM