Home >Backend Development >C++ >How Can I Generate Uniformly Distributed Random Integers in C ?
When developing software, generating random integers within a specified range is a common task. However, finding a fast and uniformly distributed random number generator can be challenging. In this article, we address this issue by exploring various approaches to generating random integers within a given range.
A common method for generating random integers is to use the rand() function. However, as expressed in the original question, rand() can lead to a biased distribution, especially for small ranges.
To address this issue, an alternative formula was proposed:
( (max - min) * rand() + (RAND_MAX / (2 * (max - min))) ) / RAND_MAX
While this formula provides a more uniform distribution, it still falls short of addressing all the requirements, namely, speed, uniform distribution, variable ranges, and seedability.
Introducing the C standard library function std::uniform_int_distribution and its associated random number generator std::mt19937. This approach is straightforward, fast, and provides unbiased results.
#include <random> std::random_device rd; std::mt19937 rng(rd()); std::uniform_int_distribution<int> uni(min,max); auto random_integer = uni(rng);
The std::random_device initializes the generator with a real entropy source, ensuring that the generated numbers are unpredictable and random. The std::uniform_int_distribution defines the range of integers to be generated, guaranteeing that all values within that range have an equal probability of being selected.
This approach fulfills all the requirements:
In conclusion, the simplest and best approach for generating uniformly distributed random integers in C is to use the std::uniform_int_distribution and std::mt19937 functions. This approach leverages the optimized algorithms of the standard library, ensuring both speed and randomness.
The above is the detailed content of How Can I Generate Uniformly Distributed Random Integers in C ?. For more information, please follow other related articles on the PHP Chinese website!