random.seed(): What does it do?

后端 未结 12 844
余生分开走
余生分开走 2020-11-22 12:44

I am a bit confused on what random.seed() does in Python. For example, why does the below trials do what they do (consistently)?

>>> i         


        
12条回答
  •  粉色の甜心
    2020-11-22 13:46

    # Simple Python program to understand random.seed() importance
    
    import random
    
    random.seed(10)
    
    for i in range(5):    
        print(random.randint(1, 100))
    

    Execute the above program multiple times...

    1st attempt: prints 5 random integers in the range of 1 - 100

    2nd attempt: prints same 5 random numbers appeared in the above execution.

    3rd attempt: same

    .....So on

    Explanation: Every time we are running the above program we are setting seed to 10, then random generator takes this as a reference variable. And then by doing some predefined formula, it generates a random number.

    Hence setting seed to 10 in the next execution again sets reference number to 10 and again the same behavior starts...

    As soon as we reset the seed value it gives the same plants.

    Note: Change the seed value and run the program, you'll see a different random sequence than the previous one.

提交回复
热议问题