note 16502 added to function.mt-srand
| From: | trobinson-a-t-gksystems-d-o-t-com at php2 dot chek dot com | Date: | Fri, 02 Nov 2001 07:15:51 +0000 |
| Subject: | note 16502 added to function.mt-srand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-20284@lists.php.net to get a copy of this message | ||
I see a problem with seeding with:
mt_srand((double)microtime()*1000000);
Too few seeds.
This chooses the seed from a space of only one million seeds. This is a shame, because the Mersenne
Twister algorithm has a period of 2**19937-1.
So of all the possible starting points in the MT sequence, the above seed only chooses at random
from among 1000000 starting points, or about 0.000...0001% of the possible starting points, where
"..." is a string of about 5986 more zeros!
In real life, this means that if you note the first few random numbers, when you see the same first
few numbers again, the chances are very good that you have the same seed and the rest of the
sequence will be the same too.
If you generate a random "unique" 100-character key for say cookie use, seeding as above,
you will likely get a duplicate key after only 1000 keys or so.
Better: To supplement the results from mt_rand, also hash in the entire contents of the microtime()
string.
Better still: Use a 31-bit hash of microtime() as the seed.
Problem 2. Way too few seeds on some hardware. It is bad to rely on a clock ticking every
microsecond. I have used computers where 100ms was the finest-resolution clock available. That would
be just 10 different seeds, as the results from (double)microtime() would look like:
0.10000000
0.20000000
etc.
--
http://www.php.net/manual/en/function.mt-srand.php
http://master.php.net/manage/user-notes.php?action=edit+16502
http://master.php.net/manage/user-notes.php?action=delete+16502
http://master.php.net/manage/user-notes.php?action=reject+16502