lundi 15 janvier 2018

Why does repeatedly running a simple snippet generating pseudo-random numbers always yield the same results?

Code:

#include <fstream>
#include <random>
#include <functional>
using namespace std;

int nmax = 5;
long long amin = -10;
long long amax = 10;

int main()
{
    auto rand_ad = bind(uniform_int_distribution<long long>(amin, amax), default_random_engine(random_device{}()));
    ofstream out("testcase");

        out << nmax << ' ' << rand_ad() << '\n';
        for(int i = 0; i < nmax; i++) {
            out << rand_ad() << (i == nmax-1 ? '\n' : ' ');
        }

    return 0;
}

I run this code repeatedly. Whether I run it manually or by a script the results are always the same. When I inspect the contents of file testcase, it always contains:

5 -8
4 0 -1 3 -3

This perplexes me. To my best understanding, as soon as I write default_random_engine(random_device{}()), I do seed my pseudo-random engine!!, so the results should NOT be the same!

Even more, repeatedly calling this code (only ofstream replaced by cout) on Ideone gives different results: link

If this matters, I'm on Windows, compiling with MinGW.

Is this:

  • My misuse of C++;
  • My PEBKAC wrt the installation of MinGW or calling the program;
  • A Windows peculiarity?



Aucun commentaire:

Enregistrer un commentaire