- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我想在 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/
我需要在半径R的圆内生成一个均匀随机点。 我意识到,通过在区间 [0 ... 2π) 中选择均匀随机的角度,并在区间 (0 ... R) 中选择均匀随机的半径,我最终会得到更多的点朝向中心,因为对于两
我想在一个正方形内生成 N 个点(均匀地)。我怎样才能做到这一点? 最佳答案 非常酷的问题,比我想象的要困难得多,但这就是想法。有关于 n 边形的论文,但我只会做正方形。因此,圆的均匀分布是一个常见问
考虑以下示例: import itertools import numpy as np a = np.arange(0,5) b = np.arange(0,3) c = np.arange(0,7)
SQL Server 将一组值分成 5 组,每组的 sum(count) 应该均匀分布。 表仅包含 2 列 rid 和 count。 create table t1(rid int, count in
我有以下简单的 HTML。 A B C 和 CSS: ul { width: 100%; display: flex; flex-direction:
我是一名优秀的程序员,十分优秀!