Amal K
Amal K

Reputation: 4874

Why does the Python random.random() give a different value if the previously generated value is explicitly set as the new seed?

I have read that the random module in Python uses the previously generated value as the seed except for the first time where it uses the system time. (https://stackoverflow.com/a/22639752/11455105, https://pynative.com/python-random-seed/) If this is true, why don't I get the same value when I explicitly set the previously generated value as the new seed like this:

random.seed(random.randint(1, 100))

The same doesn't work for the random.random() method either.

>>> import random
>>> random.seed(20)
>>> random.randint(1,100)
93
>>> random.randint(1,100)
88
>>> random.seed(20)
>>> random.randint(1,100)
93
>>> random.randint(1,100)
88
>>> random.seed(20)
>>> random.seed(random.randint(1,100))
>>> random.randint(1,100)
64

Why didn't the last randint() call not give 88?

Thanks in Advance!

Upvotes: 0

Views: 373

Answers (2)

Tim Peters
Tim Peters

Reputation: 70582

Because what you read was false, or you misunderstood what it said. CPython uses the Mersenne Twister generator under the covers, which has a state consuming 19937 bits. What you pass to .seed() is not the new state, but merely a pile of bits which is expanded to a full 19937-bit state via an undocumented (implementation-dependent) algorithm.

Note: if you want to save and restore states, that's what the .getstate() and .setstate() methods are for.

Upvotes: 9

Delgan
Delgan

Reputation: 19617

Python random module does not use the previously generated value as the seed. However, Python uses the Mersenne Twister generator to create pseudo-randomness. This algorithm is deterministic: that implies that it next state (the next generated number) depends on the previous one. This is different from the seed which is a value used to configure the initial state of the generator.

Upvotes: 5

Related Questions