Haatschii
Haatschii

Reputation: 9319

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

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?

Upvotes: 4

Views: 170

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32727

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.

Upvotes: 7

Related Questions