How to fix Eigen3 setRandom() always producing the same values

Problem

You are using Eigen3’s setRandom() function to randomize the values in a given vector.

However, you notice that the random values generated by setRandom() are always the same.

Example code:

#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;
}

When you run this code multiple times, you get the same output each time:

Random vector:
 0.680375
-0.211234
 0.566198

Solution

Eigen3 just uses rand() from libc, which is, by default always initialized with the same seed.

In order to set a (pseudo-)random seed, you can use the following code snippet:

srand(time(0));  // Set a random seed based on the current time

Note that this specific seed will only change once every second.

Full example

#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;
}