Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/numeric/random"

From cppreference.com
< cpp‎ | numeric
m (Predefined random number generators: reorder per [rand.synopsis].)
 
(24 intermediate revisions by 12 users not shown)
Line 2: Line 2:
 
{{cpp/numeric/random/navbar}}
 
{{cpp/numeric/random/navbar}}
  
The random number library provides classes that generate random and pseudo-random numbers. These classes include:
+
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. {{rl|uniform int distribution|uniform}}, {{rl|normal distribution|normal}}, or {{rl|poisson distribution}}s) which convert the output of URBGs into various statistical distributions.
  
* Random number engines (both pseudo-random number generators, which generate integer sequences with a uniform distribution, and true random number generators if available)
+
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.
* Random number distributions (e.g. [[cpp/numeric/random/uniform_int_distribution|uniform]], [[cpp/numeric/random/normal_distribution|normal]], or [[cpp/numeric/random/poisson_distribution|poisson distributions]]) which convert the output of random number engines into various statistical distributions
+
  
Engines and distributions are designed to be used together to produce random values. All of the engines may be specifically seeded, serialized, and deserialized for use with repeatable simulators.
+
===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 {{named req|UniformRandomBitGenerator}} requirements.
 +
C++20 also defines a {{lconcept|uniform_random_bit_generator}} concept.
 +
 
 +
{{dsc begin}}
 +
{{dsc header|random}}
 +
{{dsc inc|cpp/numeric/random/dsc uniform_random_bit_generator}}
 +
{{dsc end}}
  
 
===Random number engines===
 
===Random number engines===
 +
A ''random number engine'' (commonly shortened to ''engine''{{sep}}) is a uniform random bit generator which generates pseudo-random numbers using seed data as entropy source.
  
Random number engines generate pseudo-random numbers using seed data as entropy source. Several different classes of pseudo-random number generation algorithms are implemented as templates that can be customized.
+
At any given time, an engine {{c|e}} of type {{tt|E}} has a state {{box|e{{su|b={{tt|i}}}}}} for some non-negative integer {{c|i}}. Upon construction, {{c|e}} has an initial state {{box|e{{su|b={{tt|0}}}}}}, which is determined by engine parameters and an initial seed (or seed sequence).
  
The choice of which engine to use involves a number of tradeoffs: the linear congruential engine is moderately fast and has a very small storage requirement for state.  The lagged Fibonacci generators are very fast even on processors without advanced arithmetic instruction sets, at the expense of greater state storage and sometimes less desirable spectral characteristics. The Mersenne twister 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 following properties are always defined for any engine type {{tt|E}}:
 +
* The ''size'' of {{tt|E}}’s state in multiples of the size of {{tt|E::result_type}} (i.e. {{box|{{c/core|(sizeof e}}{{su|b={{tt|i}}}}{{c/core|) / sizeof(E::result_type)}}}}).
 +
* The ''transition algorithm'' {{c|TA}} by which {{c|e}}’s state {{box|e{{su|b={{tt|i}}}}}} is advanced to its successor state {{box|e{{su|b={{tt|i+1}}}}}} (i.e. {{box|{{c/core|TA(e}}{{su|b={{tt|i}}}}{{c/core|1=) == e}}{{su|b={{tt|i+1}}}}}}).
 +
* The ''generation algorithm'' {{c|GA}} by which {{c|e}}’s state is mapped to a value of type {{tt|E::result_type}}, the result is a pseudo-random number.
  
Random number engines satisfy {{concept|UniformRandomBitGenerator}}
+
A pseudo-random number sequence can be generated by calling {{c|TA}} and {{c|GA}} alternatively.
  
