Generate Random Double Numbers in C++
Last Updated :
16 Feb, 2023
Double is a data type just like a float but double has 2x more precision than float. One bit for the sign, 11 bits for the exponent and 52* bits for the value constitute the 64-bit IEEE 754 double precision Floating Point Number known as “double.” Double has 15 decimal digits of precision.
In this article, we generate random double numbers in C++.
Methods to generate random double
The random double number can be generated using a few methods which are mentioned below:
- Using random() function
- Using uniform_real_distribution and default_random_engine.
1. Using random() function
Using the random function is the method where we get random integers and by using them we create a random double number by performing certain operations in it. You can set lower and upper bounds in it.
random(): It generate a random integer.
Example:
C++
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
const long max_rand = 1000000L;
double lower_bound = 0;
double upper_bound = 100;
srandom( time (NULL));
double random_double = lower_bound
+ (upper_bound - lower_bound)
* (random() % max_rand)
/ max_rand;
cout << random_double << endl;
return 0;
}
|
2. Using uniform_real_distribution and default_random_engine
When we want to find random numbers after defining the upper and lower bound then we can use this method.
uniform_real_distribution: The random library now includes the uniform real distribution class, whose member functions generate random real numbers or continuous values with uniform probability from a specified input range.
default_random_engine: This class of pseudo-random number generators produces random numbers.
- min(): It gives back the lowest value specified by the operator ().
- max(): It gives back the highest value specified by the operator ().
- operator(): A fresh random number is given back.
Example:
C++
#include <iostream>
#include <random>
using namespace std;
int main()
{
double lower_bound = 0;
double upper_bound = 100;
uniform_real_distribution< double > unif(lower_bound,
upper_bound);
default_random_engine re;
double random_double = unif(re);
cout << random_double << endl;
return 0;
}
|
Time complexity: O(1).
Auxiliary Space: O(1).
Share your thoughts in the comments
Please Login to comment...