Generate Random Float Numbers Using the “uniform real distribution ” method
C++ has introduced a uniform_real_distribution class in the random library whose member function gives random real numbers or continuous values from a given input range with uniform probability.
Example:
C++
// C++ Program to illustrate // uniform real distribution method #include <bits/stdc++.h> using namespace std; int main() { // random generator default_random_engine gen; uniform_real_distribution< double > distribution(0.0, 4.0); for ( int i = 0; i < 5; i++) { cout << distribution(gen) << '\n' ; } return 0; } |
Output
0.526151 1.8346 0.875837 2.71546 3.73877
Time Complexity: O(1)
Auxiliary Space: O(1)
Disadvantage of using std:uniform_real_distribution:
We can not generate any random sequence whenever we execute this code, this leads us to identical sequences every time, So this code can be applied to find the probability or frequency in a certain range on a large number of experiments
Example:
C++
// C++ Program to illustrate // uniform_real_distribution #include <bits/stdc++.h> using namespace std; int main() { // number of experiments int num_of_experiments = 10000; // number of intervals int num_of_intervals = 10; // random generator default_random_engine gen; uniform_real_distribution< float > distribution(0.0, 1.0); // frequency array to store frequency int freq[num_of_intervals] = {}; for ( int i = 0; i < num_of_experiments; i++) { float number = distribution(gen); freq[ int (num_of_intervals * number)]++; } cout << "uniform_real_distribution (0.0,1.0) " "\nFrequencies after 10000 experiments :" << endl; for ( int i = 0; i < num_of_intervals; ++i) { cout << float (i) / num_of_intervals << "-" << float (i + 1) / num_of_intervals << ": " ; cout << freq[i] << endl; } return 0; } |
Output
uniform_real_distribution (0.0,1.0) Frequencies after 10000 experiments : 0-0.1: 993 0.1-0.2: 1007 0.2-0.3: 998 0.3-0.4: 958 0.4-0.5: 1001 0.5-0.6: 1049 0.6-0.7: 989 0.7-0.8: 963 0.8-0.9: 1026 0.9-1: 1016
Generate a Random Float Number in C++
Random floating numbers can be generated using 2 methods:
- Using rand()
- Using uniform real distribution
Contact Us