{{dsc begin}}
+
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:
{{dsc header | random}}
+
* The {{rl|linear congruential engine}} is moderately fast and has a very small storage requirement for state.
{{dsc tclass | cpp/numeric/random/linear_congruential_engine | implements [[enwiki:Linear_congruential_generator | linear congruential]] algorithm | notes={{mark c++11}}}}
+
* The {{rl|mersenne twister engine|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).
{{dsc tclass | cpp/numeric/random/mersenne_twister_engine | implements [[enwiki:Mersenne_twister | Mersenne twister]] algorithm | notes={{mark c++11}}}}
+
* The {{rl|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.
{{dsc tclass | cpp/numeric/random/subtract_with_carry_engine | implements subtract with carry (a [[enwiki:Lagged_Fibonacci_generator | lagged Fibonacci]]) algorithm | notes={{mark c++11}}}}
+
{{rrev|since=c++26|
{{dsc end}}
+
* The {{rl|philox engine|Philox engine}} is a {{enwiki|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.
 +
}}
  
====Random number engine adaptors====
+
None of these random number engines are {{enwiki|Cryptographically secure pseudorandom number generator|cryptographically secure}}. As with any secure operation, a crypto library should be used for the purpose (e.g. [https://www.openssl.org/docs/manmaster/man3/RAND_bytes.html OpenSSL {{tt|RAND_bytes}}]).
  
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.
+
All types instantiated from these templates meet the {{named req|RandomNumberEngine}} requirements.
  
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc header | random}}
+
{{dsc header|random}}
{{dsc tclass | cpp/numeric/random/discard_block_engine | discards some output of a random number engine | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc linear_congruential_engine}}
{{dsc tclass | cpp/numeric/random/independent_bits_engine | packs the output of a random number engine into blocks of specified number of bits | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc mersenne_twister_engine}}
{{dsc tclass | cpp/numeric/random/shuffle_order_engine | delivers the output of a random number engine in different order | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc subtract_with_carry_engine}}
 +
{{dsc inc|cpp/numeric/random/dsc philox_engine}}
 
{{dsc end}}
 
{{dsc end}}
  
====Predefined random number generators====
+
===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.
  
 +
{{dsc begin}}
 +
{{dsc header|random}}
 +
{{dsc inc|cpp/numeric/random/dsc discard_block_engine}}
 +
{{dsc inc|cpp/numeric/random/dsc independent_bits_engine}}
 +
{{dsc inc|cpp/numeric/random/dsc shuffle_order_engine}}
 +
{{dsc end}}
 +
 +
===Predefined random number generators===
 
Several specific popular algorithms are predefined.
 
Several specific popular algorithms are predefined.
  
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc header | random}}
+
{{dsc header|random}}
{{dsc hitem | Type | Definition}}
+
{{dsc hitem|Type|Definition}}
{{dsc inc | cpp/numeric/random/dsc minstd_rand0}}
+
{{dsc inc|cpp/numeric/random/dsc minstd_rand0}}
{{dsc inc | cpp/numeric/random/dsc minstd_rand}}
+
{{dsc inc|cpp/numeric/random/dsc minstd_rand}}
{{dsc inc | cpp/numeric/random/dsc mt19937}}
+
{{dsc inc|cpp/numeric/random/dsc mt19937}}
{{dsc inc | cpp/numeric/random/dsc mt19937_64}}
+
{{dsc inc|cpp/numeric/random/dsc mt19937_64}}
{{dsc inc | cpp/numeric/random/dsc ranlux24_base}}
+
{{dsc inc|cpp/numeric/random/dsc ranlux24_base}}
{{dsc inc | cpp/numeric/random/dsc ranlux48_base}}
+
{{dsc inc|cpp/numeric/random/dsc ranlux48_base}}
{{dsc inc | cpp/numeric/random/dsc ranlux24}}
+
{{dsc inc|cpp/numeric/random/dsc ranlux24}}
{{dsc inc | cpp/numeric/random/dsc ranlux48}}
+
{{dsc inc|cpp/numeric/random/dsc ranlux48}}
{{dsc inc | cpp/numeric/random/dsc knuth_b}}
+
{{dsc inc|cpp/numeric/random/dsc knuth_b}}
{{dsc | {{tt|default_random_engine}} | ''implementation-defined''}}
+
{{dsc inc|cpp/numeric/random/dsc philox4x32}}
 +
{{dsc inc|cpp/numeric/random/dsc philox4x64}}
 +
{{dsc|{{tt|default_random_engine}} {{mark c++11}}|''implementation-defined''}}
 
{{dsc end}}
 
{{dsc end}}
  
====Non-deterministic random numbers====
+
===Non-deterministic random numbers===
 
+
{{lc|std::random_device}} is a non-deterministic uniform random bit generator, although implementations are allowed to implement {{lc|std::random_device}} using a pseudo-random number engine if there is no support for non-deterministic random number generation.
{{lc|std::random_device}} is a non-deterministic uniform random number generator, although implementations are allowed to implement {{lc|std::random_device}} using a pseudo-random number engine if there is no support for non-deterministic random number generation.
+
  
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/numeric/random/dsc random_device}}
+
{{dsc inc|cpp/numeric/random/dsc random_device}}
 
{{dsc end}}
 
{{dsc end}}
  
 
===Random number distributions===
 
===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.
  
A random number distribution post-processes the output of an random number engine in such a way that resulting output is distributed according to a defined statistical probability density function.
+
Random number distributions satisfy {{named req|RandomNumberDistribution}}.
 
+
Random number distributions satisfy {{concept|RandomNumberDistribution}}
+
  
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc header | random}}
+
{{dsc header|random}}
{{dsc sep}}
+
{{dsc h2 | Uniform distributions}}
+
{{dsc inc | cpp/numeric/random/dsc uniform_int_distribution}}
+
{{dsc inc | cpp/numeric/random/dsc uniform_real_distribution}}
+
  
