Reputation: 2705
I'm used to typing random.randrange
. I'll do a from random import Random
to spot the error from now on.
For a game involving procedural generation (nope, not a Minecraft clone :p) I'd like to keep several distinct pseudo-random number generators:
The rationale being that I want to be able to reproduce the first, so I don't want the second one to interfere.
I thought random.Random
was made for that. However something is puzzling me:
import random
rnd = random.Random()
rnd.seed(0)
print [random.randrange(5) for i in range(10)]
rnd.seed(0)
print [random.randrange(5) for i in range(10)]
produces two different sequences. When I do rnd = random
then things work as expected, but I do need several generators.
What am I missing?
Upvotes: 9
Views: 9850
Reputation: 27068
It works almost exactly as you tried but the rnd.seed() applies to the rnd object
just use
rnd = random.Random(0) # <<-- or set it here
rnd.seed(7)
print [rnd.randrange(5) for i in range(10)]
or by setting the global seed, like this:
random.seed(7)
print [random.randrange(5) for i in range(10)]
Upvotes: 13
Reputation: 16327
Pass the seed to the constructor of Random
:
>>> import random
>>> rnd = random.Random(0)
>>> [rnd.randint(0, 10) for i in range(10)]
[9, 8, 4, 2, 5, 4, 8, 3, 5, 6]
>>> rnd = random.Random(0)
>>> [rnd.randint(0, 10) for i in range(10)]
[9, 8, 4, 2, 5, 4, 8, 3, 5, 6]
>>> rnd = random.Random(1)
>>> [rnd.randint(0, 10) for i in range(10)]
[1, 9, 8, 2, 5, 4, 7, 8, 1, 0]
Upvotes: 4