Why Python random is generating the same numbers?

半腔热情 提交于 2021-02-17 02:03:31

问题


I wrote this code for my homework:

import random
score=[]
random.seed(1)
for i in range(0,100):
    score.append(random.randrange(0,21))

for k in range(20, -1, -1):
    print("Who get %2d score in test? : "%(k), end='')
    while score.count(k)!=0:
        j = score.index(k)
        print("%3s" % (j), end="  ")
        score.remove(k)
        score.insert(j,25)
    print("\n")

I ran it on my computer many times and the results were the same. Ironically, in other computers, the results are different from my computer, but also also getting repeated at each execution.

What's wrong with my code?


回答1:


random.seed(n) starts the random number generator off from the same point each time the program is run.

That is you get the same sequence of random numbers. It is like taking a video of a dice being thrown and then playing it back each time - the numbers are random (pseudo random to be accurate) but you are playing back the sequence.

This is useful for testing, for example: you can run different versions of your program with the same random numbers, so you are sure differences in your results are only due to the program, not to chance.

Take random.seed out and you will get a sequence that starts at a random location. (On most computers, if you don't specify a seed, the clock time the program started is implicitely used as seed.)




回答2:


When you write

random.seed(1)

You are saying to always use the same sequence of randomly generated numbers, therefore you always have the same results. It happens when I run it on my computer too.

Simply remove the line and you should have different randomly generated numbers every time.

See this answer for an explanation of the seed.

And the python documentation for the random library



来源:https://stackoverflow.com/questions/49812521/why-python-random-is-generating-the-same-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!