std::uniform_real_distribution - 获取所有可能的数字

std::uniform_real_distribution - get all possible numbers

本文关键字:有可能 获取 数字 distribution uniform real std      更新时间:2023-10-16

我想创建一个能够在[MIN_FLOAT, MAX_FLOAT]范围内生成随机数的std::uniform_real_distribution。以下是我的代码:

#include <random>
#include <limits>
using namespace std;
int main()
{
    const auto a = numeric_limits<float>::lowest();
    const auto b = numeric_limits<float>::max();
    uniform_real_distribution<float> dist(a, b);
    return 0;
}

问题是当我执行程序时,它被中止了,因为ab似乎是无效的参数。我应该如何解决它?

uniform_real_distribution的构造函数需要:

a ≤ bb − a ≤ numeric_limits<RealType>::max() .

最后一个对您来说是不可能的,因为 lowestmax 之间的差异 ,根据定义,必须大于 max(并且几乎可以肯定是 INF)。

有几种方法可以解决此问题。正如内森指出的那样,最简单的就是只使用uniform_real_distribution<double> .除非double您的实现无法存储float的范围(并且IEEE-754 Float64可以存储Float32的范围),否则这应该可以工作。你仍然会传递floatnumeric_limits,但由于分布使用double,它可以处理增加范围的数学运算。

或者,您可以将uniform_real_distribution<float>与布尔uniform_int_distribution(即在 0 和 1 之间进行选择的布尔)组合在一起。您的实际分布应该超过正数,最多 max .每次你从真实分布中得到一个数字时,也从 int 分布中得到一个。如果整数为 1,则取反实际值。

这样做的缺点是使零的概率

略高于其他数字的概率,因为正零和负零是一回事。