1

After compilation, the program always returns the same results. Unpredictably, the code works correctly on Linux ...

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distribut(1, 6);

    for (int i=0; i < 10; i++)
    {
        std::cout << distribut(gen) << ' ';
    }

Compiler specification:

❯ g++ --version
g++.exe (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Miesho
  • 13
  • 3
  • `std::random_device` might give the same seed to `std::mt19937`every time, as some implementations are just `return constant;` – Mestkon Jan 19 '21 at 09:49
  • 1
    Have a read of https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85494 _"Anyway, it should be fixed for mingw-w64 in the gcc-9-branch, so for the GCC 9.2 release"_ – Richard Critten Jan 19 '21 at 09:51
  • 1
    Does this answer your question? [Why do I get the same sequence for every run with std::random\_device with mingw gcc4.8.1?](https://stackoverflow.com/questions/18880654/why-do-i-get-the-same-sequence-for-every-run-with-stdrandom-device-with-mingw) – Peter O. Jan 19 '21 at 10:23

1 Answers1

2

The problem here is that the std::random_device object (which you are using to seed your std::mt19937) may produce the same seed, each time (although it doesn't on my Windows 10 + Visual Studio test platform).

From cppreference (bolding mine):

std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence.

Here's a possible solution using the 'classic' call to time(nullptr) as the seed, which also avoids the use of the 'intermediate' std::random_device object to generate that seed (though there will be other options to get that seed):

#include <iostream>
#include <random>
#include <ctime>

int main()
{
    std::mt19937 gen(static_cast<unsigned int>(time(nullptr)));
    std::uniform_int_distribution<> distribut(1, 6);
    for (int i = 0; i < 10; i++) {
        std::cout << distribut(gen) << ' ';
    }
    return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83