(c++11) Random number------C + + programming principles and Practices (advanced)

Source: Internet
Author: User

The random number is both a utility and a mathematical problem, which is highly complex and matches its importance in the real world. Here we only discuss the basic content of random numbers, which can be used for simple testing and simulation. In <random>, the standard library provides a sophisticated way to produce random numbers that adapt to different mathematical distributions. This random number standard library is based on the following two basic concepts:

    • Generator (engine, random number generator): A generator is a function object that can produce a sequence of evenly distributed shaping values.
    • Distribution (distribution): A distribution is a function object, given a sequence of generators produced as input, the distribution can produce a sequence of values according to the corresponding mathematical formula.

For example, the Random_vector () function in http://www.cnblogs.com/goudanli/p/7856623.html. Calling Random_vector (n) yields a matrix object of type matrix<double,1>, which contains n elements, and the element values are random numbers between [0:n].

Vector Random_vector (Index n) {    vector v (n);    Default_random_engine ran{(unsigned int) (time (0) +2)};    Uniform_int_distribution<> ureal{0,max0};    for (Index i = 0; i < n; ++i)    {        V (i) = Ureal (ran);    }     return v;}

The default generator (Default_random_engine) is simple, cost-bottom, and easy to run. For everyday use, it's enough. For more specialized applications, the standard library provides other generators with better randomness and different execution costs. For example, Linear_congurential_engine, Mersenne_twidter_engine, and Random_device.

The two random number generators in std_lib_facilities.h are defined as follows

int randint (int min,int max) {static default_random_engine Ran;return Uniform_int_distribution<>{min,max} (ran);} int randint (int max) {return randint (0,max);}

These functions are often used, and of course there are others, so let's see how the normal distribution is produced:

Auto Gen=bind (normal_distribution<double>{15,4.0},default_random_engine{});

The standard library function in <functional> bind () constructs a function object that, when invoked, invokes its first argument and takes the second argument as the argument for the call. Thus in this example, Gen () returns a normal distribution sequence with a mean value of 15 and a variance of 4.0, using Default_random_engine. Example:

Vector<int>hist (2*15), for (int i=0;i<500;++i) ++hist[int (Round (gen ()))];for (int i=0;i!=hist.size (); ++i) { cout<<i<< ' \ t '; for (int j=0;j!=hist[i];++j) cout<< ' * ';cout<< ' \ n ';}

Complete program:

#include <iostream> #include <random> #include <functional>using namespace Std;auto gen=bind (Normal_ distribution<double>{15,4.0},default_random_engine{}); int main () {vector<int>hist (2*15); for (int i=0;i <500;++i) ++hist[int (Round (gen ()))];for (int i=0;i!=hist.size (); ++i) {cout<<i<< ' \ t '; for (int j=0;j!= HIST[I];++J) cout<< ' * ';cout<< ' \ n ';}

Output:

0       *123       **5       *6 ***7 **********8 *************9 *******************10      * * *      **********************************12      *********************************13      ********      *********************************************************15      *******      **********************************************17      * * * *      *************************************19      *******************      ****************************21      ****************22      ********23      *******24      ****25      **26272829

Normal distributions are often used, and other distributions include bernoulli_distribution,exponential_distribution and chi_distribution. Detailed descriptions can be found in the C + + programming Language. The return value of the integer distribution is the closed interval [A:B], and the return value of the real (floating-point) distribution is the open interval [a:b].

By default, each time the program runs, the generator (except Random_device) produces the same sequence. This is very beneficial for program debugging. If you want the same generator to produce different sequences, we need to set different initial values. This initialization process is called a "seed". For example:

Auto gen1= bind (uniform_int_distribution<>{0,9},                default_random_engine{});    Auto gen2= bind (uniform_int_distribution<>{0,9},                default_random_engine{10});  Auto gen3= bind (uniform_int_distribution<>{0,9},                default_random_engine{5});  

In order to obtain unpredictable sequences, we often use the current time (in nanoseconds) or other similar things as seeds.

Principles and Practice of C + + programming (Advanced article)

(c++11) Random number------C + + programming principles and Practices (advanced)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.