user877329
user877329

Reputation: 6200

Generate floating point random number with E=0

uniform_real_distribution does not include the right end. This means that it is not possible right a way to generate random numbers with E=0. How can I create a uniform_real_distribution with either an open interval, or a closed interval, not half-open?

One could argue that the bias towards negative values does not matter, because the difference is small, but still, it is not fully correct.

Upvotes: 1

Views: 59

Answers (1)

Holt
Holt

Reputation: 37616

You can combine std::uniform_real_distribution with std::nextafter:

template <typename RealType = double>
auto make_closed_real_distribution(RealType a = 0.0, RealType b = 1.0) {
    return std::uniform_real_distribution<RealType>(
        a, std::nextafter(b, std::numeric_limits<RealType>::max()));
}

After a bit of lookup, this is actually the method proposed on en.cppreference.

If you want to make an open-interval, simply use nextafter() on the first argument:

template <typename RealType = double>
auto make_open_real_distribution(RealType a = 0.0, RealType b = 1.0) {
    return std::uniform_real_distribution<RealType>(
        std::nextafter(a, std::numeric_limits<RealType>::max()), b);
}

Upvotes: 4

Related Questions