The random number engine of C + + has the following points to note:
1. Random number generator using the same seed will generate random number sequence of the same sequence
2. To make the program generate different random results every time it runs, we can use time(0) to generate a random number seed
3. We must pass the engine itself to the distribution object, because some distributions may need to call the engine several times to get the result
Here are some random distributions:
1. Uniform distribution: (1) generate random integers: uniform_int_distribution < [type] > u [(range]]
(2) generate random decimal: uniform [real] distribution < [type] > u [(range]]
Normal distribution < [type] > n (E, d)
3. Bernoulli distribution: Bernoulli [distribution B [(probability)], returns the bool value, and the probability of returning true is constant, the default is 0.5
Note: these random distributions are included in the header file random
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <random>
#include <vector>
using namespace std;
int main()
{
static default_random_engine e;
// Returns the minimum and maximum values that the engine can generate
cout<<"Min: "<<e.min()<<ends<<"Max: "<<e.max()<<endl;
// time Returns the time in seconds
e.seed(time(0));
static uniform_int_distribution<unsigned> u(0, 9);
cout<<"generate[0,9]The three random integers of are:";
for (size_t i = 0; i < 3; ++i)
cout<<u(e)<<ends;
cout<<endl;
/*
u.min() And u.max() return the minimum and maximum values that u(e) can generate
u.reset() Rebuild the state of u so that subsequent use of u does not depend on the value that u has generated
*/
static uniform_real_distribution<double> r(0, 1);
cout<<"generate[0, 1]The three random decimals of are:";
for (size_t i = 0; i < 3; ++i)
cout<<r(e)<<ends;
cout<<endl;
static normal_distribution<> n(4, 1.5);
cout<<"Statistics of number of normal distribution: "<<endl;
vector<unsigned> vals(9);
for (size_t i = 0; i != 100; ++i){
// cmath Of lround Function to round the value to the nearest integer
unsigned v = lround(n(e));
if (v < vals.size())
++vals[v];
}
for (size_t i = 0; i < vals.size(); ++i)
cout<<i<<":\t"<<vals[i]<<endl;
// Return true The probability of is 0
static bernoulli_distribution b(0);
for (size_t i = 0; i < 3; ++i)
cout<<boolalpha<<b(e)<<noboolalpha<<ends;
cout<<endl;
system("pause");
return 0;
}