{{dsc h2 | Bernoulli distributions}}
+
{{dsc h2|Uniform distributions}}
{{dsc class | cpp/numeric/random/bernoulli_distribution | produces {{c|bool}} values on a [[enwiki:Bernoulli_distribution | Bernoulli distribution]]. | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc uniform_int_distribution}}
{{dsc tclass | cpp/numeric/random/binomial_distribution | produces integer values on a  [[enwiki:Binomial_distribution | binomial distribution]].  | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc uniform_real_distribution}}
{{dsc tclass | cpp/numeric/random/negative_binomial_distribution | produces integer values on a  [[enwiki:Negative_binomial_distribution | negative binomial distribution]].  | notes={{mark c++11}}}}
+
{{dsc tclass | cpp/numeric/random/geometric_distribution | produces integer values on a  [[enwiki:Geometric_distribution | geometric distribution]].  | notes={{mark c++11}}}}
+
  
{{dsc h2 | Poisson distributions}}
+
{{dsc h2|Bernoulli distributions}}
{{dsc tclass | cpp/numeric/random/poisson_distribution | produces integer values on a  [[enwiki:Poisson_distribution | poisson distribution]]. | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc bernoulli_distribution}}
{{dsc tclass | cpp/numeric/random/exponential_distribution | produces real values on an  [[enwiki:Exponential_distribution | exponential distribution]]. | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc binomial_distribution}}
{{dsc tclass | cpp/numeric/random/gamma_distribution | produces real values on an  [[enwiki:Gamma_distribution | gamma distribution]]. | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc negative_binomial_distribution}}
{{dsc tclass | cpp/numeric/random/weibull_distribution |produces real values on a  [[enwiki:Weibull_distribution | Weibull distribution]]. | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc geometric_distribution}}
{{dsc tclass | cpp/numeric/random/extreme_value_distribution | produces real values on an  [[enwiki:Generalized_extreme_value_distribution | extreme value distribution]]. | notes={{mark c++11}}}}
+
  
{{dsc h2 | Normal distributions}}
+
{{dsc h2|Poisson distributions}}
{{dsc tclass | cpp/numeric/random/normal_distribution | produces real values on a  [[enwiki:Normal_distribution | standard normal (Gaussian) distribution]]. | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc poisson_distribution}}
{{dsc tclass | cpp/numeric/random/lognormal_distribution | produces real values on a  [[enwiki:Lognormal_distribution | lognormal distribution]]. | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc exponential_distribution}}
{{dsc tclass | cpp/numeric/random/chi_squared_distribution | produces real values on a  [[enwiki:Chi-squared_distribution | chi-squared distribution]].  | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc gamma_distribution}}
{{dsc tclass | cpp/numeric/random/cauchy_distribution | produces real values on a  [[enwiki:Cauchy_distribution | Cauchy distribution]]. | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc weibull_distribution}}
{{dsc tclass | cpp/numeric/random/fisher_f_distribution | produces real values on a  [[enwiki:F-distribution | Fisher's F-distribution]]. | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc extreme_value_distribution}}
{{dsc tclass | cpp/numeric/random/student_t_distribution | produces real values on a  [[enwiki:Student's t-distribution | Student's t-distribution]]. | notes={{mark c++11}}}}
+
  
{{dsc h2 | Sampling distributions}}
+
{{dsc h2|Normal distributions}}
{{dsc tclass | cpp/numeric/random/discrete_distribution | produces random integers on a discrete distribution. | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc normal_distribution}}
{{dsc tclass | cpp/numeric/random/piecewise_constant_distribution | produces real values distributed on constant subintervals.| notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc lognormal_distribution}}
{{dsc tclass | cpp/numeric/random/piecewise_linear_distribution | produces real values distributed on defined subintervals. | notes={{mark c++11}}}}
+
{{dsc inc|cpp/numeric/random/dsc chi_squared_distribution}}
 +
{{dsc inc|cpp/numeric/random/dsc cauchy_distribution}}
 +
{{dsc inc|cpp/numeric/random/dsc fisher_f_distribution}}
 +
{{dsc inc|cpp/numeric/random/dsc student_t_distribution}}
 +
 
 +
{{dsc h2|Sampling distributions}}
 +
{{dsc inc|cpp/numeric/random/dsc discrete_distribution}}
 +
{{dsc inc|cpp/numeric/random/dsc piecewise_constant_distribution}}
 +
{{dsc inc|cpp/numeric/random/dsc piecewise_linear_distribution}}
 
{{dsc end}}
 
{{dsc end}}
  
 
===Utilities===
 
===Utilities===
 +
{{dsc begin}}
 +
{{dsc header|random}}
 +
{{dsc inc|cpp/numeric/random/dsc generate_canonical}}
 +
{{dsc inc|cpp/numeric/random/dsc seed_seq}}
 +
{{dsc end}}
  
 +
===Random number algorithms===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc header | random}}
+
{{dsc header|random}}
{{dsc inc | cpp/numeric/random/dsc generate_canonical}}
+
{{dsc inc|cpp/algorithm/ranges/dsc generate_random}}
{{dsc class | cpp/numeric/random/seed_seq | general-purpose bias-eliminating scrambled seed sequence generator | notes={{mark c++11}}}}
+
 
{{dsc end}}
 
{{dsc end}}
  
 
===C random library===
 
===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:
 
In addition to the engines and distributions described above, the functions and constants from the C random library are also available though not recommended:
  
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc header | cstdlib}}
+
{{dsc header|cstdlib}}
{{dsc inc | cpp/numeric/random/dsc rand}}
+
{{dsc inc|cpp/numeric/random/dsc rand}}
{{dsc inc | cpp/numeric/random/dsc srand}}
+
{{dsc inc|cpp/numeric/random/dsc srand}}
{{dsc inc | cpp/numeric/random/dsc RAND_MAX}}
+
{{dsc inc|cpp/numeric/random/dsc RAND_MAX}}
 
