将“最小到最大"均匀的实际分布会产生Inf,-Inf或NaN吗? [英] Will "min to max" uniform real distribution produce Inf,-Inf, or NaN?
问题描述
如果我要通过以下方式生成浮点值:
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
生成的内容.
产生随机浮点值i,它们均匀分布在间隔[a,b)
因此,它介于std::numeric_limits<foat>::min()
和std::numeric_limits<float>::max()
之间,包括前者,但不包括后者.这些限制返回什么值?它们分别返回FLT_MIN
和FLT_MAX
.好吧,那是什么?
最小归一化的正浮点数
最大可表示的有限浮点数
由于{positive,negative} infinity和NaN都不在有限数范围内,因此不会生成它们.
如克里斯托弗·奥里克斯(Christopher Oicles)所指出的那样,请注意,FLT_MIN
以及由此扩展的std::numeric_limits<foat>::min()
是最小的正可表示值.
如Chris Dodd所指出的,如果 [min, max)
的范围超过std::numeric_limits<float>::max()
,那么您将获得未定义的行为,在这种情况下,包括生成无穷大在内的任何输出都是可能的. /p>
If I were to produce floating point values in the following way:
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>();
//...
Is it possible that I will ever get back a NaN
, Inf
, or -Inf
?
Let's consider what std::uniform_real_distribution
generates.
Produces random floating-point values i, uniformly distributed on the interval [a, b)
So, that's between std::numeric_limits<foat>::min()
and std::numeric_limits<float>::max()
, including former, but excluding latter. What values do those limits return? They return FLT_MIN
and FLT_MAX
respectively. Well, what are those?
minimum normalized positive floating-point number
maximum representable finite floating-point number
Since neither {positive,negative} infinity, nor NaN is within the range of finite numbers, no they're not generated.
As pointed out by Christopher Oicles, pay attention that FLT_MIN
and by extension, std::numeric_limits<foat>::min()
is the smallest positive representable value.
As pointed out by Chris Dodd, if the range of [min, max)
exceeds std::numeric_limits<float>::max()
, then you would get undefined behaviour and in that case any output, including generating infinity would be possible.
这篇关于将“最小到最大"均匀的实际分布会产生Inf,-Inf或NaN吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!