如果我按以下方式生成浮点值:
template <typename T>
T RandomFromRange(T low, T high){
std::random_device random_device;
std::mt19937 engine{random_device()};
std::uniform_real_distribution<T> dist(low, high);
return dist(engine);
}
template <typename T>
T GetRandom(){
return RandomFromRange
(std::numeric_limits<T>::min(),std::numeric_limits<T>::max());
}
//produce floating point values:
auto num1 = GetRandom<float>();
auto num2 = GetRandom<float>();
auto num3 = GetRandom<float>();
//...
我有没有可能得到一个 NaN
、Inf
或 -Inf
?
最佳答案
让我们考虑一下std::uniform_real_distribution
产生。
Produces random floating-point values i, uniformly distributed on the interval [a, b)
所以,这介于 std::numeric_limits<foat>::min()
之间和 std::numeric_limits<float>::max()
,包括前者,但不包括后者。这些限制返回什么值?他们返回 FLT_MIN
和 FLT_MAX
分别。那么,那些是什么?
minimum normalized positive floating-point number
maximum representable finite floating-point number
因为 {positive,negative} 无穷大和 NaN 都不在有限数的范围内,所以不会生成它们。
正如 Christopher Oicles 所指出的,请注意 FLT_MIN
并推而广之,std::numeric_limits<foat>::min()
是最小的正可表示值。
正如 Chris Dodd 所指出的,如果 [min, max)
的范围超过 std::numeric_limits<float>::max()
,那么你会得到未定义的行为,在这种情况下,任何输出,包括生成无穷大都是可能的。
关于c++ - "min to max"均匀实数分布会产生 Inf、-Inf 还是 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36825815/