0

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?

1
  • 4
    "Is this the right practice?" for what? Repeatability? Seeding the RNG is so you can get repeatable results. Commented Feb 6, 2017 at 22:13

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is the better answer compared to the accepted.
"which will ensure that it produces different random numbers each time you run the code." Unless you happen to run several processes where it might ensure exactly the opposite.
2

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.

1 Comment

"Using time as seed is better practice" this is short sighted. For e.g. nimerical simulations it is absolutely not a better peactice.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.