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?
- 4"Is this the right practice?" for what? Repeatability? Seeding the RNG is so you can get repeatable results.roganjosh– roganjosh2017-02-06 22:13:57 +00:00Commented Feb 6, 2017 at 22:13
2 Answers
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.
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.