Random numbers

Most computer programs do the same thing every time they are executed, so they are said to be deterministic. Usually, determinism is a good thing, since we expect the same calculation to yield the same result. For some applications, though, we would like the computer to be unpredictable. Games are an obvious example.

Making a program truly nondeterministic turns out to be not so easy, but there are ways to make it at least seem that way. One of them is to generate “pseudorandom” numbers and use them to determine the outcome of the program. Pseudorandom numbers are not truly random in the mathematical sense, but for our purposes, they will do.

C++ provides a function called uniform_int_distribution that returns a pseudorandomly generated integer value uniformly distributed within the range you specify. It is declared in the header file random, which is another part of the standard library.

To see a sample, run this loop:

Take a look at the active code below, which generates 4 random numbers.

Notice there is a lot going on in this small program.

  1. Before we create a random number, we have to create a random number generator engine.

    The engine is the object that actually does all the hard work.

    The C++ standard library provides many options and variations for pseudorandom engines, since it is such an important topic.

    But for most simple purposes, the default way is good enough.

  2. The uniform_int_distribution object needs 3 pieces of information:

    • <int> - the type of the random value to return

    • {0, 10000} - the range of values (inclusive) to select from

    • (gen) - the engine to use

You have attempted of activities on this page