Page 1 of 1

Random numbers ... it works, but why like this?

Posted: Thu Feb 26, 2004 5:58 am
by Stryks
Hi all,

Just a simple question really. I got some help with a random number generation function, and the function works well enough, but I would really like to know why it has been made the way it is.

Code: Select all

function _rand_num($min = null, $max = null)
{
   static $seeded;

   if (!$seeded) {
      mt_srand((double)microtime()*1000000);
      $seeded = true;
   }

   if (isset($min) && isset($max)) {
      if ($min >= $max) {
         return $min;
      } else {
         return mt_rand($min, $max);
      }
   } else {
      return mt_rand();
   }
}
In particular, what I dont understand is the whole ...

Code: Select all

static $seeded;

   if (!$seeded) {
... bit.

Isnt it just redundant. Wont $seeded, although static, always be valueless and thus always make seeding necessary.

If not, why. And what is the purpose if it has one.

Thanks. :?

Posted: Thu Feb 26, 2004 6:17 am
by Stryks
Oh, OK ... I get it.

If it is called more than once in a page load, it only stops to seed the number generator the first time around.

Cool 8)

Posted: Thu Feb 26, 2004 6:21 am
by Stryks
Actually, while I'm here.

The manual says that you dont need to call mt_srand anymore as it is automatic. However, if I dont call it beforehand, the number it returns is always the same.

Any reason? Or is it just a new development.

Posted: Thu Feb 26, 2004 6:45 am
by twigletmac
Whether you need to seed should depend on your PHP version - are you using 4.2 or above? - but I've had iffy results and just leave the seeding in to be sure.

Mac

Posted: Thu Feb 26, 2004 7:24 am
by Stryks
Thanks :D