为什么 Python random 生成相同的数字? [英] Why Python random is generating the same numbers?

查看:87
本文介绍了为什么 Python random 生成相同的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为作业写了这段代码:

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.

我的代码有什么问题?

推荐答案

random.seed(n) 每次程序运行时都会从同一点启动随机数生成器.

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.

取出 random.seed,您将得到一个从随机位置开始的序列.(在大多数计算机上,如果您不指定种子,则程序启动的时钟时间会隐式用作种子.)

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

这篇关于为什么 Python random 生成相同的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