c++ - Uniform_real 不接受 numeric_limits::lowest()

标签 c++ c++11 random

我有一条线:

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 and b-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/

相关文章:

c++ - 根据指定的时间间隔将浮点值映射到函数

c++ - VS2012 SP1(+11 月包)未知类型错误(如 C::a(T &&...) )

python - 从功能上打乱列表

java - 如何在 Java 中返回 5 个随机的 "Powerball"数字

algorithm - 遗传算法 : 2D chromosome; crossover and mutation probabilities

c++ - 科学 ofstream 中的指数只有 2 位数

c++ - 传递成员函数时替代 std::bind

BST 中的 C++11 神奇删除构造函数

c++ - Linux写函数

c++ - 将 std::ptr_fun 用于成员函数