|
Tutorial 8
Generating Random numbers
Functions demonstrated
- <?srand(integer)>
<?$number = rand()>
<?$number = getrandmax()>
See the man pages for the srand() and rand() C library functions for more information.
Note that these functions are not very good random number generators, but they should be
adequate for most purposes.
The first thing to do is to seed the random number generator. Do this with the
srand()
function. This function takes any integer as an argument. One choice is to use the
date
function to give you the current number of seconds past the minute. ie.
<?srand(date("s"))>
Now you can generate random numbers by simply calling the rand() function. ie.
<?$number = rand()>
You can use the getmaxrand() function to check what the maximum possible number is on your
system. You can also adjust the range of possible random values by using the mod operator.
ie.
<?$number = rand() % 100>
This would always produce a random number between 0 and 100.
Random number between 0 and 2147483646: 206527624
Random number between 0 and 99: 33
Random number between 50 and 59: 52
You may reload this page many times to verify that the generated random numbers are
within the specified ranges. Note that the ranges include both endpoints.
|