Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I use std::random_device?

Tags:

c++

random

c++11

According to the standard, std::random_device works the following way:

result_type operator()();

Returns: A non-deterministic random value, uniformly distributed between min() and max(), 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?

like image 313
user4363909 Avatar asked Dec 15 '14 20:12

user4363909


People also ask

How do you generate a random number in C++?

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.

What is mt19937 C++?

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.

Is random number generator deterministic?

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).


1 Answers

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.

like image 151
Bill Lynch Avatar answered Oct 13 '22 13:10

Bill Lynch