我有一条线:
std::uniform_real_distribution<T> distribution(std::numeric_limits<T>::lowest(),
std::numeric_limits<T>::max());
它编译但在调试时崩溃(VS 2017CE)。我的猜测是,根据 std::uniform_real_distribution
的文档:
Requires that
a ≤ b
andb-a ≤ std::numeric_limits<RealType>::max()
当我的b
是::max()
和 a
是::lowest()
, 条件:
b-a ≤ std::numeric_limits<RealType>::max()
未满足 b-a
基本上使 max
的值翻倍.有什么解决方法可以让我保持这么大的数字范围吗? ::min()
工作完美但忽略了负值。只有 float 才会出现问题。
最佳答案
至少对于常见的 IEEE-754 float ,一个简单的解决方案是随机翻转随机非负数的符号:
std::uniform_real_distribution<T> distribution(0.,
std::numeric_limits<T>::max());
auto rn = distribution(eng);
return someRandomFlag ? rn : -rn;
其中 someRandomFlag
是从 {true, false}
中统一选择的。
关于c++ - Uniform_real 不接受 numeric_limits::lowest(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52039103/