Home >Backend Development >C++ >How Can I Generate Random Floating-Point Numbers in C ?

How Can I Generate Random Floating-Point Numbers in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 09:25:17356browse

How Can I Generate Random Floating-Point Numbers in C  ?

Generating Random Floating-Point Numbers in C

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.

Generating Floats from 0.0 to 1.0

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);

Generating Floats within an Arbitrary Range

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);

Generating Floats within a Custom Range

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));

Initializing the Random Number Generator

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)));

Header File Inclusions

Note the following header file inclusions are necessary:

  • for calling rand() and srand()
  • for calling time()

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn