VOOZH about

URL: https://www.geeksforgeeks.org/cpp/generate-a-random-float-number-in-cpp/

⇱ Generate a Random Float Number in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate a Random Float Number in C++

Last Updated : 23 Jul, 2025

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:


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:


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:


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:


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:


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:


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:


Output
1504136767
12
0.204022
13.5138

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

Comment