Reputation: 5
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.
Upvotes: 0
Views: 887
Reputation: 724
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?
Upvotes: 1