std::uniform_real_distribution总是返回无穷大
当我运行此代码时:
double getRandomDouble() {
static std::mt19937 entropy_ = std::mt19937();
std::uniform_real_distribution<double> distribution;
distribution.param(typename decltype(distribution)::param_type(std::numeric_limits<double>::lowest(),
std::numeric_limits<double>::max()));
return distribution(entropy_);
}
它总是返回无穷大(至少在 GCC8.1 和 clang 11.0.1 中。在 MSVC 14.16.27023 中它断言)
这是 GodBolt 中的一个工作演示
我希望这个函数返回任何随机的双精度值,这里发生了什么?
回答
参数的选择违反了std::uniform_real_distribution(参见第26.6.9.2.2.2 节)的前提条件。
先决条件是a ? b和b - a ? numeric_limits<T>::max(),其中a和b是分布的最小值和最大值。使用numeric_limits<double>::lowest()andnumeric_limits<double>::max()会违背这一点。
正如Ted所建议的那样,使用a = -max()/2.0,b = max()/2.0将是更好的选择。
- `[0; max) * randomSign` might be more appropriate to have "whole" double's range.
THE END
二维码