简体   繁体   中英

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

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?

For lightweight randomnes (eg games), you could certainly consider default_random_engine . But if your code depends heavily on quality of randomness (eg 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 (eg cryptographic) purpose.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM