user288609
user288609

Reputation: 13015

Seeding Python's random number generator

I am using irand=randrange(0,10) to generate random numbers in a program. This random number generator is used multiple times in the code. At the beginning of the code, I initiate the seed with random.seed(1234). Is this the right practice?

Upvotes: 0

Views: 1535

Answers (2)

Chris Mueller
Chris Mueller

Reputation: 6680

Seeding the random number generator at the beginning will ensure that the same random numbers are generated each time you run the code. This may or may not be 'the right practice' depending on how you plan to use the random numbers.

import random

# Initial seeding
random.seed(1234)
[random.randrange(0, 10) for _ in range(10)]
# [7, 1, 0, 1, 9, 0, 1, 1, 5, 3]

# Re-seeding produces the same results
random.seed(1234)
[random.randrange(0, 10) for _ in range(10)]
# [7, 1, 0, 1, 9, 0, 1, 1, 5, 3]

# Continuing on the same seed produces new random numbers
[random.randrange(0, 10) for _ in range(10)]
# [0, 0, 0, 5, 9, 7, 9, 7, 2, 1]

If you do not seed the random number generator at the beginning of your code, then it is seeded with the current system time which will ensure that it produces different random numbers each time you run the code.

Upvotes: 5

Krzysiek Przekwas
Krzysiek Przekwas

Reputation: 138

As documentation say, when you use random.seed you have two options:

random.seed() - seeds from current time or from an operating system specific randomness source if available

random.seed(a) - hash(a) is used instead as seed

Using time as seed is better practice if you want to have different numbers between two instances of your program, but for sure is much harder to debug.

Using hardcoded number as seed makes your random numbers much more predictable.

Upvotes: 2

Related Questions