Tech

Random Number Generation–Functions–STRUCTURED PROGRAMMING Course Notes

Random Number Generation

rand();

  • a C++ Standard Library function that generates an unsigned integer between 0 and RAND_MAX (a symbolic constant defined in the <cstdlib> header file). The function prototype for the ‘rand’ function is in <cstdlib>.

rand()%6

  • to produce integers specifically in the range 0 to 5, for a dice-rolling game, for example, we use the modulus operator(%).
  • This is called scaling. The number 6 is called the “scaling factor”.
  • We would then shift the range of numbers produced by adding 1 to our previous result.
  • ex: (1 + rand() % 6 )

srand()

  • the function ‘srand‘ takes an unsigned integer argument and seeds the ‘rand‘ function to produce a different sequence of random numbers for each execution.
  • Function ‘srand‘ takes an unsigned int value as an argument. The function prototype for the srand function is in the header file <cstdlib>.
  • To randomize without having to enter a seed each time, we may use a statement like:
    • srand ( time(0) );
    • This causes the computer to read its clock to obtain the value for the seed. Function ‘time’ (with the argument ‘0’) typically returns the current time as the number of seconds since January 1, 1970 at midnight Greenwich Mean Time (GMT). The function prototype for ‘time’ is in <ctime>.

Generalized Scaling & Shifting of Random Numbers

Earlier we learned how to write a single statement to simulate the rolling of a six-sided die with the statement:

face = 1 + rand() %6;

…which always assigns an integer (at random) to variable ‘face’ in the range 1 <= face <= 6.

Th width of this range (i.e., the number of consecutive integers in the range) is 6 and the starting number in the range is 1. Referring to the previous statement, we see that the width of the range is determined by the number used to scale ‘rand‘ with the modulus operator (i.e., 6), and the starting number of the range is equal to the number (i.e., 1) that is added to the expression rand%6.

We can generalize this result as:

number = shiftingValue + rand() % scalingFactor;

…where ‘shiftingValue‘ is equal to the first number in the desired range of consecutive integers and ‘scalingFactor’ is equal to the width of the desired range of consecutive integers.