Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random_device vs default_random_engine

Tags:

c++

random

c++11

#include <vector>
#include <random>

using namespace std;

int main()
{
    vector<int> coll{1, 2, 3, 4};
    shuffle(coll.begin(), coll.end(), random_device{});

    default_random_engine dre{random_device{}()};
    shuffle(coll.begin(), coll.end(), dre);
}

Question 1: What's the difference between

shuffle(coll.begin(), coll.end(), random_device{});

and

shuffle(coll.begin(), coll.end(), dre);?

Question 2: Which is better?

like image 598
xmllmx Avatar asked Dec 18 '22 15:12

xmllmx


2 Answers

Question 1: What's the difference between...

std::random_device conceptually produces true random numbers. Some implementations will stall if you exhaust the system's source of entropy so this version may not perform as well.

std::default_random_engine is a pseudo-random engine. Once seeded, with an random number it would be extremely difficult (but not impossible) to predict the next number.

There is another subtle difference. std::random_device::operator() will throw an exception if it fails to come up with a random number.

Question 2: Which is better?

It depends. For most cases, you probably want the performance and temporal-determinism of the pseudorandom engine seeded with a random number, so that would be the second option.

like image 73
Richard Hodges Avatar answered Dec 24 '22 03:12

Richard Hodges


Both random_device and default_random_engine are implementation defined. random_device should provide a nondeterministic source of randomness if available, but it may also be a prng in some implementations. Use random_device if you want unpredictable random numbers (most machines nowadays have hardware entropy sources). If you want pseudo random numbers you'd probably use one of the specific algorithms, like the mersenne_twister_engine.

I guess default_random_engine is what you'd use if you don't care about the particulars of how you get your random numbers. I'd suspect it'd just use rand under the hood or a linear_congruential_engine most of the time.

I don't think the question "which is better" can be answered objectively. It depends on what you're trying to do with your random numbers. If they're supposed to be random sources for some cryptographic process, I suspect default_random_engine is a terrible choice, although I'm not a security expert, so I'm not sure if even random_device is good enough.

like image 36
Cubic Avatar answered Dec 24 '22 02:12

Cubic