生成E = 0的浮点随机数

时间:2017-01-03 14:26:57

标签: c++ random

uniform_real_distribution不包括右端。这意味着生成E = 0的随机数是不可能的。如何创建一个具有开放间隔或闭合间隔的uniform_real_distribution,而不是半开?

有人可能会说,对负值的偏见并不重要,因为差异很小,但仍然不完全正确。

1 个答案:

答案 0 :(得分:4)

您可以将std::uniform_real_distributionstd::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()));
}

经过一些查找后,这实际上是en.cppreference上提出的方法。

如果要创建开放区间,只需在第一个参数上使用nextafter()

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);
}