{{dsc end}}
 
{{dsc end}}
  
 
===Example===
 
===Example===
 
{{example
 
{{example
| p=true
+
|code=
| code=
+
#include <cmath>
#include <iostream>
+
 
#include <iomanip>
 
#include <iomanip>
#include <string>
+
#include <iostream>
 
#include <map>
 
#include <map>
 
#include <random>
 
#include <random>
#include <cmath>
+
#include <string>
  
 
int main()
 
int main()
Line 136: Line 164:
 
     // Seed with a real random value, if available
 
     // Seed with a real random value, if available
 
     std::random_device r;
 
     std::random_device r;
 
+
   
 
     // Choose a random mean between 1 and 6
 
     // Choose a random mean between 1 and 6
 
     std::default_random_engine e1(r());
 
     std::default_random_engine e1(r());
Line 142: Line 170:
 
     int mean = uniform_dist(e1);
 
     int mean = uniform_dist(e1);
 
     std::cout << "Randomly-chosen mean: " << mean << '\n';
 
     std::cout << "Randomly-chosen mean: " << mean << '\n';
 
+
   
 
     // Generate a normal distribution around that mean
 
     // Generate a normal distribution around that mean
     std::seed_seq seed2{r(), r(), r(), r(), r(), r(), r(), r()};  
+
     std::seed_seq seed2{r(), r(), r(), r(), r(), r(), r(), r()};
 
     std::mt19937 e2(seed2);
 
     std::mt19937 e2(seed2);
 
     std::normal_distribution<> normal_dist(mean, 2);
 
     std::normal_distribution<> normal_dist(mean, 2);
+
   
 
     std::map<int, int> hist;
 
     std::map<int, int> hist;
     for (int n = 0; n < 10000; ++n) {
+
     for (int n = 0; n != 10000; ++n)
 
         ++hist[std::round(normal_dist(e2))];
 
         ++hist[std::round(normal_dist(e2))];
     }
+
      
     std::cout << "Normal distribution around " << mean << ":\n";
+
     std::cout << "Normal distribution around " << mean << ":\n"
    for (auto p : hist) {
+
              << std::fixed << std::setprecision(1);
        std::cout << std::fixed << std::setprecision(1) << std::setw(2)
+
    for (auto [x, y] : hist)
                  << p.first << ' ' << std::string(p.second/200, '*') << '\n';
+
        std::cout << std::setw(2) << x << ' ' << std::string(y / 200, '*') << '\n';
    }
+
 
}
 
}
| output=
+
|p=true
 +
|output=
 
Randomly-chosen mean: 4
 
Randomly-chosen mean: 4
 
Normal distribution around 4:
 
Normal distribution around 4:
-4  
+
-4
-3  
+
-3
-2  
+
-2
-1  
+
-1
 
  0 *
 
  0 *
 
  1 ***
 
  1 ***
Line 174: Line 202:
 
  7 ***
 
  7 ***
 
  8 *
 
  8 *
  9  
+
  9
10  
+
10
11  
+
11
12  
+
12
 
}}
 
}}
  
 
===See also===
 
