March 20, 2000

PHP fractions

This is a quickie test of my "random numbers to sorted legible fractions" widget.
Refreshing the page will show you what it does.
Sort of.
3  @  7205 - 3/8
1  @  324 - 3/16
2  @  129
1  @  60 - 11/16
2  @  3 - 1/8
1  @  1 - 7/16
1  @  0 - 1/16

Source for above:

<?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>';

?>
Posted by Hal Eckhart at March 20, 2000 06:56 AM | TrackBack
Comments
Post a comment
spam and annoying comments will be deleted







Remember personal info?




enter this number security code in the box below (prevents comment spam)