Consider the following minimal example:
#include <random>
#include <iostream>
int main (const int argC, char* argV[] ) {
std::uniform_real_distribution<double> dist(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max());
std::random_device gen;
std::cout << dist(gen) << std::endl;
return 0;
}
I would expect the program to print basically any number in the range of double
. However on my machine the output is always inf
. The same is true if I replace double
by float
.
I can easily imagine how this can happen by a faulty implementation of std::uniform_real_distribution
, as e.g. the length of the interval from which the numbers are drawn is not representable as a double
. However my question is, is this indeed a bug in my standard library implementation, or did I miss some some restriction on the interval allowed by the C++ standard?
One of the requirements for a uniform_real_distribution
is that the difference between the two bounds is less than std::numeric_limits<double>::max()
. So your attempt is ill-formed.
As a workaround, you could split it into two generators, one for negative numbers and one for non-negative numbers. Randomly select one of the two generators.
Keep in mind that the upper bound of the range cannot be returned as a generated number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With