我正在运行以下函数,它使用 Visual Studio 2012 为我提供范围 [low, high] 之外的值(我得到的随机数结果高于我给出的最高值 - 例如 1.8848149390180773范围 [0.0, 1.0)):
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 问题 ( out of range random number generation in C++ using tr1 ),但我并没有真正看到我做错了什么。
最佳答案
您定义您的分布:
static std::uniform_real_distribution<double> distribution(low, high);
注意 static
。这意味着 distribution
是在第一次调用 GetRandomDoubleBetween()
时构建的,随后传递了 low
和 high
。下一次 GetRandomDoubleBetween()
distribution
不会再次构造。
如果您使用不同的参数调用 GetRandomDoubleBetween()
,则第二次调用将使用第一次调用的 low
和 high
。如果您想支持不同的参数,请删除 static
。
另请注意,您的设计不是线程安全的。
关于c++ - uniform_real_distribution 给我超出范围的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26113724/