David
David

Reputation: 871

Are the implementations of the C++ normal_distribution and MATLAB's randn consistent?

I'm using Mersenne twister in order to have consistent random values between projects in Matlab and C++. But I've not been able to get consistent normally distributed pseudo-random values when using randn or C++11's normal_distribution.

Here's the C++:

void main()
{
    unsigned int mersenneSeed = 1977;
    std::mt19937_64 generator; // it doesn't matter if I use the 64 or the std::mt19937
    generator.seed(mersenneSeed);
    std::normal_distribution<double> normal; // default is 0 mean and 1.0 std
    double temp = normal(generator); 
        // results 1.4404780513814264 for mt19937_64 and 1.8252033038258377 for mt19937
}

Here's the Matlab:

rng(1977) % default Matlab uses mersenne twister
randn()   % default is 0 mean and 1.0 std

I'm using Matlab 2013b and Visual Studio Express 2013. Am I doing something wrong with the C++11 normal distribution?

Upvotes: 0

Views: 1556

Answers (1)

A. Donda
A. Donda

Reputation: 8477

The Mersenne twister by itself only produces 32-bit integer random numbers. The most likely explanation for the discrepancy you observe is the way how these uniformly distributed integers are transformed into normally distributed double-precision floating point numbers.

Since the documentation of randn does not explain this transformation and the source code is not available (it is a built-in function), it is hard to say anything more about this without reverse-engineering. (According to Casey's comment, the same seems to hold for the C++ side of things.)

The easiest way to achieve consistency probably would be to generate random numbers in C++ or Matlab, save the results, and load them as needed. An alternative would be to write your own Matlab random number function in C++ as a MEX file (using C++'s normal_distribution), and use this function in Matlab instead of randn.

Upvotes: 1

Related Questions