uniform_real_distribution给我的值超出范围

uniform_real_distribution giving me values out of range

本文关键字:范围 real distribution uniform 我的      更新时间:2023-10-16

我正在运行以下函数,它使用Visual Studio 2012为我提供了超出[低,高]范围的值(我得到的随机数结果高于我给出的最高值,例如,范围为[0.0,1.0)的1.8848149390180773):

double GetRandomDoubleBetween(double low, double high)
{
    assert(low <= high);
    static std::random_device rd;
    static std::mt19937 rng(rd());
    static std::uniform_real_distribution<double> distribution(low, high);
    double random = distribution(rng);
    assert(random >= low);
    assert(random < high);
    return random;
}

我看到了这个文档链接(http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution)以及这个SO问题(在C++中使用tr1生成超出范围的随机数),我并没有真正意识到我做错了什么。

您定义您的分布:

static std::uniform_real_distribution<double> distribution(low, high);

注意static。这意味着distribution是在GetRandomDoubleBetween()的第一次调用上构造的,然后传递lowhigh。下一次GetRandomDoubleBetween() distribution而不是

如果使用不同的参数调用GetRandomDoubleBetween(),则第二次调用将使用第一次调用中的lowhigh。如果要支持不同的参数,请删除static

还要注意,您的设计不是线程安全的。