【发布时间】:2018-09-01 13:21:28
【问题描述】:
我想创建一个MxN 数组(N 维空间中的M 粒子),在上下边界内填充随机数。我有一个看起来像这样的工作 python 代码:
# upper_bound/lower_bound are arrays of shape (dim,)
positions = np.random.rand(num_particle,dim)*(upper_bound-lower_bound)+lower_bound
每一行代表一个粒子,每一列代表问题空间中的一个维度。所以upper_bound 和lower_bound 适用于每一列。现在我想把上面的代码翻译成c++,我有这样的东西:
#include <iostream>
#include <vector>
#include <random>
#include <algorithm>
#include <ctime>
typedef std::vector<double> vect1d;
std::vector<vect1d> positions;
for (int i=0; i<num_particle; i++){
std::mt19937_64 generator(static_cast<std::mt19937::result_type>(time(0)));
std::uniform_real_distribution<double> distribution(0,1);
vect1d pos(dimension);
std::generate(pos.begin(),pos.end(),distribution(generator));
positions[i] = pos;
}
我的问题:
它给出了关于生成器的错误,所以我不确定我是否正确设置它。我也不确定如何使用
std::generator。我正在尝试它,因为我查看了其他类似的帖子,它似乎允许我一次生成多个随机数,所以我不必为每个元素运行 MxN 次。这是真的吗?如何正确使用?在 python 中,我可以通过矢量化和广播来操作 numpy 数组。在 C++ 中最“矢量化”的方法是什么?
上面的(不正确的)代码只创建了0到1之间的随机数,但是如何在python版本中合并
lower_bound和upper_bound呢?我知道我可以更改distribution(0,1)中的值,但问题是每个维度的限制可能不同(因此每列可以有不同的有效范围),那么考虑到生成随机数的最有效方法是什么每个维度的范围?
谢谢
【问题讨论】:
-
你设置
positions的大小吗?如果为空,分配给positions[i]的是UB。 -
你在使用 Visual Studio 吗?
-
如何使用生成器:
std::generate(pos.begin(), pos.end(), [&]() { return distribution(generator); }); -
为了将来参考,最好将这些类型的多问题拆分为单独的问题。增加获得答案的机会。
-
这可能对
3.stackoverflow.com/questions/52021277/… 有帮助 需要使用浮点参数来获得浮点结果,也就是random_number(0.0, 1.0)。