[Numpy-discussion] match RNG numbers with R?

Yaroslav Halchenko lists at onerussian.com
Sun Apr 6 21:59:42 EDT 2014

On Sun, 06 Apr 2014, Sturla Molden wrote:
> > R, Python std library, numpy all have Mersenne Twister RNG implementation.  But
> > all of them generate different numbers.  This issue was previously discussed in
> > https://github.com/numpy/numpy/issues/4530 :  In Python, and numpy generated
> > numbers are based on using 53 bits of two 32 bit random integers generated by
> > the algorithm (see below).    Upon my brief inspection, original 32bit numbers
> > are nohow available for access neither in NumPy nor in Python stdlib
> > implementation.

> NumPy uses the Randomkit library. The source is here:

> https://github.com/numpy/numpy/tree/master/numpy/random/mtrand

> It very easy to modify to produce whatever result you want. You can build
> it separately from NumPy.

> RandomState.bytes and np.random.bytes gives you the original random bytes
> in little endian order. It basically calles rk_fill in Randomkit and then
> unpacks the 32 bit random integer into four bytes. Just view it as
> dtype='<u4' to see the original 32-bit unsigned integers:

> a = np.random.bytes(4*n).view(dtype='<u4')

Hi Sturla,

Thanks a lot for helping out!  With some tune up (.view doesn't work
here since bytes() output is a string...)  getting yet another random

>> np.random.seed(1); [int(np.asscalar(np.fromstring(np.random.bytes(4), dtype='<u4'))*10/float(0xFFFFFFFF+1)) for x in range(10)]
[4, 9, 7, 9, 0, 1, 3, 9, 1, 2]

so I would assume that the devil is indeed in R post-processing and would look
into it (if/when get a chance).

Yaroslav O. Halchenko, Ph.D.
http://neuro.debian.net http://www.pymvpa.org http://www.fail2ban.org
Senior Research Associate,     Psychological and Brain Sciences Dept.
Dartmouth College, 419 Moore Hall, Hinman Box 6207, Hanover, NH 03755
Phone: +1 (603) 646-9834                       Fax: +1 (603) 646-1419
WWW:   http://www.linkedin.com/in/yarik        

More information about the NumPy-Discussion mailing list