random number generator functions

The so called “random numbers” generated by the so called “random number generators” are not truly random. They follow a particular algorithm to generate a number.

There are two random number generators (invoked with rand() and mt_rand(), respectively), each has three associated functions:

  • seeding
  • the call
  • retrieve the largest integer that might be returned

mt_rand() is better than rand().

Read the PHP manual to learn how to use the following functions:

Random Number Functions
Function Description
srand() Seeds the random number generator.
rand() If called with no arguments, returns a random number between 0 and RAND_MAX . The function can also be called with two integer arguments to specify the range.
getrandmax() Returns the largest number that may be returned by rand()
mt_srand() Like srand(), except it works with mt_rand().
mt_rand() Like rand(), but better.
mt_getrandmax() Returns the largest number that may be returned by mt_rand().


On some systems you can get random numbers without seeding — Don’t do it that way!

Seeding the generator


mt_srand( (double)microtime() * 1000000 );

This sets the seed of the generator to be the number of microseconds that have elapsed since the last whole second.

The typecast to double is necessary, because microtime() returns a string.

This later code sample is the best way to seed a random number generator. Run it once before using the generator.


About samehramzylabib

See About on https://samehramzylabib.wordpress.com
This entry was posted in Coding, PHP Math and tagged , . Bookmark the permalink.


Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s