Home >Backend Development >C++ >How to Generate Random Double Numbers with Specified Precision in C ?
Generating Random Double Numbers in C with Specified Precision
Generating random double numbers within a specified range is a common requirement in programming. Particularly, when you need the numbers to have a specific precision, such as "xxxxx,yyyyy," this task can become a bit more challenging. Fortunately, C provides a robust library for handling random number generation.
The solution involves using the uniform_real_distribution class from the
<code class="cpp">#include <random> int main() { // Define the lower and upper bounds of the desired range double lower_bound = 0; double upper_bound = 10000; // Create a uniform real distribution within the specified range std::uniform_real_distribution<double> unif(lower_bound, upper_bound); // Initialize a random engine std::default_random_engine re; // Generate a random double using the distribution double a_random_double = unif(re); return 0; }</code>
In this example, the range is defined between 0 and 10000. The unif distribution is initialized with these bounds. To generate a random double, the re engine is used to feed into the distribution. The resulting a_random_double will be a random number within the specified range.
For more details on random number generation in C , refer to John D. Cook's "Random number generation using C TR1" or Stroustrup's "Random number generation."
The above is the detailed content of How to Generate Random Double Numbers with Specified Precision in C ?. For more information, please follow other related articles on the PHP Chinese website!