uniform_real_distribution给我的值超出范围
uniform_real_distribution giving me values out of range
我正在运行以下函数,它使用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()
的第一次调用上构造的,然后传递low
和high
。下一次GetRandomDoubleBetween()
distribution
是而不是。
如果使用不同的参数调用GetRandomDoubleBetween()
,则第二次调用将使用第一次调用中的low
和high
。如果要支持不同的参数,请删除static
。
还要注意,您的设计不是线程安全的。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 尝试通过多个向量访问变量时,向量下标超出范围
- 错误:未在此范围内声明'reverse'
- 正在将指针转换为范围
- 使用std::transform将一个范围的元素添加到另一个范围中
- 在基于范围的for循环中使用结构化绑定声明
- 如何计算数据类型的范围,例如int
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 在C++中查找范围的长度
- 如何设置一个范围来提取我想要获得的信息
- 并行用于C++17中数组索引范围内的循环
- 为左值和右值的包装器实现C++范围
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 超出范围时使用对象
- 不计算一个范围内的完美数
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 如何访问超出其块范围的对象?
- 矢量下标超出SFML游戏中的范围