Search code examples
c++c++11mersenne-twister

How to run Mersenne Twister inside a function?


I have a short piece of code which runs the Mersenne Twister PRNG and it works great:

std::random_device randDev;
std::mt19937 twister(randDev());
std::uniform_int_distribution<int> dist(0,99);

for (int i = 0; i < 10; i++) {
    std::cout << dist(twister) << std::endl;
}

It outputs ten random numbers. However if I put the exact same code into a function:

#include <random>

int getRand(const int& A, const int& B) {
    std::random_device randDev;
    std::mt19937 twister(randDev());
    std::uniform_int_distribution<int> dist(A,B);

    return dist(twister);
}

int main() {
    for (int i = 0; i < 10; i++) {
        std::cout << getRand(0,99) << std::endl;
    }

    return 0;
}

It outputs the same number ten times. I'm just starting out with C++ so I have no idea what causes this or how to go about fixing the problem.

EDIT: The problem lies with std::random_device. It could be a bug in Eclipse C++ IDE (Luna version) or MinGW 4.8.1 but for whatever reason that random number is always the same. I believe time(0) will be a suitable seed for my uses.

EDIT 2: Taking T.C.'s suggestion into account and the fact that time(0) still results in ten of the same number, here's the final code so far. I know rand() is bad but it works.

#include <iostream>
#include <random>

std::mt19937 twister(rand());

int getRand(const int& A, const int& B) {
    std::uniform_int_distribution<int> dist(A,B);

    return dist(twister);
}

int main() {
    for (int i = 0; i < 10; i++) {
        std::cout << getRand(0,99) << std::endl;
    }

    return 0;
}

Solution

  • What compiler and OS do you use? Visual Studio 2012 (not sure about 2013) didn't have a real implementation of std::random_device, which means that it was initialized with same value each time - so in such case you would have mersenne twister initialized with same seed each time, thus same result.

    And by the way, seems that same question was asked in:

    Why do I get the same sequence for every run with std::random_device with mingw gcc4.8.1?

    so apparently GCC4.8 on Windows also has std::random_device implemented as pseudo-random.