Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On the full double range std::uniform_real_distribution always returns inf

Tags:

c++

random

c++11

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?

like image 963
Haatschii Avatar asked Mar 02 '23 00:03

Haatschii


1 Answers

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.

like image 151
1201ProgramAlarm Avatar answered May 10 '23 21:05

1201ProgramAlarm