1

Following two version code should have given the same output. Looks like np.random.seed need to be called every time. Is it correct?

Is there any way to set seed once so that same random number generated everytime

np.random.seed(0)
for _ in range(10):
    print(np.random.randint(low=1, high=100))

Output: 45 48 65 68 68 10 84 22 37 88

for _ in range(10):
    np.random.seed(0)
    print(np.random.randint(low=1, high=100))

Output: 45 45 45 45 45 45 45 45 45 45

Shiv
  • 369
  • 2
  • 13
  • 1
    Er.. in the first version you set the seed once and then repeatedly request a random value, in the second you set the seed on every iteration and then request a random value which will be same every time, what are you expecting? – EdChum Jun 27 '18 at 12:08
  • well, no. if you seed right before randint you get the same value all the time – Jean-François Fabre Jun 27 '18 at 12:08
  • 2
    "Following two version code should have given the same output." why? – ayhan Jun 27 '18 at 12:11
  • 1
    The two code blocks should not give the same output. Check this answer for a nice explanation of what np.random.seed(0) does: https://stackoverflow.com/questions/21494489/what-does-numpy-random-seed0-do – Ani Jun 27 '18 at 12:12
  • I have edited the question to add - "Is there any way to set seed once so that same random number generated evrytime" – Shiv Jun 27 '18 at 12:18
  • @Shiv, Then what is the point of using random number generatorm at each step. You can just do `a = np.random.randint()` once and use this variable afterwards. – Seljuk Gulcan Jun 27 '18 at 12:21
  • @Seljuk , The need is there so that we set once in global header file and all team member will get same random number everytime. – Shiv Jun 27 '18 at 12:30
  • FYI: If you use a random-ish value to seed np.random this wouldn't happen. For example: with `from timeit import default_timer as tmr` and `np.random.seed(int(tmr()*100000) % 11)` you'll get (seemingly) random values based on the current time even if you seed the RNG before every call to `randint`. – meissner_ Jun 27 '18 at 12:31

1 Answers1

2

Unless you are using a cryptographically secure random number generator, random numbers are not really random. You are using a pseudo random number generator, which means you are iterating over a fixed table of predefined numbers. Seeding the random number means choosing the entry in that table you want to use first. Seeding it every time before you create a random number to the same position means you will always get the same number.

Sefe
  • 13,731
  • 5
  • 42
  • 55