![]() |
VOOZH | about |
Random floating numbers can be generated using 2 methods:
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:
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:
0.408574 0.209153 0.189758 0.57597 0.843264
Time Complexity: O(1)
Auxiliary Space: O(1)
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:
0.526151 1.8346 0.875837 2.71546 3.73877
Time Complexity: O(1)
Auxiliary Space: O(1)
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:
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
Suppose there are two numbers a and b, we want to generate a random number between them [a, b)
Example:
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
Example:
10.859 19.3532 13.1625 18.3262 16.2245
Time Complexity: O(1)
Auxiliary Space: O(1)
Let us wrap up all the things in one example.
Example:
1504136767 12 0.204022 13.5138
Time Complexity: O(1)
Auxiliary Space: O(1)