Home >Backend Development >C++ >How can I generate truly uniform random numbers within a specific range in C ?
To generate random numbers within a specified interval [min, max] uniformly, the following guidelines should be considered:
Using rand() and the modulo operator, as demonstrated in the given code snippet, may not produce uniformly distributed random numbers. It depends on the range and the value of RAND_MAX.
With C 11, you can utilize std::uniform_int_distribution to generate random numbers within a range:
#include <iostream> #include <random> int main() { const int range_from = 0; const int range_to = 1000; std::random_device rand_dev; std::mt19937 generator(rand_dev()); std::uniform_int_distribution<int> distr(range_from, range_to); std::cout << distr(generator) << '\n'; }
C 11 provides additional random number generators with various distributions, such as Bernoulli, Poisson, and normal.
To shuffle a container randomly, use std::shuffle:
#include <iostream> #include <random> #include <vector> int main() { std::vector<int> vec = {4, 8, 15, 16, 23, 42}; std::random_device random_dev; std::mt19937 generator(random_dev()); std::shuffle(vec.begin(), vec.end(), generator); std::for_each(vec.begin(), vec.end(), [](auto i){std::cout << i << '\n';}); }
If C 11 is not available, you can use Boost.Random, which offers an interface similar to C 11's random number generation facilities.
The above is the detailed content of How can I generate truly uniform random numbers within a specific range in C ?. For more information, please follow other related articles on the PHP Chinese website!