std::uniform_real_distribution - 获取所有可能的数字
std::uniform_real_distribution - get all possible numbers
我想创建一个能够在[MIN_FLOAT, MAX_FLOAT]
范围内生成随机数的std::uniform_real_distribution
。以下是我的代码:
#include <random>
#include <limits>
using namespace std;
int main()
{
const auto a = numeric_limits<float>::lowest();
const auto b = numeric_limits<float>::max();
uniform_real_distribution<float> dist(a, b);
return 0;
}
问题是当我执行程序时,它被中止了,因为a
和b
似乎是无效的参数。我应该如何解决它?
uniform_real_distribution
的构造函数需要:
a ≤ b
和b − a ≤ numeric_limits<RealType>::max()
.
最后一个对您来说是不可能的,因为 lowest
和 max
之间的差异 ,根据定义,必须大于 max
(并且几乎可以肯定是 INF)。
有几种方法可以解决此问题。正如内森指出的那样,最简单的就是只使用uniform_real_distribution<double>
.除非double
您的实现无法存储float
的范围(并且IEEE-754 Float64可以存储Float32的范围),否则这应该可以工作。你仍然会传递float
的numeric_limits
,但由于分布使用double
,它可以处理增加范围的数学运算。
或者,您可以将uniform_real_distribution<float>
与布尔uniform_int_distribution
(即在 0 和 1 之间进行选择的布尔)组合在一起。您的实际分布应该超过正数,最多 max
.每次你从真实分布中得到一个数字时,也从 int 分布中得到一个。如果整数为 1,则取反实际值。
略高于其他数字的概率,因为正零和负零是一回事。
相关文章:
- 有可能在Armadillo中复制MATLAB circshift方法吗
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 有可能使shared_ptr协变吗
- 有可能在信号处理程序中设置promise吗
- 是否有必要获取锁并在不需要唤醒线程时通知condition_variable?
- 是否有可能实现O(N)时间和O(1)空间解决方案,以实现C++中的字符串循环移位
- 是否有可能构建面向Linux和Windows的.Net Core C++ / CLI应用程序?
- 是否有可能使用debug_info获取ELF文件的源代码?
- C++,是否有可能/如何定义在.h和.cpp源文件中调用函数的类构造函数
- 有可能在C++中有类的查找表吗
- 是否有可能让 c++ dll 在后台运行 python 程序并让它填充向量图?如果是这样,如何?
- 是否有可能通过指向另一个未关联的子对象的指针来获取指向一个子对象的指针?
- 某种程度上有可能从手柄中获取hmodule
- 最有可能使用的方法是处理多个键以使用STL容器获取值
- 是否有可能在QtQGraphicsScene中获取顶级项目
- 有可能在线程运行时从它获取数据吗?C++
- 在c++中,是否有可能获取函数的返回类型,以便在不调用该函数的情况下声明该变量?
- 是否有可能从std::string中获取内存(就像string move tor所做的那样)
- 是否有可能通过重复的std::元组的类型名来获取
- c++:是否有可能从重载<<的对象中获取std::string ?操作符