MatrixXf :: Random总是返回相同的矩阵

wlf*_*bck 7 c++ matrix eigen

我刚刚和Eigen玩了一下,注意到MatrixXf :: Random(3,3)总是返回相同的矩阵,第一个总是这个例如:
0.680375 0.59688 -0.329554
-0.211234 0.823295 0.536459
0.566198 -0.604897 -0.444451

这是预期的行为,还是我只是监督一些非常简单的事情?(我对数学库的经验接近于零)

我使用的代码:

for(int i = 0; i < 5; i++) {
        MatrixXf A = MatrixXf::Random(3, 3);
        cout << A <<endl;
}
Run Code Online (Sandbox Code Playgroud)

gga*_*ael 17

是的,这是预期的行为.Matrix :: Random使用标准库的随机数生成器,因此您可以使用srand(unsigned int seed)初始化随机数序​​列,例如:

srand((unsigned int) time(0));
Run Code Online (Sandbox Code Playgroud)

  • 但这并不能解释为什么Matrix :: Random每次都在wlfbck原始代码的循环中返回相同的矩阵.设置种子将确保随机结果是确定性的,但每次调用Matrix :: Random都会产生不同的结果. (2认同)

dav*_*igh 6

取而代之的是,srand您还可以将空表达式与现代C ++ 11随机数生成一起使用:

//see https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution
std::random_device rd;
std::mt19937 gen(rd());  //here you could set the seed, but std::random_device already does that
std::uniform_real_distribution<float> dis(-1.0, 1.0);

Eigen::MatrixXf A = Eigen::MatrixXf::NullaryExpr(3,3,[&](){return dis(gen);});
Run Code Online (Sandbox Code Playgroud)

这也允许使用更复杂的分布,例如正态分布。

  • 这个答案需要认真的投票。它排除了遗留“rand()”功能的所有缺点。 (2认同)