This post will discuss how to generate random float values in C++.

1. Using std::uniform_real_distribution

Since C++11, we can produce uniformly distributed floating-point values between two numbers with std::uniform_real_distribution. Consider the following code, which produces high-quality floating-point random values in the closed interval [1, 10] using std::uniform_real_distribution. It uses std::random_device to obtain seed for the standard mersenne_twister_engine std::mt19937, based on the Mersenne Twister algorithm.

Download  Run Code

 
Note that there are numerous other predefined random number generators defined in the header <random>, as listed here. Before C++11, you may use Mersenne Twister by boost library to generate random float values. For example, the following solution uses Boost.Random with boost::random::uniform_real_distribution and std::mt19937 algorithm to generate a random floating-point value in closed range [1, 10].

Download Code

2. Using rand() function

Another simple, but less preferred solution to generate pseudo-random numbers in C++ is with rand() function. It returns a random number between 0 and RAND_MAX, and can be used to generate floating-point random values in any arbitrary closed interval. Don’t forget to seed the random number generator with srand() before invoking rand(). Both rand() and srand() functions are defined in <cstdlib> header.

For example, the following will generate a floating-point number in close range [0, 1].

Download  Run Code

 
We can easily extend the solution to generate an arbitrary float value between two specified values. For example, the expression low + rand() * (high - low) / RAND_MAX; generates a random floating-point value in the closed range [low, high], as shown below:

Download  Run Code

That’s all about generating random float values in C++.