均匀实分布的范围限制是多少?

qua*_*ant 1 c++ random c++14

我想在double浮点范围的数字限制内创建一个随机数.我觉得这很容易:

#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;                                                                    
}                                                                                   
Run Code Online (Sandbox Code Playgroud)

断言失败,两个clang 3.8.0gcc 5.4.0的,因为很明显的结果dist(engine)inf.我尝试使用nextafter(a,0)nextafter(b,0)不是ab构造时,dist但得到相同的结果.

根据std::uniform_real_distribution,方法,minmax应提供将返回的数字范围,但显然不是这种情况:

std::cout << dist.min() << ", " << dist.max() << std::endl;
Run Code Online (Sandbox Code Playgroud)

这个输出是:

-1.79769e + 308,1.79769e + 308

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

const auto rand = dist(engine);
assert(rand <= dist.max() && rand >= dist.min());
Run Code Online (Sandbox Code Playgroud)

同样,两个编译器的结果相同.根据min和的定义max,上述断言应该触发.这是怎么回事?

krz*_*zaq 7

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

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

explicit uniform_real_distribution(RealType a = 0.0, RealType b = 1.0);
Run Code Online (Sandbox Code Playgroud)

要求: a ? bb ? a ? numeric_limits<RealType>::max().

要回答你的问题,为范围的限制uniform_real_distribution,因此是[a/2,b/2]在那里ablowestmax你的浮点类型的数字限制值.

  • @arman这对我来说也是新的.但是我的gcc总是返回无限的这一事实足以暗示前提条件. (2认同)