# Reproducing MATLAB's randn

Gentlemen! I have to reproduce MATLAB random normal generator (randn) with some fixed seed.

Also, I have to reproduce it in an external script, without MATLAB itself. Has anyone done this? What random normal generator implementation is better to use?

P.S. Preferred languages are Python and C/C++, but other languages may be useful too.

• You can save/set the state of Matlab's random number generator with rng. Using it, you can configure Matlab to use the Mersenne Twister, which has implementations in many languages. However, the MT generates a uniform distribution; I don't know the details of how Matlab converts it to normal. – MBaz Mar 24 '15 at 16:13
• Well, I know about rng(), I want to emulate MATLAB randn generator outside MATLAB. I need it for some of my tests. I know, that I can just save pre-calculated noise data, but it looks like a perversion. – Felix Mar 24 '15 at 16:53
• @jojek How is that the same question? – endolith Mar 25 '15 at 0:12
• do you need to reproduce randn() precisely? to do the very same thing MATLAB does with the very same seed values? – robert bristow-johnson May 24 '15 at 6:28

Its hard to say without knowing exactly how Matlab's randn is processed from the RNG you're using and how Matlab uses the seed.

The most reasonable way is to save pre-calculated noise data or just deal with a different random number generator (Boost among others has a normal random number generator, and you can pull it into Matlab to use via MEX if necessary).

• +1 even if we know that MATLAB uses the Mersenne Twister (i think that's only one mode), we don't know exactly what they do with the seed or seeds. and we don't know how they make a Gaussian random variable out if it. they could pass the uniform RV through a non-linear mapping or they could generate a dozen uniform RVs, add them up, and then subtract 6 to get something that is close to Gaussian. there are all sorts of ways of making a uniform RV into Gaussian. – robert bristow-johnson May 24 '15 at 6:27

python: using the numpy plugin (numpy, scipy, matplotlib will make python incredibly matlab like) has the function already defined

numpy.random.normal

I don't know if this is 'cheating' but unless this is a school project where you must explicitly write out an algorithm I would assume it's ok. I say why reinvent the wheel if you don't need to?

edit

as endolith pointed out numpy provides another predefined that is even better suited for your situation

numpy.random.randn

• thanks for that info. I suppose both are equivalent when you supply numpy.random.normal with mean=0 and std=1 but your suggestion would be more correct, thanks – andrew Mar 25 '15 at 2:34