0

I am working on randomized algorithm in C++ in which I need to generate random numbers, both real and integer. I have written two functions:

double random_real_number() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dis(0.0, 1.0);
    double number = dis(gen);
    cout << number << endl;
    return number;
}

int random_integer_number() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<int> dis(0, INT_MAX);
    int number = dis(gen);
    cout << number << endl;
    return number;
}

The functions are called multiple times in a loop by other function. When I compile and run the the program with Visual Studio 2013 everything works fine, but when I use g++ (on Windows) to compile and run the program, the random_real_number() always produces 0.726249 and random_integer_number() always produces 14959223606. I think I have written functions correctly according to opinions shared on internet, but I do not know how to overcome this. I will be thankful for help.

  • 3
    You're doing it wrong. Also, `std::random_device` is broken in mingw on windows. Though, per standard, it is correct. – Incomputable Dec 11 '17 at 18:17
  • 3
    In general, seed the generator once, not every time you use it. As written, the code relies on the randomness of `std::random_device`, with the `std::mt19937` just spinning wheels. – Pete Becker Dec 11 '17 at 18:20
  • You can use [std::seed_seq](http://en.cppreference.com/w/cpp/numeric/random/seed_seq) to seed the Mersenne twister with some more source of entropy. E.g. https://ideone.com/gd5n5l – Bob__ Dec 11 '17 at 19:44

0 Answers0