Pseudo-random number generation
The random number library provides classes that generate random and pseudo-random numbers. These classes include:
- Uniform random bit generators (URBGs), which include both random number engines, which are pseudo-random number generators that generate integer sequences with a uniform distribution, and true random number generators (if available).
- Random number distributions (e.g. uniform, normal, or poisson distributions) which convert the output of URBGs into various statistical distributions.
URBGs and distributions are designed to be used together to produce random values. All of the random number engines may be specifically seeded, serialized, and de-serialized for use with repeatable simulators.
Contents
[edit] Uniform random bit generators
A uniform random bit generator is a function object returning unsigned integer values such that each value in the range of possible results has (ideally) equal probability of being returned.
All uniform random bit generators meet the UniformRandomBitGenerator requirements.
C++20 also defines a uniform_random_bit_generator
concept.
<random>
[edit] Random number engines
A random number engine (commonly shortened to engine ) is a uniform random bit generator which generates pseudo-random numbers using seed data as entropy source.
At any given time, an engine e of type E
has a state ei
for some non-negative integer i. Upon construction, e has an initial state e0
, which is determined by engine parameters and an initial seed (or seed sequence).
The following properties are always defined for any engine type E
:
- The size of
E
’s state in multiples of the size ofE::result_type
(i.e. (sizeof ei
) / sizeof(E::result_type)). - The transition algorithm TA by which e’s state e
i
is advanced to its successor state ei+1
(i.e. TA(ei
) == ei+1
). - The generation algorithm GA by which e’s state is mapped to a value of type
E::result_type
, the result is a pseudo-random number.
A pseudo-random number sequence can be generated by calling TA and GA alternatively.
The standard library provides the implementations of three different classes of pseudo-random number generation algorithms as class templates, so that the algorithms can be customized. The choice of which engine to use involves a number of trade-offs:
- The linear congruential engine is moderately fast and has a very small storage requirement for state.
- The Mersenne twister engine is slower and has greater state storage requirements but with the right parameters has the longest non-repeating sequence with the most desirable spectral characteristics (for a given definition of desirable).
- The subtract with carry engine is very fast even on processors without advanced arithmetic instruction sets, at the expense of greater state storage and sometimes less desirable spectral characteristics.
- The Philox engine is a counter-based random number generator. It has a small state and a long period (not less than 2^130) and is intended for use in Monte-Carlo simulations which require massively parallel random number generation. It is easily vectorized and parallelized and is implemented in GPU-optimized libraries.
None of these random number engines are cryptographically secure. As with any secure operation, a crypto library should be used for the purpose (e.g. OpenSSL RAND_bytes
).
All types instantiated from these templates meet the RandomNumberEngine requirements.
<random>
[edit] Random number engine adaptors
Random number engine adaptors generate pseudo-random numbers using another random number engine as entropy source. They are generally used to alter the spectral characteristics of the underlying engine.
<random>
(class template) [edit]
[edit] Predefined random number generators
Several specific popular algorithms are predefined.
<random>
minstd_rand0
(C++11)
std::linear_congruential_engine <std::uint_fast32_t,
16807, 0, 2147483647>Discovered in 1969 by Lewis, Goodman and Miller, adopted as "Minimal standard" in 1988 by Park and Miller[edit]
minstd_rand
(C++11)
std::linear_congruential_engine <std::uint_fast32_t,
48271, 0, 2147483647>
Newer "Minimum standard", recommended by Park, Miller, and Stockmeyer in 1993[edit]
mt19937
(C++11)
std::mersenne_twister_engine <std::uint_fast32_t,
32, 624, 397, 31,
0x9908b0df, 11,
0xffffffff, 7,
0x9d2c5680, 15,
0xefc60000, 18, 1812433253>
32-bit Mersenne Twister by Matsumoto and Nishimura, 1998[edit]
mt19937_64
(C++11)
std::mersenne_twister_engine <std::uint_fast64_t,
64, 312, 156, 31,
0xb5026f5aa96619e9, 29,
0x5555555555555555, 17,
0x71d67fffeda60000, 37,
0xfff7eee000000000, 43,
6364136223846793005>
64-bit Mersenne Twister by Matsumoto and Nishimura, 2000[edit]
ranlux24
(C++11)
std::discard_block_engine <std::ranlux24_base, 223, 23>24-bit RANLUX generator by Martin Lüscher and Fred James, 1994[edit]
ranlux48
(C++11)
std::discard_block_engine <std::ranlux48_base, 389, 11>48-bit RANLUX generator by Martin Lüscher and Fred James, 1994[edit]
philox4x32
(C++26)
std::philox_engine <std::uint_fast32_t, 32, 4, 10,
0xCD9E8D57, 0x9E3779B9,
0xD2511F53, 0xBB67AE85>[edit]
philox4x64
(C++26)
std::philox_engine <std::uint_fast64_t, 64, 4, 10,
0xCA5A826395121157, 0x9E3779B97F4A7C15,
0xD2E7470EE14C6C93, 0xBB67AE8584CAA73B>[edit]
[edit] Non-deterministic random numbers
std::random_device is a non-deterministic uniform random bit generator, although implementations are allowed to implement std::random_device using a pseudo-random number engine if there is no support for non-deterministic random number generation.
[edit] Random number distributions
A random number distribution post-processes the output of a URBG in such a way that resulting output is distributed according to a defined statistical probability density function.
Random number distributions satisfy RandomNumberDistribution.
<random>
Uniform distributions
Bernoulli distributions
Poisson distributions
Normal distributions
Sampling distributions
[edit] Utilities
<random>
[
0,
1)
(function template) [edit]
[edit] Random number algorithms
<random>
(algorithm function object)[edit]
[edit] C random library
In addition to the engines and distributions described above, the functions and constants from the C random library are also available though not recommended:
<cstdlib>
[edit] Example
#include <cmath> #include <iomanip> #include <iostream> #include <map> #include <random> #include <string> int main() { // Seed with a real random value, if available std::random_device r; // Choose a random mean between 1 and 6 std::default_random_engine e1(r()); std::uniform_int_distribution <int> uniform_dist(1, 6); int mean = uniform_dist(e1); std::cout << "Randomly-chosen mean: " << mean << '\n'; // Generate a normal distribution around that mean std::seed_seq seed2{r(), r(), r(), r(), r(), r(), r(), r()}; std::mt19937 e2(seed2); std::normal_distribution <> normal_dist(mean, 2); std::map <int, int> hist; for (int n = 0; n != 10000; ++n) ++hist[std::round (normal_dist(e2))]; std::cout << "Normal distribution around " << mean << ":\n" << std::fixed << std::setprecision (1); for (auto [x, y] : hist) std::cout << std::setw (2) << x << ' ' << std::string (y / 200, '*') << '\n'; }
Possible output:
Randomly-chosen mean: 4 Normal distribution around 4: -4 -3 -2 -1 0 * 1 *** 2 ****** 3 ******** 4 ********* 5 ******** 6 ****** 7 *** 8 * 9 10 11 12