0

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!

1
  • 5
    It's not true. Seeding will initialize some inner state. The inner state always deterministically implies the next random-number. But seeding with some integer x does not mean setting the inner-state like it would look like outputting number x. (the internal state of the MersenneTwister is bigger than some integer. Or else your period would never exceed 2^int-size) Commented Sep 1, 2019 at 17:10

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.