note 13135 modified in function.srand by felipe

From: Date: Wed, 23 Jul 2008 13:07:18 +0000
Subject: note 13135 modified in function.srand by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-142605@lists.php.net to get a copy of this message
Use the srand() seed "(double)microtime()*1000000" as mentioned by the richard@zend.com at the top of these user notes. The most notable effect of using any other seed is that your random numbers tend to follow the same, or very similar, sequences each time the script is invoked. Take note of the following script: <?php srand($val); echo rand(0, 20) . ", "; echo rand(0, 20) . ", "; echo rand(0, 20) . ", "; echo rand(0, 20) . ", "; echo rand(0, 20); ?> If you seed the generator with a constant, say; the number 5 ($val = 5), then the sequence generated is always the same, in this case (0, 18, 7, 15, 17) (for me at least, different processors/processor speeds/operating systems/OS releases/PHP releases/webserver software may generate different sequences). If you seed the generator with time(), then the sequence is more random, but invokations that are very close together will have similar outputs. As richard@zend.com above suggests, the best seed to use is (double) microtime() * 1000000, as this gives the greatest amount of psuedo-randomness. In fact, it is random enough to suit most users. In a test program of 100000 random numbers between 1 and 20, the results were fairly balanced, giving an average of 5000 results per number, give or take 100. The deviation in each case varied with each invokation. --was-- Use the srand() seed "(double)microtime()*1000000" as mentioned by the richard@zend.com at the top of these user notes. The most notable effect of using any other seed is that your random numbers tend to follow the same, or very similar, sequences each time the script is invoked. Take note of the following script: srand($val); echo rand(0, 20) . ", "; echo rand(0, 20) . ", "; echo rand(0, 20) . ", "; echo rand(0, 20) . ", "; echo rand(0, 20); If you seed the generator with a constant, say; the number 5 ($val = 5), then the sequence generated is always the same, in this case (0, 18, 7, 15, 17) (for me at least, different processors/processor speeds/operating systems/OS releases/PHP releases/webserver software may generate different sequences). If you seed the generator with time(), then the sequence is more random, but invokations that are very close together will have similar outputs. As richard@zend.com above suggests, the best seed to use is (double) microtime() * 1000000, as this gives the greatest amount of psuedo-randomness. In fact, it is random enough to suit most users. In a test program of 100000 random numbers between 1 and 20, the results were fairly balanced, giving an average of 5000 results per number, give or take 100. The deviation in each case varied with each invokation. http://php.net/manual/en/function.srand.php

« previous php.notes (#142605) next »