dada
dada

Reputation: 1493

Argument 1234 in numpy.random.RandomState

I came across this line in a code :

numpy_rng = numpy.random.RandomState(1234)

I've seen in the documentation that numpy.random.RandomState is sort of a library in which one can find many probability distributions. I don't understand the argument 1234 however. Someone please explain ?

Upvotes: 1

Views: 2721

Answers (2)

Eric Appelt
Eric Appelt

Reputation: 2973

The statement:

r = numpy.random.RandomState(1234)

creates a Mersenne Twister random number generator, and binds it to the name r. The Mersenne Twister is a very useful algorithm for generating pseudorandom numbers that are suitable for large scale scientific simulations.

The parameter you pass to numpy.random.RandomState is the seed for the generator, which specifies the starting point for a sequence of pseudorandom numbers. If you seed two different generators with the same thing, you will get the same sequence of results. The uniform() method returns a pseudorandom number between zero and one. Observe:

>>> import numpy.random
>>> r = numpy.random.RandomState(1234)
>>> r.uniform()
0.1915194503788923
>>> r.uniform()
0.6221087710398319

>>> r2 = numpy.random.RandomState(1235)
>>> r2.uniform()
0.9537625822517408
>>> r2.uniform()
0.9921264707372405

>>> r3 = numpy.random.RandomState(1234)
>>> r3.uniform()
0.1915194503788923
>>> r3.uniform()
0.6221087710398319

Saving the value of the seed you used to construct the RandomState object will allow you to rerun a simulation with the same sequence of pseudorandom numbers later.

Upvotes: 2

Freyja
Freyja

Reputation: 40804

RandomState is a pseudorandom number generator, which means that it can't generate truly random numbers, but only numbers that "look" random. To do this, you need to give it some initial "seed" that it can use to generate the numbers.

The argument you're referring to is the seed; it should preferrably be unique to each function call, since if it's called with the same seed twice, it will generate the exact same sequence of numbers.

Upvotes: 1

Related Questions