c++ - 均匀实数分布的范围限制是多少?

标签 c++ random c++14

我想在 double float 范围内创建一个随机数。我认为这很容易:

#include <random>                                                                   
#include <cassert>                                                                  
#include <math.h>                                                                

int main()                                                                          
{                                                                                   
    double a = std::numeric_limits<double>::lowest();                               
    double b = std::numeric_limits<double>::max();                                  

    std::default_random_engine engine;                                           

    std::uniform_real_distribution<double> dist(a, b);                           
    assert(std::isfinite(dist(engine))); // this triggers!

    return 0;                                                                    
}                                                                                   

clang 3.8.0gcc 5.4.0 的断言均失败,因为显然 dist(engine) 的结果是 信息。我尝试使用 nextafter(a,0)nextafter(b,0) 而不是 ab 时构建 dist 但得到相同的结果。

根据 std::uniform_real_distribution ,方法 minmax 应该提供将返回的数字范围,但显然情况并非如此:

std::cout << dist.min() << ", " << dist.max() << std::endl;

这个的输出是:

-1.79769e+308, 1.79769e+308

并且,正如预期的那样,以下断言触发,证明了矛盾:

const auto rand = dist(engine);
assert(rand <= dist.max() && rand >= dist.min());

同样,两个编译器的结果相同。根据 minmax 的定义,上述断言不应被触发。怎么回事?

最佳答案

您的代码表现出未定义的行为,因为它违反了以下条件:

N4140 § 26.5.8.2.2 [rand.dist.uni.real]

explicit uniform_real_distribution(RealType a = 0.0, RealType b = 1.0);

Requires: a ≤ b and b − a ≤ numeric_limits<RealType>::max().

为了回答您的问题,uniform_real_distribution 的范围限制因此是[a/2,b/2]其中 ablowestmax您的浮点类型的数字限制值。

关于c++ - 均匀实数分布的范围限制是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40826657/

相关文章:

c++ - 非整数/枚举类型的非类型模板参数的用例?

c++ - 用于 int -> float -> int 往返转换的舍入

c# - 随机数概率

c++ - 梅森捻线机预热与再现性

c++ - 传递泛型函数以对同类类型进行操作

c++ - 将分配器分配给字段 - 我应该将默认分配器创建为全局变量吗?

c++ - 在 C++ 中创建一个不可见的文本文件

c++ - 如何正确地计算浮点对总和

java - 尝试随机生成一个从 000 到 110 的二进制数

c++ - 实现 `to_xstring()` 来合并 `to_string()` 和 `to_wstring()`