===See also===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc see c | c/numeric/random | Pseudo-random number generation}}
+
{{dsc see c|c/numeric/random|Pseudo-random number generation|nomono=true}}
 
{{dsc end}}
 
{{dsc end}}
  
[[de:cpp/numeric/random]]
+
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}
[[es:cpp/numeric/random]]
+
[[fr:cpp/numeric/random]]
+
[[it:cpp/numeric/random]]
+
[[ja:cpp/numeric/random]]
+
[[pt:cpp/numeric/random]]
+
[[ru:cpp/numeric/random]]
+
[[zh:cpp/numeric/random]]
+

Latest revision as of 11:40, 30 August 2024

 
 
 
 

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.

Defined in header <random>
specifies that a type qualifies as a uniform random bit generator
(concept) [edit]

[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 of E::result_type (i.e. (sizeof ei) / sizeof(E::result_type)).
  • The transition algorithm TA by which e’s state ei 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.
(since C++26)

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.

Defined in header <random>
implements linear congruential algorithm
(class template) [edit]
implements Mersenne twister algorithm
(class template) [edit]
implements a subtract-with-carry (lagged Fibonacci) algorithm
(class template) [edit]
a counter-based parallelizable generator
(class template) [edit]

[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.

Defined in header <random>
discards some output of a random number engine
(class template) [edit]
packs the output of a random number engine into blocks of a specified number of bits
(class template) [edit]
delivers the output of a random number engine in a different order
(class template) [edit]

[edit] Predefined random number generators

Several specific popular algorithms are predefined.

Defined in header <random>
Type Definition
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_base (C++11) std::subtract_with_carry_engine<std::uint_fast32_t, 24, 10, 24>[edit]
ranlux48_base (C++11) std::subtract_with_carry_engine<std::uint_fast64_t, 48, 5, 12>[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]

knuth_b (C++11) std::shuffle_order_engine<std::minstd_rand0, 256>[edit]
philox4x32 (C++26) std::philox_engine<std::uint_fast32_t, 32, 4, 10,
                   0xD2511F53, 0x9E3779B9,
                   0xCD9E8D57, 0xBB67AE85>[edit]
philox4x64 (C++26) std::philox_engine<std::uint_fast64_t, 64, 4, 10,
                   0xD2E7470EE14C6C93, 0x9E3779B97F4A7C15,
                   0xCA5A826395121157, 0xBB67AE8584CAA73B>[edit]
default_random_engine (C++11) implementation-defined

[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.

non-deterministic random number generator using hardware entropy source
(class) [edit]

[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.

Defined in header <random>
Uniform distributions
produces integer values evenly distributed across a range
(class template) [edit]
produces real values evenly distributed across a range
(class template) [edit]
Bernoulli distributions
produces bool values on a Bernoulli distribution
(class) [edit]
produces integer values on a binomial distribution
(class template) [edit]
produces integer values on a negative binomial distribution
(class template) [edit]
produces integer values on a geometric distribution
(class template) [edit]
Poisson distributions
produces integer values on a Poisson distribution
(class template) [edit]
produces real values on an exponential distribution
(class template) [edit]
produces real values on a gamma distribution
(class template) [edit]
produces real values on a Weibull distribution
(class template) [edit]
produces real values on an extreme value distribution
(class template) [edit]
Normal distributions
produces real values on a standard normal (Gaussian) distribution
(class template) [edit]
produces real values on a lognormal distribution
(class template) [edit]
produces real values on a chi-squared distribution
(class template) [edit]
produces real values on a Cauchy distribution
(class template) [edit]
produces real values on a Fisher's F-distribution
(class template) [edit]
produces real values on a Student's t-distribution
(class template) [edit]
Sampling distributions
produces random integers on a discrete distribution
(class template) [edit]
produces real values distributed on constant subintervals
(class template) [edit]
produces real values distributed on defined subintervals
(class template) [edit]

[edit] Utilities

Defined in header <random>
evenly distributes real values of given precision across [01)
(function template) [edit]
(C++11)
general-purpose bias-eliminating scrambled seed sequence generator
(class) [edit]

[edit] Random number algorithms

Defined in header <random>
fills a range with random numbers from a uniform random bit generator
(niebloid)[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:

Defined in header <cstdlib>
generates a pseudo-random number
(function) [edit]
seeds pseudo-random number generator
(function) [edit]
maximum possible value generated by std::rand
(macro constant) [edit]

[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

[edit] See also

C documentation for Pseudo-random number generation