mercredi 20 mars 2019

Efficient way to initialize Eigen Matrix or Vector with random numbers from a specific range?

I am trying to initialise an Eigen vector of integers with random numbers from a specific range. My approach so far has been to create a functor and calling it, it is however problematic in the sense that I need to initialise the random generation in a way that it wont be re-initialised each time.

What would be "the best" way of doing this? Speed-wise.

My code for the functor so far is:

std::mt19937 rd(time(0));
std::default_random_engine gen(rd());

template<typename Scalar>
struct RandomRange {
    RandomRange(const Scalar& low, const Scalar& high) : m_low(low), m_high(high) {}
    const Scalar operator()(const Scalar& high) const {
        std::uniform_int_distribution<> dis(m_low, m_high);
        return dis(gen); }
    Scalar m_low, m_high;
};

And i call it using:

VectorXi testVec = VectorXi(10).unaryExpr(RandomRange<int>(5,100));

A side question is where it would be proper to put such a definition? I am rather new to c++ in general, but I imagine it should be in a header file, but am unsure how it would work with the initialisation of the random number generator.

Best regards!




Aucun commentaire:

Enregistrer un commentaire