How to generate random integers 0 to 0x7FFFFFFF?

-2

This doesn't work:

for (int p = 0; p < 10; p++) {
    random_device rd;
    mt19937 gen(rd);
    uniform_real_distribution<int> dis(0, INT_MAX);
    printf("%i\n", dis(gen));
}

Any advice would be appreciated.

c++
visual-studio
windows-10
asked on Stack Overflow Aug 29, 2018 by Ziggi

1 Answer

4

You have few mistakes in your code.

  1. You should move creation of random_device and seeding mt19937 outside the for loop. I'll also suggest the same for uniform_real_distribution<int>
  2. mt19937 takes in the constructor value of seed not random_device so you have to call it to get seed(rd())
  3. You should use uniform_int_distribution<int> if you are generating integers
  4. If your intention is to generate number to 0x7FFFFFFF you should put this number explicitly but if you want to get numbers to max int value i'll suggest using more C++ style std::numeric_limits<int>::max()

Here is working example:

#include <cstdio>
#include <random>
#include <limits>
using namespace std;

int main(){
  random_device rd;
  mt19937 gen(rd());
  uniform_int_distribution<int> dis(0, std::numeric_limits<int>::max());
  for (int p = 0; p < 10; p++) {
    printf("%i\n", dis(gen));
  }
  return 0;
}
answered on Stack Overflow Aug 29, 2018 by maxmati

User contributions licensed under CC BY-SA 3.0