Python random use both state and seed?

1.1k views Asked by At

Seeding Python's built-in (pseudo) random number generator will allows us to get the same response each time we use that seed -- documentation here. And I've heard saving the internal state of the generator reduces the likelihood of repeating values from previous inputs. Is this necessary? That is, is getState() and setState() in the below code unnecessary in order to get the same results every time I seed with "foo"?

import random
...
state = random.getstate()
random.seed("foo")
bitmap = random.sample(xrange(100), 10)
random.setstate(state)
return bitmap
2

There are 2 answers

0
ali_m On BEST ANSWER

No, setting either the seed or the state is sufficient:

import random

# set seed and get state
random.seed(0)
orig_state = random.getstate()

print random.random()
# 0.8444218515250481

# change the RNG seed
random.seed(1)
print random.random()
# 0.13436424411240122

# setting the seed back to 0 resets the RNG back to the original state
random.seed(0)
new_state = random.getstate()
assert new_state == orig_state

# since the state of the RNG is the same as before, it will produce the same
# sequence of pseudorandom output
print random.random()
# 0.8444218515250481

# we could also achieve the same outcome by resetting the state explicitly
random.setstate(orig_state)
print random.random()
# 0.8444218515250481

Setting the seed is usually more convenient to do programatically than setting the RNG state explicitly.

2
hajtos On

Setting any of the seed or the state is sufficient to make the randomizing repeatable. The difference is that the seed can be arbitraly set in the code, like in your example, with "foo", while the getstate() and setstate() may be used to get the same random sequence twice, with the sequence still being non-deterministic.