Executing the program of Fig. 6.7 again produces
6 6 5 5 6
5 1 1 5 3
6 6 2 4 2
6 2 3 4 1
The program prints exactly the same sequence of values shown in Fig. 6.7. How can these be random numbers? When debugging a simulation program, this repeatability is essential for proving that corrections to the program work properly.
Function rand
actually generates pseudorandom numbers. Repeatedly calling rand
produces a sequence of numbers that appears to be random. However, the sequence repeats itself each time the program executes. Once a program has been thoroughly debugged, it can be conditioned to produce a different sequence of random numbers for each execution. This is called randomizing and is accomplished with the C++ Standard Library function srand. Function srand
takes an unsigned
integer argument and seeds the rand
function to produce a different sequence of random numbers for each execution. C++11 provides additional random number capabilities that can produce nondeterministic random numbers—a set of random numbers that can’t be predicted. Such random number generators are used in simulations and security scenarios where predictability is undesirable. Section 6.8 introduces C++11 random-number generation capabilities.