According to the standard, std::random_device
works the following way:
result_type operator()();
Returns: A non-deterministic random value, uniformly distributed between
min()
andmax()
, inclusive. It is implementation-defined how these values are generated.
And there are a couple of ways you can use it. To seed an engine:
std::mt19937 eng(std::random_device{}());
As an engine in itself:
std::uniform_int_distribution<> uid(1, 10);
std::cout << dist(dev);
Because it is implementation-defined, it doesn't sound as strong as say std::seed_seq
or srand(time(nullptr))
. Do I prefer to use it as a seed, as an engine or not at all?
rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.
std::mt19937(since C++11) class is a very efficient pseudo-random number generator and is defined in a random header file. It produces 32-bit pseudo-random numbers using the well-known and popular algorithm named Mersenne twister algorithm.
Random bits are generated by running a deterministic random bit generator (DRBG) on the entropy pool data bits. This algorithm is deterministic (it always produces the same output given the same input).
Generally speaking, std::random_device
should be the source of the most truly random information you can access on your platform. That being said, accessing it is much slower than std::mt19937
or what not.
The correct behavior is to use std::random_device
to seed something like std::mt19937
.
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