为什么 Python random 生成相同的数字?

编程入门 行业动态 更新时间:2024-10-23 23:28:55
本文介绍了为什么 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 生成相同的数字?

本文发布于:2023-11-30 00:41:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648153.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   Python   random

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!