|
Posted by Gordon Burditt on 04/23/06 06:57
>I need to generate 2 random numbers in rapid sequence from either PHP or
>mysql.
Same page hit or different page hits? I cannot explain why you
would get the same number in rapid sequence from several calls on
the same hit.
>I have not been able to do either. I get the same number back several times
>from PHP's mt_rand() and from mysql's RAND().
>any ideas?
When PHP starts up, the seed gets initialized to <SOMETHING>,
possibly based on microtime(), but I really don't care. Apache/PHP
don't get restarted very often. With a good host, it could easily
be less than once a month. However, once PHP starts, it's fixed.
It is likely that if Apache fork()s for a given hit, the seed stays
initialized to <SOMETHING> unless you explicitly set it. Any changes
to that by more calls to get pseudo-random numbers are discarded
when that instance of Apache exits. To get different values, you
need to explicitly set the seed to a function of something other
than just microtime().
Things to use for a seed (jumble them all together, as in concatenate,
then take md5 of result, then convert some of md5 result to integer):
microtime()
getmypid()
$_SERVER['UNIQUE_ID'] (Apache only, and may need a module turned on)
$_SERVER['REMOTE_ADDR']
$_SERVER['REMOTE_PORT']
Actually, using just the first two should be sufficient, as the
pair (microtime(), getmypid()) should be unique. However, to get
more entropy, throw in some of the others.
If you are using pseudo-random numbers to select one of 100 images,
expect the same image twice in a row about 1% of the time, unless
you have code to deal with this. My suggestion is to not attempt
to avoid this.
>I suppose I could use the current rancom number as the seed for the next
>random number. but would that really work?
It's a very BAD idea to seed a pseudo-random number generator
multiple times in the same run. Using the output of the random
number generator as a new seed is also not a good idea. It's very
easy to cripple a good pseudo-random number generator with a poor
method of choosing a seed. The problem you're having with microtime()
demonstrates this. Seed once. Use a good source of (pseudo-)randomness.
microtime() alone doesn't qualify if you require rapid-fire results.
Gordon L. Burditt
Navigation:
[Reply to this message]
|