我只是玩了一下 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;
}
最佳答案
除了 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);});
这也允许使用更复杂的分布,例如正态分布。
关于c++ - MatrixXf::Random 总是返回相同的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21292881/