9

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:

  • one for the generation of the world (landscape, quests, etc.),
  • one for the random events that can happen in the world (such as damage during fight).

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?

1
  • 1
    It actually took me a few minutes to spot that too. Don't feel bad happens to all of us, glad it's solved :) Commented Jan 25, 2012 at 21:00

2 Answers 2

13

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)]
Sign up to request clarification or add additional context in comments.

Comments

4

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]

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.