1

I read that if you specify seed value it generates same random numbers. In the following code although I have specified seed value but in for loop rf is generating different random values. But if I omit for loop and run this code twice rf generates same random values. Can someone please explain this why is it so?

SEED= 1234567
s=np.random.seed(SEED)
print(s)
for i in range(3):
   rf=np.random.uniform(-1.0,1.0,(3,4))
   print(rf)
herry
  • 155
  • 10
  • You need to define the seed every time that you are generating a random number. By defining the seed to be the same number, the generated random numbers become the same. – LoMaPh Sep 10 '18 at 03:01
  • So in the above code I have fixed seed value to 1234567 and I am expecting that rf should be same when loop runs 3 times – herry Sep 10 '18 at 03:04
  • Try moving `np.random.seed(SEED)` to the *top* of the loop. – wwii Sep 10 '18 at 03:09
  • If I move np.random.seed(SEED) inside loop it generates same numbers 3 times. . Why specifying it once outside loop doesn't show same behaviour – herry Sep 10 '18 at 03:12

1 Answers1

5

Yes. When you call random.seed(), it sets the random seed. The sequence of numbers you generate from that point forwards will always be the same.

The thing is, you're only set the seed once, and then you're calling np.random.uniform() three times. That means you're getting the next three numbers from your random.seed(). Of course they're different – you haven't reset the seed in between. But every time you run the program, you'll get the same sequence of three numbers, because you set the seed to the same thing before generating them all.

Setting the seed only affects the next random number to be generated, because of how pseudo-random number generation (which np.random uses) works: it uses the seed to generate a new random number deterministically, and then uses the generated number to set a new seed for the next number. It effectively boils down to getting a really really long sequence of random numbers that will, eventually, repeat itself. When you set the seed, you're jumping to a specified point in that sequence – you're not keeping the code there, though.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • Nice answer. OP could get the desired result by sticking the call to `seed` inside the loop. – Mad Physicist Sep 10 '18 at 03:09
  • Whta do you mean by "every time you run programe. you will get same sequence of three numbers" ? – herry Sep 10 '18 at 03:15
  • Say you run the program once, and it prints out "0.77, -0.36, 0.52". Then, you run the program again, and it prints out the same three numbers. Then you run it a third time and it prints out the same three numbers. – Green Cloak Guy Sep 10 '18 at 03:18