4

For the same seed, why does random.random() produce different random values when compared to numpy.random(). My understanding is that they both use the Mersenne Twister to generate random values.

import random as rnd
import numpy as np

rnd.seed(1)
np.random.seed(1)

rnd.random()
np.random.rnd()

0.13436...

0.41702...

Aegir
  • 117
  • 11
  • 1
    Why would you expect them to be the same? Even if both use the same algorithm, there can be small differences in the implementation. For example, how the seed is represent and how it's used might differ. – Ignacio Vergara Kausel Mar 09 '18 at 14:18
  • For example, MATLAB will produce identical values to Numpy when asked for random numbers using the same seed. I am curious as to why the standard library random module does not. – Aegir Mar 09 '18 at 14:20

1 Answers1

12

The random module and numpy.random both use a mt19937 to generate random numbers. Because of this, we can copy the state of one from one generator to the other to see if they have the same underlying implementation.

import random as rnd
import numpy as np

# seed numpy
np.random.seed(1)

# get state from numpy
state = [int(s) for s in list(np.random.get_state()[1])]
state.append(624)
state = tuple(state)
state = (3, tuple(state), None)

# set state for python 
rnd.setstate(state)

print(rnd.random())
print(np.random.rand())

0.417022004702574

0.417022004702574

It looks like the mt19937 engine used gives equivalent results if the state is manually set to be the same. This seems to imply the seed function are implemented differently.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
alexdor
  • 816
  • 5
  • 8