vendredi 7 août 2020

Random number generation, two different methods?

Does anyone know the differences between the two methods of random number generation used in the following code? My suspicion is the first case may be more computationally expensive because it's getting a new seed from /dev/urandom every time a random number is generated. Also appreciate any comments if I'm generating random numbers correctly in these examples.

I'm confused because uniform_int_distribution specifies template<class URNG> result_type operator()(URNG& g); and in some examples I see the parameter passed to be of the type default_random_engine and other time random_device. This adds confusion to what default_random_engine actually does.

For example, method 1 I have seen:

#include <iostream>
#include <random>
#include <map>
using namespace std;

int main()
{
    random_device rd;
    uniform_int_distribution<int> p{0,9};

    map<int,int> m;
    for (int i=0; i < 100; ++i) {
        m[p(rd)]++;
    }

    for (map<int,int>::iterator it = m.begin();
         it != m.end(); ++it)
        cout << it->first << ", " << it->second << '\n';
    
    return 0;
}

Method 2,

#include <iostream>
#include <random>
#include <map>
using namespace std;

int main()
{
    random_device rd;
    default_random_engine gen(rd());
    uniform_int_distribution<int> p{0,9};

    map<int,int> m;
    for (int i=0; i < 100; ++i) {
        m[p(gen)]++;
    }

    for (map<int,int>::iterator it = m.begin();
         it != m.end(); ++it)
        cout << it->first << ", " << it->second << '\n';
    
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire