I am learning C++, trying to generate a few random numbers within a specified range.
I'm trying to implement this answer here on SO, and revise it for it to be able to generate 64-bit integer.
Which I basically succeeded in, basic program could look like:
#include <iostream>
#include <random>
unsigned long long int random_integer(unsigned long long int rand_min, unsigned long long int rand_max)
{
// initialize = seed the random device
std::random_device random_device;
// use Mersenne Twister as random-number generator engine
std::mt19937_64 random_number_generator(random_device());
// number distribution, guaranteed unbiased
std::uniform_int_distribution<unsigned long long int> number_distribution(rand_min, rand_max);
return number_distribution(random_number_generator);
}
int main()
{
for (int i = 1; i <= 10; i++)
{
std::cout << random_integer(10000000, 100000000) << std::endl;
}
return 0;
}
Questions:
should I define the random device:
std::random_device random_device
out of the function?
I am also unsure where to define the Mersenne Twister:
std::mt19937_64 random_number_generator(random_device());
for the function to work as expected.
No, you should not define the random device outside of the function. It's best to reduce objects to the minimum scope required to satisfy their usefulness. This helps avoid tougher to track / understand state.
You should define the Mersenne Twister inside the function as well.
Additionally, if you want to get a random 64 bit (unsigned) integer, use std::uint64_t from <cstdint>.
Using the static and thread_local keywords, we can set up the function to only initialize the Twister / use the std::random_device once, rather than recreate them every function call, which is nice!
Here's something nice you can do that I find convenient when hacking about:
#include <random>
#include <cstdint>
std::uint64_t random_integer(std::uint64_t rand_min, std::uint64_t rand_max) {
static thread_local std::mt19937_64 rng{std::random_device{}()};
std::uniform_int_distribution<std::uint64_t> dist(rand_min, rand_max);
return dist(rng);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With