Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use std::default_random_engine or should I use std::mt19937?

Tags:

c++

when I want to generate random numbers using std::random, which engine should I prefer? the std::default_random_engine or the std::mt19937? what are the differences?

like image 379
Alaya Avatar asked May 14 '15 15:05

Alaya


2 Answers

For lightweight randomnes (e.g. games), you could certainly consider default_random_engine. But if your code depends heavily on quality of randomness (e.g. simulation software), you shouldn't use it, as it gives only minimalistic garantees:

It is the library implemention's selection of a generator that provides at least acceptable engine behavior for relatively casual, inexpert, and/or lightweight use.

The mt19937 32 bits mersene twister (or its 64 bit counterpart mt19937_64) is on the other side a well known algorithm that passes very well statistical randomness tests. So it's ideal for scientific applications.

However, you shall consider neither of them, if your randomn numbers are meant for security (e.g. cryptographic) purpose.

like image 108
Christophe Avatar answered Oct 23 '22 19:10

Christophe


The question is currently having one close vote as primary opinion based. I would argue against that and say that std::default_random_engine is objectively a bad choice, since you don't know what you get and switching standard libraries can give you different results in the quality of the randomness you receive.

You should pick whatever random number generator gives you the kind of qualities you are looking for. If you have to pick between the two, go with std::mt19937 as it gives you predictable and defined behaviour.

like image 8
JustSid Avatar answered Oct 23 '22 18:10

JustSid