0

What’s the purpose of this seed when running this for loop?

import numpy as np 
np.random.seed(123)
outcomes = []
for x in range(10):
    coin = np.random.randint(0,2)
    if coin == 0:
        outcomes.append(“heads”)
    else:
        outcomes.append(“tails”)
print(outcomes)

From what I understand, sees saves the outcome of a random function. Is the seed function only used once in this example? If so, what’s the point of including it? I appreciate the help!

saberfan7
  • 35
  • 6
  • This is guaranteed to be a duplicate but I'm too lazy to look. I encourage you search around on stack – kevinkayaks Oct 24 '19 at 19:19
  • "sees saves the output" ??? Please explain. – Prune Oct 24 '19 at 19:20
  • 1
    so your example will do the same thing everytime. Without seed, seed is current time or something, so it's _really_ random, and different each time you're running it – Jean-François Fabre Oct 24 '19 at 19:22
  • Yeah I though it’d always return the same thing. It’s in a DataCamp video though, and the output always shows something different (ie heads or tails, not just heads) which is why I was confused. – saberfan7 Oct 24 '19 at 19:24
  • Possible duplicate of [random.seed(): What does it do?](https://stackoverflow.com/questions/22639587/random-seed-what-does-it-do) – b_c Oct 24 '19 at 19:42

1 Answers1

0

Setting seed will produce the same sequence of pseudorandom numbers every time you run the program. So you need to set the seed only once in your code and it will produce same output every time you run your code.

For example, with seed 0, if you are getting the sequence of coin tosses as H, T, T, H, T, H, H then when you run the code again, it will give the same sequence of coin toss. Try running you code with and without setting the seed. You will notice that without seed, sequence will be different in each run.

One of the reason to use seed is to make debugging of the code relatively easier.

Kaushal28
  • 5,377
  • 5
  • 41
  • 72
  • Yes setting seed is per code. So sequence will be generated randomly in a single run but for each run the same sequence will be repeated. – Kaushal28 Oct 25 '19 at 03:45