reg: Percentile calculation in Math::Stats package
| From: | Yuvaraj V | Date: | Tue, 11 Dec 2007 15:10:42 +0000 |
| Subject: | reg: Percentile calculation in Math::Stats package | ||
| Groups: | php.pear.dev | ||
| Request: | Send a blank email to pear-dev+get-48751@lists.php.net to get a copy of this message | ||
Hi,
I had a requirement to calculate Nth Percentile from an array; I had a look
at the percentile calculation algorithm used in the Math::Stat package. I
tried the same and compared with the percentile obtained from Excel and
found that it doesn't match. So I wrote percentile calculation which matches
with the percentile obtained from Excel.
I am attaching the function here which can be easily integrated in the
current package. The following code may not be elegant ..
*function* *mypercentile *($data, $percentile){
if ( 0 < $percentile && $percentile < 1 ) {
$p = $percentile;
} else if (1 < $percentile && $percentile <= 100) {
$p = $percentile * .01;
} else {
return "";
}
$count = count ($data);
$allindex = ($count-1)*$p;
$intvalindex = intval ($allindex);
$floatval = $allindex - $intvalindex;
sort ($data);
if (!is_float($floatval)){
$result = $data [$intvalindex];
} else {
if ($count > $intvalindex+1)
$result = $floatval*($data[$intvalindex+1] -
$data[$intvalindex]) + $data[$intvalindex];
else
$result = $data[$intvalindex];
}
return $result;
}
Note: The existing algorithm calculates the 75th to 100th percentile as 56
for data [12, 34, 56], whereas in excel it grows linearly as expected.
Revert in case of any clarifications.
Regards,
Yuvaraj