It's easy to make mistakes when generating pseudo-random numbers. For example, in some cases, using rand() % RANGE may result in an erroneous distribution of numbers. (See this link for an example of a problem.)
It doesnโt matter, itโs trivial what you do.
If you need high-quality pseudo-random numbers, there are ways to fix rand() (see link above), but modern C ++ also provides <random> and uniform_int_distribution .
Here is an example simulating the casting of a hexagonal matrix, adapted from examples in Boost and the C ++ Reference :
#include <iostream> #include <random> std::random_device rd; std::mt19937 gen(rd()); int roll_die() { std::uniform_int_distribution<> dist(1, 6); return dist(gen); } int main() { std::cout << roll_die() << std::endl; }
The part that says dist(1, 6) can be changed to dist(0, 1) to create an output in the range [0, 1] (inclusive) with a uniform distribution.
source share