0

I have been using the following code for random integer generation when developing my projects on Ubuntu GNU/linux.

class RandomInteger {
    std::mt19937 m_gen;
    std::random_device m_rd;

public:
    RandomInteger() { m_gen = std::mt19937(m_rd()); }

    int operator()(int a, int b) {
        std::uniform_int_distribution<> dis{std::min(a, b), std::max(a, b)};
        return dis(m_gen);
    }
};

This generates random numbers when calling operator(). Well at least it's random enough that it seems random. But I was surprised when I compiled the same code in windows, and my program was suddenly acting very deterministically. Turns out this code generates the same numbers every time on windows.

Was I misusing the c++ random number generators all along? Why does it seem random in linux but not in windows? What can I do to make it random on both?

Anonymous Entity
  • 3,254
  • 3
  • 27
  • 41
  • Is `m_rd()` returning the same value every time? – Joseph Mansfield Jan 18 '15 at 13:16
  • 1
    I cannot reproduce this problem with VS2013. What compiler/library implementation are you using? – Andy Prowl Jan 18 '15 at 13:21
  • 1
    I'm genuinely curious how you're using `RandomInteger` (is it repeated instantiated, used, and destroyed or is it instantiated *once* and used from then on?). Also,not that it should matter, but is there a reason you even have `m_rd`, at all ? I would think `RandomInteger() : m_gen(std::random_device{}()) {}` would accomplish the same end-goal. – WhozCraig Jan 18 '15 at 13:24
  • @AndyProwl I am using GNU GCC – Anonymous Entity Jan 18 '15 at 13:27
  • @WhozCraig it's instantiated once per object that needs it (ai component) and then used during the lifetime of that object. – Anonymous Entity Jan 18 '15 at 13:29
  • @JosephMansfield YES – Anonymous Entity Jan 18 '15 at 13:34
  • @AndyProwl I just tried clang, same results.. – Anonymous Entity Jan 18 '15 at 13:35
  • @user11177 wait. did you just say `operator()` from `std::random_device` is returning the same *sequence* (or worse, the same *value* ? Not good... – WhozCraig Jan 18 '15 at 13:37
  • @user11177: Clang on Windows? What version? If you ended up using the same library implementation you use with GCC, then I'm not surprised you obtain the same results. Btw check [this Q&A](http://stackoverflow.com/questions/18880654/why-do-i-get-same-sequence-for-everyrun-with-stdrandom-device-with-mingw-gcc4). – Andy Prowl Jan 18 '15 at 13:40
  • Oh no... So it's actually broken?! I'm not just using it wrong? – Anonymous Entity Jan 18 '15 at 13:42

0 Answers0