I wrote a small function to return a random in a given range:
int random_in_range(int min, int max) {
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<int> uni(min, max);
return uni(rng);
}
But I read somewhere that you should only seed a random number generator once leading me to believe that the function should really be:
std::random_device rd;
std::mt19937 rng(rd());
int random_in_range(int min, int max) {
std::uniform_int_distribution<int> uni(min, max);
return uni(rng);
}
I later tested both to see if one was clearly better than the other (in terms of randomness) and got results which do not make things any clearer.
First example result with 10 runs, making a decision of 1 or 0:
for (int i = 0; i < 10; i++) {
cout << first_example(0, 1);
}
>0100100001
The second example result with 10 runs, making a decision of 1 or 0:
for (int i = 0; i < 10; i++) {
cout << second_example(0, 1);
}
>1011000110
The two results don't seem too strange leading me to be confused about how I should initialize random number generators. Basically, what I am asking is: which of these two example (or something else if both are wrong) would be used in order to guarantee the lowest amount of bias?
rng
out of your function, too. Moving the random device outside is not sufficient. \$\endgroup\$