我想在 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.0
和 gcc 5.4.0
的断言均失败,因为显然 dist(engine)
的结果是 信息
。我尝试使用 nextafter(a,0)
和 nextafter(b,0)
而不是 a
和 b
时构建 dist
但得到相同的结果。
根据 std::uniform_real_distribution
,方法 min
和 max
应该提供将返回的数字范围,但显然情况并非如此:
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());
同样,两个编译器的结果相同。根据 min
和 max
的定义,上述断言不应被触发。怎么回事?
最佳答案
您的代码表现出未定义的行为,因为它违反了以下条件:
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
andb − a ≤ numeric_limits<RealType>::max()
.
为了回答您的问题,uniform_real_distribution
的范围限制因此是[a/2,b/2]
其中 a
和 b
是 lowest
和 max
您的浮点类型的数字限制值。
关于c++ - 均匀实数分布的范围限制是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40826657/