Random Numbers

Random numbers are useful in programs that need to simulate random events, such as games, simulations and experimentations. In practice no functions produce truly random data -- they produce pseudo-random numbers. These are computed form a given formula (different generators use different formulae) and the number sequences they produce are repeatable. A seed is usually set from which the sequence is generated. Therefore is you set the same seed all the time the same set will be be computed.

One common technique to introduce further randomness into a random number generator is to use the time of the day to set the seed, as this will always be changing. There are many (pseudo) random number functions in the standard library. They all operate on the same basic idea but generate different number sequences (based on different generator functions) over different number ranges.

The simplest set of functions is following:

·       srand() is used to set the seed once. A simple example of using the time of the day to initiate a seed is via a call like what you see in the program below.

·       rand() returns successive pseudo-random numbers in the range from 0 to (2^15)-1.

The following program illustrates the use of these functions to generate random numbers:

#include <ctime>  // For using the time type

#include <iostream>

using namespace std;

 

void main()

{

        //*******************************************************

        //Seed the random number generator with the current time

        // of day if we haven't done so yet.

        //Do this one time in the beginning of the main function

        //*******************************************************

        srand( (unsigned int)time( NULL ) );

 

 

        //*******************************************************

        //Now you can call rand( ) anytime to get a random number.

        // and then use the % operator to get a number in the range you want.

        //*******************************************************

        cout <<"\n   Test 1: 15 random numbers ranging from "

     << " [0, (2 to the 15 th power) -1].\n";

        for (int i=0; i<15; i++)

               cout << rand() << endl;

       

        cout <<"\n   Test 2: 15 random numbers, ranging from 0 to 99 \n";

        for (int i=0; i<15; i++)

               cout << rand()%100 << endl;

 

        cout <<"\n   Test 3: 15 random numbers, ranging from 0 to 999 \n";

        for (int i=0; i<15; i++)

               cout << rand()%1000 << endl;

 

        cout <<"\n   Test 4: 15 random numbers, ranging from 0 to 9999 \n";

        for (int i=0; i<15; i++)

               cout << rand()%10000 << endl;

}