note 29071 added to ref.math

From: Date: Fri, 31 Jan 2003 23:25:08 +0000
Subject: note 29071 added to ref.math
Groups: php.notes 
Request: Send a blank email to php-notes+get-43234@lists.php.net to get a copy of this message
This might be useful in generating fractional numbers for construction, if only because most carpenters would rather put a nail in your foot than hear about any number that ends with .8125". Since I couldn't figure out the fraction code above, this is my simple-minded take on the problem. Also, align by "char" doesn't seem to work yet in html, so it seems necessary to use tables (egad!) to make numbers align properly. The following code illustrates a way to make a dynamically sized table with aligned fractions from an array of random numbers. Since I don't care about fractions less than 1/16, this rounds them into oblivion. Also, it sorts the list from long to short and collates multiples in the array. One bit of cleverness here (gleaned from these pages) that might not be obvious: I'm using 1 *bitwise and* (1 &) to determine odd numbers. If you copy and paste the following code, try refreshing the page a few times to see how the table adjusts itself. <?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>'; ?> -- http://www.php.net/manual/en/ref.math.php http://master.php.net/manage/user-notes.php?action=edit+29071 http://master.php.net/manage/user-notes.php?action=delete+29071 http://master.php.net/manage/user-notes.php?action=reject+29071

« previous php.notes (#43234) next »