CSE 202: Computer Science II, Winter 2018
Random number generation

C++ inherits the PRNG (Psuedorandom number generator) utilities provided by the C standard library, they are found in the <cstdlib> header. They are:

Expression Meaning
std::srand(x) "Seeds" the pseudo-random number generator with integer value x
std::rand() Produces the next int value (from 0 to RAND_MAX) in the psuedo-random number sequence based on the initial value provided to std::srand.

Here is a simple program that generates 5 pseudo-random integers:

#include <iostream> int main() { for (int i = 0; i < 5; ++i) { std::cout << std::rand() << endl; } return 0; }

The problem with this program is that it displays the same 5 integers on every run. To get a different sequence of integers, the function std::srand should be invoked with some initial integer value which is called the "seed". Inserting a statement such as std::srand(123); at the beginning of main will result in a different generated sequence from std::rand.

However, even with a different seed value, the program will still display the same numbers on successive runs. To get a different sequence of numbers from the last program run, std::srand needs a different value on each run. A common practice is to seed the PRNG with the current time returned from std::time:

#include <iostream> #include <ctime> #include <cstdlib> int main() { std::srand(std::time(0)); for (int i = 0; i < 5; ++i) { std::cout << std::rand() << endl; } return 0; }

Now the generated values are seemingly random and different on each program run under the condition that the program is not ran more than once per second. If you run this program twice or more in the same second, you get the same sequence of values multiple times.

std::srand and std::rand, while useful, are obsolete compared to the PRNG utilities in C++11.

Random number generation with C++11

C++11 introduces a robust prng library in <random>, it allows you to generate random numbers, including fractional numbers, distributed uniformly or over some statistical probability function. Here is a C++11 program that generates 5 random double values between 0.0 and 100.0 over a uniform distribution:

#include <iostream> #incldue <random> int main() { std::random_device rd; std::default_random_engine re(rd()); std::uniform_real_distribution<double> rdist(0.0, 100.0); for (int i = 0; i < 5; ++i) std::cout << rdist(re) << endl; return 0; }

To compile this program, random.cpp, with GCC use the following command:

g++ -std=c++11 random.cpp

You are encouraged to try out C++11 features, but you won't be required to in this course.