C++ random number between 0 and 1

C++ random number between 0 and 1

Random numbers are frequently used in programming for test case generation, cryptography, and other related purposes.

In this tutorial, we will generate random number between 0 and 1 in C++.

The numbers generated are fractions, so they will be either float or double values.

Using the rand() function to generate random number between 0 and 1 in C++

The rand() function is used to generate a random number in C++. To work with this function we need to import the random library in C++. We can specify the range for the rand() function.

To generate random number between 0 and 1, we use the following code.

Output:

0.840188
0.394383
0.783099
0.79844
0.911647

In the above code,

  • We generated 5 random numbers using the rand() function and running it 5 times using the for loop.
  • The value for RAND_MAX constant is implementation-dependent and changes from compiler to compiler.
  • We typecast the final number to a float value.

It should be noted that whenever this code is run, the outcome will always be the same 5 random numbers. To fix this, we can use the srand() function, which sets the starting point for random number generation.

It is not advisable to use a constant value for the srand() function, so instead we use the time() function which helps in generating a different sequence every time.

See the following code.

Output:

0.257404
0.980979
0.616666
0.0109556
0.953417

Another thing to remember is that the above method will include 0 and 1 as random numbers. We can exclude 1 from it, by adding 1.0 in the denominator making it (float)(RAND_MAX + 1.0)

Using the std::uniform_real_distribution() function to generate random number between 0 and 1 in C++

This function is used to generate float values between a given range. We can generate random number between 0 and 1 using this function as shown below.

Output:

0.0935004
0.864206
0.830996
0.756512
0.206154

In the above example,

  • The random_device initializes the seed for the random number generation engine.
  • We specify the <float> datatype, otherwise, the final output can be in double or long double type also.
  • The range for the numbers is specified in the dis() argument.
    That’s all about C++ random number between 0 and 1.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.