乐闻世界logo
搜索文章和话题

Why does C++ rand() seem to generate only numbers of the same order of magnitude?

1个答案

1

The rand() function in C++ is based on a pseudo-random number generator (PRNG) to generate random numbers. However, using rand() to generate random numbers may have certain limitations, particularly in terms of the range and distribution of numbers.

First, the rand() function defaults to generating a random number between 0 and RAND_MAX, where RAND_MAX is a constant typically valued at 32767 on most platforms. Therefore, the generated random numbers fall within this range, which is why you observe the generated numbers to be within the same order of magnitude.

Additionally, the random numbers generated by rand() are not statistically uniformly distributed. This means that certain numbers may appear more frequently than others. This non-uniform distribution may be due to the algorithm used internally by rand(), which may not adequately simulate true randomness.

If you need to generate random numbers with a larger range and more uniform distribution, consider using alternative methods such as:

  1. Use a better random number generation library: For example, the <random> library introduced in C++11 provides various high-quality random number generators and distribution types.

  2. Adjust the generation range: You can generate a random decimal in [0,1] using the formula (double) rand() / RAND_MAX, and then scale and shift it appropriately to generate random numbers within any desired range.

  3. Use advanced algorithms: For example, the Mersenne Twister algorithm can generate random number sequences with longer periods and higher-dimensional uniform distributions.

Through a practical example, assume we need to generate random numbers between 0 and 100000. Using the C++11 <random> library, it can be implemented as:

cpp
#include <random> #include <iostream> int main() { std::random_device rd; // Obtain a random seed std::mt19937 gen(rd()); // Use the Mersenne Twister algorithm std::uniform_int_distribution<> distrib(0, 100000); for(int i=0; i<10; i++) { std::cout << distrib(gen) << std::endl; } return 0; }

The random numbers generated by this code will be more uniform and not constrained by RAND_MAX.

2024年6月29日 12:07 回复

你的答案