Fractions with PHP


<?php

// get some numbers to play with

$x=rand(0,130000)/10;
$y=rand(0,1200);
$z=rand(0,4)/64;
$array=array($x, $x, $x, $y, $y, $z, 324.19, 425/7, sqrt(2), pi(), pi());

// functions

function mult($n) { return intval(round($n*16)); }

function
frac($num) { $mod=fmod($num,1)*16;
if (
1 & $mod) { return " - ".$mod."/16"; }
else
$mod=$mod/2;
if (
1 & $mod) { return " - ".$mod."/8"; }
else
$mod=$mod/2;
if (
1 & $mod) { return " - ".$mod."/4"; }
else
$mod=$mod/2;
if (
1 & $mod) {return " - ".$mod."/2";}
}

// make a table

echo '<table>';
   
$array = array_map("mult", $array);
   
$array = (array_filter($array, strval)); //get rid of zeros
   
$array = (array_count_values ($array));
krsort ($array);
while (list (
$key, $val) = each ($array)) {
   
$key = $key/16;
echo
"<tr><td>$val</td><td>&nbsp; @ &nbsp;</td><td align=\"right\">".intval($key)." </td><td> ".frac($key)." </td></tr>";
}
echo
'</table>';

?>

See an example