c++ - "min to max"均匀实数分布会产生 Inf、-Inf 还是 NaN?

标签 c++ random floating-point nan uniform-distribution

如果我按以下方式生成浮点值:

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>();
//...

我有没有可能得到一个 NaNInf-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_MINFLT_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/

相关文章:

c++ - 为什么 printf ("%.2f", (double) 12.555) 返回 12.55?

floating-point - 如何确定 double 的最小显着变化

python - 控制数字是否在 python 中向上或向下舍入

c++ - 我们什么时候应该选择其他IPC而不是直接内存访问来进行线程间通信

thread-safety - 线程安全的统一随机数生成器

random - 不重复的随机数

c++ - 如何限制C++中rand函数生成的数字

C++ 编译器在封装行为上存在分歧——哪一个做对了?

c++ - 对短字符串编码的有理数执行算术运算时 float 的简单替代方法

c++ - 为什么 cout<<hex 语句使其余部分仅以十六进制格式打印