user7465838
user7465838

Reputation:

Generating Gaussian Noise

I created a function that is suppose to generate a set of normal random numbers from 0 to 1. Although, it seems that each time I run the function the output is the same. I am not sure what is wrong.

Here is the code:

MatrixXd generateGaussianNoise(int n, int m){
    MatrixXd M(n,m);
    normal_distribution<double> nd(0.0, 1.0);
    random_device rd;
    mt19937 gen(rd());
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            M(i,j) = nd(gen);
        }
    }
    return M;
}

The output when n = 4 and m = 1 is

0.414089
0.225568
0.413464
 2.53933

I used the Eigen library for this, I am just wondering why each time I run it produces the same numbers.

Upvotes: 0

Views: 2276

Answers (1)

cnettel
cnettel

Reputation: 1024

From: http://en.cppreference.com/w/cpp/numeric/random/random_device

std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence.

Thus, I think you should look into what library stack you are actually using here, and what's known about random_device in your specific implementation.

I realize that this then might in fact be a duplicate of "Why do I get the same sequence for every run with std::random_device with mingw gcc4.8.1?".

Furthermore, it at least used to be that initializating a new mt19937 instance would be kind of expensive. Thus, you have performance reasons in addition to quality of randomness to not re-initalize both your random_device and mt19937 instance for every function call. I would go for some kind of singleton here, unless you have very clear constraints (building in a library, unclear concurrency) that would make that an unuistable choice.

Upvotes: 3

Related Questions