如何修复 Eigen3 setRandom() 总是产生相同的值
问题
你正在使用 Eigen3 的 setRandom() 函数来随机化给定向量中的值。
但是,你注意到 setRandom() 生成的随机值总是相同的。
示例代码:
eigen_setrandom_same_values.cpp
#include <iostream>
#include <Eigen/Dense>
int main() {
Eigen::VectorXd v = Eigen::VectorXd::Zero(3);
v.setRandom();
std::cout << "Random vector:" << std::endl << v << std::endl;
return 0;
}当你多次运行此代码时,每次都会得到相同的输出:
eigen_setrandom_output.txt
Random vector:
0.680375
-0.211234
0.566198解决方案
Eigen3 只是使用 libc 中的 rand(),默认情况下总是用相同的种子初始化。
为了设置(伪)随机种子,你可以使用以下代码片段:
eigen_setrandom_seed.cpp
srand(time(0)); // Set a random seed based on the current time
请注意,此特定种子每秒只会更改一次。
完整示例
eigen_setrandom_full.cpp
#include <iostream>
#include <Eigen/Dense>
#include <ctime>
int main() {
Eigen::VectorXd v = Eigen::VectorXd::Zero(3);
srand(time(0)); // Set a random seed based on the current time
v.setRandom();
std::cout << "Random vector:" << std::endl << v << std::endl;
return 0;
}Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow