note 34074 added to function.rand

From: Date: Tue, 15 Jul 2003 15:43:52 +0000
Subject: note 34074 added to function.rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-52141@lists.php.net to get a copy of this message
This is a good way if you want gen probabilitys(like the word says). It returns TRUE if the random value is inside the bound $howmuch. Very good for garbage collectors. class Probability { private function __construct() { } public static function get($howmuch) { if ($howmuch <= 100) { $percent = 100 - $howmuch; srand((double)microtime()*1000000); $randvalue = rand(0,100); if ($randvalue >= $percent) return TRUE; else return FALSE; } } } Pay attention that it won´t return always TRUE or FALSE in the same way. If you test it 100 times, the return values always change. Consider the folowing: for ($j=0;$j<=4;$j++){ $value = 20; $CTrue = 0; $CFalse = 0; for ($i=0;$i<=99;$i++){ if (Probability::get($value)) $CTrue++; else $CFalse++; } echo "Iteracao: " . $j . "\n"; echo "Probabilidade: " . $value . "\n"; echo "True: " . $CTrue . "\n"; echo "False: " . $CFalse . "\n\n"; } Eduardo R. Maciel (inetd) ---- Manual Page -- http://www.php.net/manual/en/function.rand.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+34074 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+34074&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+34074&report=yes

« previous php.notes (#52141) next »