Miesho
Miesho

Reputation: 13

std::random - On Windows always I get the same numbers

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.

Upvotes: 1

Views: 719

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51845

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;
}

Upvotes: 2

Related Questions