lundi 25 mars 2019

Use of random in C++

Are these codes equivalent in terms of "randomness" ?

1)

std::vector<int> counts(20);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 19);

for (int i = 0; i < 10000; ++i) {
    ++counts[dis(gen)];
}

2)

std::vector<int> counts(20);
std::random_device rd;
std::mt19937 gen(rd());

for (int i = 0; i < 10000; ++i) {
    std::uniform_int_distribution<> dis(0, 19);
    ++counts[dis(gen)];
}

3)

std::vector<int> counts(20);
std::random_device rd;

for (int i = 0; i < 10000; ++i) {
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, 19);
    ++counts[dis(gen)];
}

4)

std::vector<int> counts(20);

for (int i = 0; i < 10000; ++i) {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, 19);
    ++counts[dis(gen)];
}

In the documentation of std::random_device, it is says that multiple std::random_device object may generate the same number sequence so the code 4 is bad, isn't it ?

And for the other codes ?

If I need to generate random values for multiple stuffs unrelated, must I need to create differents generators or can I keep the same ? :

1)

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> disInt(0, 10);
std::uniform_float_distribution<> disFloat(0, 1.0f);

// Use for one stuff
disInt(gen);

// Use same gen for another unrelated stuff
disFloat(gen);

2)

std::random_device rd1, rd2;
std::mt19937 gen1(rd1()), gen2(rd2());
std::uniform_int_distribution<> disInt(0, 10);

// Use for one stuff
disInt(gen1);

// Use another gen for another unrelated stuff
disFloat(gen2);




Aucun commentaire:

Enregistrer un commentaire