note 19321 added to function.srand

From: Date: Fri, 22 Feb 2002 22:53:23 +0000
Subject: note 19321 added to function.srand
Groups: php.notes 
Request: Send a blank email to php-notes+get-26961@lists.php.net to get a copy of this message
In addition to my earlier post being stupidly coded with $wasseeded = TRUE :-| here is an update: In PHP4, I *BELIEVE* the random number generator will seed itself if you don't seed it. In PHP3, or some versions of PHP3?, that was not the case -- An unseeded rand() wouldn't be random. While it would "work fine" in terms of spitting out a number, an unseeded random number generator won't be very random in many situations unless it has been properly seeded. I'm afraid I can't explain all the details of why this is because A) it would be an entire textbook, and B) I don't know them all by heart, even if I understood them 20 years ago in college. If you are running PHP4, you are probably okay, and if you are happy with the randomness of your values, you are fine, but you may want to do a little test like: <?php $stats[1] = 0; $stats[2] = 0; $stats[3] = 0; for ($i = 0; $i < 1000; $i++){ if (!$i){ $choice = rand(1,3); echo "First random choice: $choice<BR>\n"; } $stats[$choice]++; } reset($stats); while (list($num, $count) = each($stats)){ echo "$num: $count<BR>\n"; } ?> Run the test a half-dozen times and check that the distribution of 1, 2, and 3 is even, and that the first number chosen is not the same every time. This is hardly an exhaustive test, but it at least gives some reassurance that the numbers aren't completely predictable. You may also wish to switch to http://php.net/mt_rand which is faster (if you generate a *LOT* of numbers) and allegedly a "better" (more random) function. Again, it would be an entire book to explain why mt_rand is "more random"... YMMV. If you're doing "Casino Slots" with real money, you'd better do your homework on this. If you're giving away a free CD or something silly, who cares? -- http://www.php.net/manual/en/function.srand.php http://master.php.net/manage/user-notes.php?action=edit+19321 http://master.php.net/manage/user-notes.php?action=delete+19321 http://master.php.net/manage/user-notes.php?action=reject+19321

« previous php.notes (#26961) next »