In C , the rand() function serves as a reliable tool for creating pseudo-random numbers. By combining it with RAND_MAX and performing simple mathematical operations, you can generate random floats within specified intervals. For recreational programs and educational purposes, this approach suffices. However, if your requirement demands genuinely random numbers with normal distribution, consider implementing more sophisticated techniques.
To obtain a random float between 0.0 and 1.0 (inclusive), employ the following formula:
float r = static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
For generating a float within the range [0.0, X], use the following formula:
float r2 = static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / X);
To generate a float within the range [LO, HI], utilize the following formula:
float r3 = LO + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (HI - LO));
Before employing rand(), it is crucial to initialize the random number generator by calling srand(). This initialization should occur only once during the program's execution, not with each call to rand(). A common practice involves:
srand(static_cast<unsigned>(time(0)));
Note the following header file inclusions are necessary:
The above is the detailed content of How Can I Generate Random Floating-Point Numbers in C ?. For more information, please follow other related articles on the PHP Chinese website!