我想在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.0和gcc 5.4.0的,因为很明显的结果dist(engine)是inf.我尝试使用nextafter(a,0)而nextafter(b,0)不是a和b构造时,dist但得到相同的结果.
根据std::uniform_real_distribution,方法,min并max应提供将返回的数字范围,但显然不是这种情况:
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,上述断言不应该触发.这是怎么回事?
您的代码显示未定义的行为,因为它违反了以下条件:
N4140§26.5.8.2.2[rand.dist.uni.real]
Run Code Online (Sandbox Code Playgroud)explicit uniform_real_distribution(RealType a = 0.0, RealType b = 1.0);要求:
a ? b和b ? a ? numeric_limits<RealType>::max().
要回答你的问题,为范围的限制uniform_real_distribution,因此是[a/2,b/2]在那里a和b是lowest和max你的浮点类型的数字限制值.