random.seed(): What does it do?

后端 未结 12 952
余生分开走
余生分开走 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:45

    random.seed(a, version) in python is used to initialize the pseudo-random number generator (PRNG).

    PRNG is algorithm that generates sequence of numbers approximating the properties of random numbers. These random numbers can be reproduced using the seed value. So, if you provide seed value, PRNG starts from an arbitrary starting state using a seed.

    Argument a is the seed value. If the a value is None, then by default, current system time is used.

    and version is An integer specifying how to convert the a parameter into a integer. Default value is 2.

    import random
    random.seed(9001)
    random.randint(1, 10) #this gives output of 1
    # 1
    

    If you want the same random number to be reproduced then provide the same seed again

    random.seed(9001)
    random.randint(1, 10) # this will give the same output of 1
    # 1
    

    If you don't provide the seed, then it generate different number and not 1 as before

    random.randint(1, 10) # this gives 7 without providing seed
    # 7
    

    If you provide different seed than before, then it will give you a different random number

    random.seed(9002)
    random.randint(1, 10) # this gives you 5 not 1
    # 5
    

    So, in summary, if you want the same random number to be reproduced, provide the seed. Specifically, the same seed.

提交回复
热议问题