Generate a Random Float Number in C++
Last Updated :
14 Dec, 2022
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;
}
Output1.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;
}
Output0.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;
}
Output0.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;
}
Outputuniform_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;
}
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;
}
Output10.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;
}
Output1504136767
12
0.204022
13.5138
Time Complexity: O(1)
Auxiliary Space: O(1)
Similar Reads
Generate a Random Number between 0 and 1
The Task is to generate a random number between 0 and 1. It is obvious that the number between 0 and 1 will be a floating point number. To generate a random number between 0 and 1, we will make use of the rand() function. The rand() function creates a random number. Approach: Generating a Random Num
5 min read
How to Generate Random Numbers in R
Random number generation is a process of creating a sequence of numbers that don't follow any predictable pattern. They are widely used in simulations, cryptography and statistical modeling. R Programming Language contains various functions to generate random numbers from different distributions lik
2 min read
Generating Random Numbers in Golang
Golang provides a package math/rand for generating pseudorandom numbers. This package basically uses a single source that causes the production of a deterministic sequence of values each time a program is executed. Here, if you need different output or outcome for each execution, you can use the see
3 min read
How to Generate Unique Random Numbers in Excel?
Excel is powerful data visualization and analysis program we use to create reports or data summaries. So, sometimes happen that we have to create a report and assign a random id or number in a spreadsheet then we can create a random number without any repeat and manually.Approach 1: Using =RAND() f
1 min read
Program to generate a random two-digit number
Write a program to generate a random two-digit number. Example 1: 73Example 2: 26 Approach: To solve the problem, follow the below idea: We can generate a random two-digit number by generating a random integer first and then modulo it by 90. Now, after modulo 90 the remainder can be in the range 0 t
2 min read
How to generate a random number between 0 and 1 in Python ?
The use of randomness is an important part of the configuration and evaluation of modern algorithms. Here, we will see the various approaches for generating random numbers between 0 ans 1. Method 1: Here, we will use uniform() method which returns the random number between the two specified numbers
1 min read
Program to generate a random number between L to R
Write a program that generates a random number within a specified range [L, R]. The program should take two integers, L and R, as input and output a random number between L and R (inclusive). Examples: Input: L = 10, R = 20Output: 15 Input: L = -5, R = 5Output: 3 Approach: To solve the problem, foll
2 min read
Program to generate a random single digit number
Write a program to generate a random single-digit number. Example 1: 7Example 2: 3 Approach: To solve the problem, follow the below idea: To generate a random single-digit number, we can first generate a random integer and then take apply modulo to get the last digit of that random integer. This las
2 min read
Random Numbers in MATLAB
Random numbers, as the name suggests, are numbers chosen randomly from a set of numbers. In practical application, classical computers cannot create truly random numbers as they are developed on binary logic thus, they require some sort of algorithm to generate random numbers, this type of random nu
2 min read
Random number generation using TensorFlow
In the field of Machine Learning, Random numbers generation plays an important role by providing stochasticity essential for model training, initialization, and augmentation. We have TensorFlow, a powerful open-source machine learning library, that contains tf.random module. This module helps us for
6 min read