c++ - uniform_real_distribution 给我超出范围的值

标签 c++ visual-studio-2012 c++11

我正在运行以下函数,它使用 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() 时构建的,随后传递了 lowhigh。下一次 GetRandomDoubleBetween() distribution 不会再次构造。

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

另请注意,您的设计不是线程安全的。

关于c++ - uniform_real_distribution 给我超出范围的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26113724/

相关文章:

c# - 为我的插件在 "SolutionExplorer\Project\references\MyReference"中选择的项目

c# - 如何使用 Visual Studio 2012 从源代码管理中分离项目?

c++ - 为什么通用模板方法定义与模板类特化不匹配?

c++ - 基于范围的循环 : get item by value or reference to const?

c++ - 如何将二维矩阵的 1 列传递给 C/C++ 中的函数

c++ - 使用 vector 时,pop_back 是否会连同元素一起删除值?

c++ - 代码仅在 Visual Studio 调试中有效,但在 Release模式和 .exe 中均无效

c++ - 默认值输入错误的构造函数不会引发 GCC 7 错误

c# - 可移植类库中的 System.Tuple 在哪里?

c++ - 如何在 GCC 5 中处理双 ABI?