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

I have a large array of doubles, and I need to calculate the 75th and 90th percentile values โ€‹โ€‹for the array. What is the most efficient way to do this with a function?

+6
source share
2 answers

Some time has passed since the statistics, so I could be here, but here is a crack.

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); 
+13
source

The answer above may trigger a notification of an undefined value if you use a higher percentage value (100) and do not return the correct values โ€‹โ€‹according to the Excel PERCENTILE function. You can see here an example of how this fails .

I wrote a function in PHP on Wikipedia. The second option, which is used in Excel. This function is also protected against non-percentage value (out of range).

 function getPercentile($array, $percentile) { $percentile = min(100, max(0, $percentile)); 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; } 
0
source

Source: https://habr.com/ru/post/970343/


All Articles