2014-09-30 113 views
0

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

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),这太问题(out of range random number generation in C++ using tr1),我没有真正看到我在做什么错误。

+1

代码是否触发其中一个断言? – NPE 2014-09-30 06:00:41

+0

它可能与浮点比较的常见问题一样简单。 – juanchopanza 2014-09-30 06:02:35

+0

@juanchopanza他给出了一个值为1.8848149390180773的范围[0.0,1.0)。这比通常浮点问题可能导致的要大得多。 – 2014-09-30 08:11:42

回答

1

定义你的分配:

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

注意static。这意味着distribution会在GetRandomDoubleBetween()的第一个呼叫中生成,lowhigh通过。下一次GetRandomDoubleBetween()distribution不是再次构建。

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

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