Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python's random.Random.seed work?

Tags:

python

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?

like image 332
Niriel Avatar asked Jan 25 '12 20:01

Niriel


1 Answers

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)]
like image 123
Johan Lundberg Avatar answered Sep 24 '22 05:09

Johan Lundberg