Generating Uniformly Distributed Random Integers
In many programming applications, generating random integers within a specified range is a common requirement. However, ensuring that these integers are uniformly distributed presents a challenge. This article explores various approaches to achieving uniform distribution.
Existing Code and Limitations
The code provided by the user leverages the rand() function to generate random numbers within a given range. However, this approach suffers from a lack of uniformity, particularly for small ranges like <0, 1>. This is attributed to the low probability of rand() returning RAND_MAX, the maximum value.
Proposed Formula
To address this issue, the user devised a new formula:
( (max - min) * rand() + (RAND_MAX / (2 * (max - min))) ) / RAND_MAX
While this formula aims to improve uniformity, it still falls short, as evidenced by sampling data.
C Standard Library Solution
The C standard library provides an elegant and reliable solution to this problem. The std::random header includes a set of random number generators and distributions that can generate random numbers with uniform distribution.
#include <random> // Initialize random-number engine with a seed std::random_device rd; std::mt19937 rng(rd()); // Define uniform integer distribution std::uniform_int_distribution<int> uni(min, max); // Generate random integer within range auto random_integer = uni(rng);
This approach leverages well-tested and optimized code, ensuring uniform distribution and efficiency. It eliminates the need for reinventing the wheel and concerns about bias or seed values.
The above is the detailed content of How Can We Generate Truly Uniformly Distributed Random Integers in a Specified Range?. For more information, please follow other related articles on the PHP Chinese website!