Search code examples
pythonrandom-walk

Seeds in relation to random walks in python


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!


Solution

  • 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.