std::uniform_real_ distribution class in C++ with Examples
Last Updated :
01 Mar, 2024
In Probability, Uniform Distribution Function refers to the distribution in which the probabilities are defined on a continuous random variable, one which can take any value between two numbers, then the distribution is said to be a continuous probability distribution. For example, the temperature throughout a given day can be represented by a continuous random variable and the corresponding probability distribution is said to be continuous.
C++ have introduced
uniform_real_distribution class in the
random library whose member function give random real numbers or continuous values from a given input range with uniform probability.
Public member functions in uniform_real_distribution class:
- operator(): This function returns a random value from the range given. The datatype of the return value is specified during initialization of the template class. The probability for any value is same. The time complexity for this operation is O(1).
Example:
CPP
#include <iostream>
#include <random>
using namespace std;
int main()
{
default_random_engine generator;
double a = 0.0, b = 1.0;
uniform_real_distribution< double > distribution(a, b);
const int num_of_exp = 10000000;
int n = 100;
int p[n] = {};
for ( int i = 0; i < num_of_exp; ++i) {
double number = distribution(generator);
++p[ int (number * n)];
}
cout << "Probability of some ranges" << endl;
cout << "0.50-0.51"
<< " " << ( float )p[50] / ( float )num_of_exp << endl;
cout << "0.60-0.61"
<< " " << ( float )p[60] / ( float )num_of_exp << endl;
cout << "0.45-0.46"
<< " " << ( float )p[45] / ( float )num_of_exp << endl;
return 0;
}
|
Output:Probability of some ranges
0.50-0.51 0.0099808
0.60-0.61 0.0099719
0.45-0.46 0.009999
The probability of all ranges are almost equal.
a(): Returns lower bound of range.
b(): Returns upper bound of range.
min(): Returns minimum value the function can return. For uniform distribution min() and a() return same value.
max(): Returns minimum value the function can return. For uniform distribution min() and a() return same value.
reset(): This function resets the distribution such that the next random values generated are not based on the previous values.
Example:
CPP
#include <iostream>
#include <random>
using namespace std;
int main()
{
double a = 0, b = 1.5;
uniform_real_distribution< double > distribution(a, b);
cout << "Lower Bound"
<< " " << distribution.a() << endl;
cout << "Upper Bound"
<< " " << distribution.b() << endl;
cout << "Minimum possible output"
<< " " << distribution.min() << endl;
cout << "Maximum possible output"
<< " " << distribution.max() << endl;
distribution.reset();
return 0;
}
|
Output: Lower Bound 0
Upper Bound 1.5
Minimum possible output 0
Maximum possible output 1.5
Reference:
http://www.cplusplus.com/reference/random/uniform_real_distribution/
Share your thoughts in the comments
Please Login to comment...