C++ random number generation, range of [0...n], as quick and lazy as possible?
c++, random
Solution
Watch Stephan T. Lavavej’s talk `rand()` considered harmful, it will answer all your questions and more.
In particular:
To generate uniform random numbers between 0 and n, use
std::random_device dev;
std::mt19937 gen{dev()};
std::uniform_real_distribution<T> dist{0, n};
This uses the predefined `mt19937` engine, which is a good default and should be used in all cases where there’s no strong argument against it.
For seeding, use `std::random_device` unless you need a reproducible seed.
Do not use `std::default_random_engine`, since it is under-specified: there is no control over what engine it is using, and it is not portable.
To shuffle a sequence of elements, use `std::shuffle`, do not use `std::random_shuffle` any more, consider it deprecated.
Problem
`<random>` has a ton of engine and distribution options. This is good and all, but most documentation I've read treats every engine and distribution with equal attention, and made no effort to suggest usage or useful instances for certain use-cases. I usually just use `rand()` to get useful data quickly, but I'm trying to be a better C++ programmer! (plus, getting useful floats out of `rand()` in a certain range can be it's own head ache sometimes) My question is, what is the quickest and laziest way to instance a random number generator in C++ that will do random numbers (floats, to pick a type) in the range [0...n] without any quirky surprises? edit: Watching the presentation on random mentioned in the comments, I realize the engine and distribution I needed was `mt199937` and `uniform_real_distribution`. I wasn't sure which was the mersenne twister, but seeing the 'mt' it's pretty obvious now. Combining the two concepts also makes sense now. Here is what I'm using in case anyone else comes across this: ``` std::mt19937 randomEngine(seed); std::uniform_real_distribution<float> range(0, n); float randomResult = range(randomEngine); ```