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?

- 3,287
- 4
- 27
- 39
-
1Consult the documentation. The choice of random number generator depends on your particular situation. That said, the Mersenne Twister is often a good starting point. – Bathsheba May 14 '15 at 15:17
-
I'm curious when one should choose `std::default_random_engine`. Does it have any advantage over `std::mt19937`? – Deqing Aug 18 '16 at 13:26
3 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.

- 68,716
- 7
- 72
- 138
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.

- 25,168
- 7
- 79
- 97
They address different needs. The first is an implementation-defined alias for a certain generator whilst the latter specifically uses the Mersenne-Twister algorithm with a 32 bit seed.
If you don't have particular requirements, std::default_random_engine
should be ok.

- 8,220
- 2
- 26
- 45