Home >Backend Development >C++ >How Can I Generate Truly Uniform Random Numbers in C ?
You seek to generate random numbers uniformly distributed within a specified interval, [min, max]. However, your current method is producing numbers clustered around a single point.
The rand() function is often unreliable for generating uniform distributions. It relies on a modulus operator that can introduce biases.
In C 11, consider using std::uniform_int_distribution for a more reliable solution:
#include <iostream> #include <random> int main() { const int range_from = min; const int range_to = max; 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'; }
The C 11 library offers various other random generators with different distributions. For example, std::shuffle can randomly reorder a container's elements.
If C 11 is not available, consider using Boost.Random, which provides similar functionality.
The above is the detailed content of How Can I Generate Truly Uniform Random Numbers in C ?. For more information, please follow other related articles on the PHP Chinese website!