note 48768 added to function.srand

From: Date: Thu, 06 Jan 2005 16:22:56 +0000
Subject: note 48768 added to function.srand
Groups: php.notes 
Request: Send a blank email to php-notes+get-82846@lists.php.net to get a copy of this message
Hey, I use rand() all the time to get a rough probability of something happening. I went ahead and wrote a little function to help with the situation "I wish this thing would happen 2% of the time, so here is 5 lines of code to figure it out" since I run into it so much. Obviously, this is pretty similar to the if rand($x, $y) <$soething way, but I find it a little more flexible. /** * @return boolean * @param int $baseChance * @param int $chanceAmplifier * @desc Returns a true or false value based on a whether a random number * in the range 1 - (100 * $chanceAmplifier) is less than $baseChance. */ function RandomChance($baseChance, $chanceAmplifier = 1) { srand( ((int)((double)microtime()*1000003)) ); // get a good seed $totalBag = 100 * $chanceAmplifier; // set up max limit $probCheck = rand(1,$totalBag); // get random number if ( ($probCheck < $baseChance) ) { //compare it to $baseChance $result = true; } else { $result = false; } return $result; //Yay! } ---- Manual Page -- http://www.php.net/manual/en/function.srand.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+48768 Delete -- http://master.php.net/manage/user-notes.php?action=delete+48768&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+48768&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+48768&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+48768&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+48768&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+48768&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+48768&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#82846) next »