bab2min / EigenRand

Fastest Random Distribution Generator for Eigen
https://bab2min.github.io/eigenrand/
MIT License
92 stars 13 forks source link

How to generate different randomized matrices with min and max values? #24

Closed NicoBrug closed 3 years ago

NicoBrug commented 3 years ago

I use the library to generate randomized arrays. I had 2 questions: Why when I do MatrixXd m{rows,cols}; Rand::Vmt19937_64 urng{ 42 }; Rand::balancedLike(m, urng); m = Rand::balancedLike(m, urng); it always returns the same matrix with the same values.

And my other question: is it possible to choose min and max values to generate random numbers?

bab2min commented 3 years ago

Hi @NicoBrug

MatrixXd m{rows,cols}; 
Rand::Vmt19937_64 urng{ 42 }; 
m = Rand::balancedLike(m, urng);

It always returns the same result because the seed of random number generator is fixed as 42. If you want to get different results every run, you should pass the seed with different value like:

MatrixXd m{rows,cols}; 
auto seed = std::random_device{}(); // it requires #include <random>
Rand::Vmt19937_64 urng{ seed }; 
m = Rand::balancedLike(m, urng);

For your second question: You can change the minimum and maximum values of distribution with some arithmetic:

MatrixXd m{rows,cols}; 
double min_v = -2, max_v = 3;
Rand::Vmt19937_64 urng{ 42 }; 
m = ((Rand::balancedLike(m, urng).array() + 1) * (max_v - min_v) / 2 + min_v).matrix();

It will generate a matrix with uniform random reals in [-2, 3]. But it looks ugly, so in the next update I'll add a function to set the min/max value more simply.

bab2min commented 3 years ago

A new function overloading balanced and balancedLike for arbitrary range [a, b] was added at version 0.3.5.

andrewfowlie commented 1 year ago

@bab2min I would find an example demonstrating the use of std::random_device helpful in the getting started section of the docs (https://bab2min.github.io/eigenrand/v0.5.0/en/getting_started.html). It's not the first time I've used C++11 style random number generation, but still somehow didn't find this obvious.