C++ Standard-Library Random Numbers

时间:2022-10-08 17:22:36

Extracted from Section 17.4 Random Numbers, C++ Primer 5th. Ed.

The random-number library generates random numbers through a set of cooperating classes: random-number engines and random-number distribution classes. An engine generates  a sequence of unsigned random numbers. A distribution uses an engine to generate random numbers of a specified type, in a given range, distributed according to a particular probability distribution. A random-number generator means  the combination of a distribution object with an engine.

The random-number engines and random-number distribution are both function-object classes. The random-number engines define a call operator that takes no arguments and returns a random unsigned numbers. We can generate raw random numbers by calling an object of a random-number engine type. The library defines several random-number engines that differ in terms of their performance and quality of randomness. Each compiler designates one of these engines as the defaut_random_engine type. This type is intended to be the engine with the most generally useful properties. The distribution types define a call operator that takes a random-number engine as its argument. The distribution object uses its engine argument to produce random numbers that the distribution object maps to the specified distribution.

A given random-number generator always produces the same sequence of numbers. A function with a local random-number generator should make that generator (both the engine and distribution objects) static. Otherwise, the function will generate the identical sequence on each call.

The fact that a generator returns the same sequence of numbers is helpful during debugging. However, once our program is tested, we often want to cause each run of the program to generate different random results. We do so by providing a seed. A seed is a value that an engine can use to start generating numbers at a new point in its sequnce.

We can seed an engine in one of two ways:

  • provide the seed when creating an engine object
  • call the engine's seed member

Pickintg a good seed, like most things about generating good random numbers, is surprisingly hard. Perhaps the most common approach is to call the system time function. This function, defined in the <ctime> header, returns the number of seconds since a given epoch. The time function takes a single parameter that is a pointer to structure into which to write the time. If that pointer is null, the function just returns the time. Because time returns time as the number of seconds, this seed is useful only for applications that generate the seed at second-level, or longer, intervals.