Open In App

Generate a Random Float Number in C++

Improve
Improve
Like Article
Like
Save
Share
Report

Random floating numbers can be generated using 2 methods:

  • Using rand()
  • Using uniform real distribution

1. Use of rand()

We can generate random integers with the help of the rand() and srand() functions. There are some limitations to using srand() and rand(). To know more about the srand() and rand() functions refer to srand() and rand() in C++.

Approach: We can modify the approach we used to find a random integer here to find a random float, 

Example:

C++




// C++ program to generate random float numbers
#include <bits/stdc++.h>
 
using namespace std;
 
float randomFloat()
{
    return (float)(rand()) / (float)(rand());
}
 
signed main()
{
    // seeds the generator
    srand(time(0));
 
    for (int i = 0; i < 5; i++) {
        // generate different sequence of random float
        // numbers
        cout << randomFloat() << endl;
    }
 
    return 0;
}


Output

1.95347
0.329458
2.98083
0.870023
0.114373

Time Complexity: O(1)
Auxiliary Space: O(1)

Say someone wants to generate the fraction part only then,

Example:

C++




// C++ program to generate random float numbers
#include <bits/stdc++.h>
 
using namespace std;
 
float randomFloat()
{
    return (float)(rand()) / (float)(RAND_MAX);
}
 
signed main()
{
    // seeds the generator
    srand(time(0));
 
    for (int i = 0; i < 5; i++) {
        // generate different sequence of
        // random float numbers
        cout << randomFloat() << endl;
    }
 
    return 0;
}


Output

0.408574
0.209153
0.189758
0.57597
0.843264

Time Complexity: O(1)
Auxiliary Space: O(1)

2. 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 Random Numbers in a Range

Suppose there are two numbers a and b, we want to generate a random number between them [a, b) 

1. Generate Random Integer in a Range

Example:

C++




// C++ program to generate random integers
#include <bits/stdc++.h>
 
using namespace std;
 
int randomInt(int a, int b)
{
    if (a > b)
        return randomInt(b, a);
    if (a == b)
        return a;
    return a + (rand() % (b - a));
}
 
signed main()
{
    // seeds the generator
    srand(time(0));
 
    // generate random integers in a range [ Min , Max )
    for (int i = 0; i < 5; i++) {
        cout << randomInt(10, 20) << " ";
    }
 
    return 0;
}


Output

16 17 16 10 14 

Time Complexity: O(1)
Auxiliary Space: O(1)

Now we can use this same concept to generate a random float number in a range 

2. Generate Random Float Numbers in a Range

Example:

C++




// C++ program to generate random float numbers
#include <bits/stdc++.h>
 
using namespace std;
 
float randomFloat()
{
    return (float)(rand()) / (float)(RAND_MAX);
}
 
int randomInt(int a, int b)
{
    if (a > b)
        return randomInt(b, a);
    if (a == b)
        return a;
    return a + (rand() % (b - a));
}
 
float randomFloat(int a, int b)
{
    if (a > b)
        return randomFloat(b, a);
    if (a == b)
        return a;
 
    return (float)randomInt(a, b) + randomFloat();
}
 
signed main()
{
 
    // seeds the generator
 
    srand(time(0));
 
    // generate random float numbers in a
    // range [ Min , Max)
    for (int i = 0; i < 5; i++) {
        cout << randomFloat(10, 20) << "\n";
    }
 
    return 0;
}


Output

10.859
19.3532
13.1625
18.3262
16.2245

Time Complexity: O(1)
Auxiliary Space: O(1)

Wrap Up:

Let us wrap up all the things in one example.

Example:

C++




// C++ program to generate random numbers
#include <bits/stdc++.h>
 
using namespace std;
 
class Random {
public:
    // constructor
    Random()
    {
        // seeds the generator
        srand(time(0));
    }
 
    // generate random integer
    int randomInt() { return rand(); }
 
    // generate random integer in a range [Min , Max)
    int randomInt(int a, int b)
    {
        if (a > b)
            return randomInt(b, a);
        if (a == b)
            return a;
        return a + (rand() % (b - a));
    }
 
    // generate random fraction
 
    float randomFloat()
    {
        return (float)(rand()) / (float)(RAND_MAX);
    }
 
    // generate random float in a range
    float randomFloat(int a, int b)
    {
        if (a > b)
            return randomFloat(b, a);
        if (a == b)
            return a;
 
        return (float)randomInt(a, b) + randomFloat();
    }
};
 
signed main()
{
 
    Random random = Random();
 
    // random integer
    cout << random.randomInt() << "\n";
 
    // random integer in a range
    cout << random.randomInt(10, 15) << "\n";
 
    // random  float (fraction)
    cout << random.randomFloat() << "\n";
 
    // random float in range
    cout << random.randomFloat(10, 15) << "\n";
 
    return 0;
}


Output

1504136767
12
0.204022
13.5138

Time Complexity: O(1)
Auxiliary Space: O(1)



Last Updated : 14 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads