每次在Python中运行random

每次在Python中运行random

本文介绍了每次在Python中运行random.randint(2,12)都会返回相同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本可以生成2到12之间的10个随机数:

I have a script that generates 10 random numbers between 2 and 12:

repetition = 10
while repetition > 0:
    print(random.randint(2,12))
    repetition = repetition - 1

执行此代码时,会生成10个随机数,但是每次执行该代码时,都会生成相同的10个随机数.即使我在另一台计算机上运行代码,也会发生这种情况!

When this code is executed 10 random numbers are generated, but each time I execute the code the same 10 random numbers are generated. This happens even if I run the code on a different computer!

推荐答案

您应该了解的第一件事是计算机生成的随机数并不是真正的随机数.为了生成伪随机数,计算机使用一种功能,该功能会根据先前的值生成数字( https://en.wikipedia.org/wiki/Random_number_generation ).伪随机数的顺序取决于传递给此函数的第一个值,即种子.

The first thing that you should understand is that computer generated random numbers are not really random. To generate a pseudo-random number, the computer uses a function that generates a number based on a previous value (more details in https://en.wikipedia.org/wiki/Random_number_generation). The sequence of pseudo-random numbers depends on the first value passed to this function, known as seed.

默认情况下,Python的random模块使用的Random类的构造函数(__init__)中,种子由操作系统定义.这通常基于当前系统时间.如果使用函数random.seed定义了自己的种子,则结果将是确定的.在这种情况下,您将始终获得相同的值.

By default in the Random class' constructor (__init__), used by Python's random module, the seed is defined by the operating system. This is usually based on the current system time. If you defined your own seed using the function random.seed your results will be deterministic. You will always get the same values in this case.

这篇关于每次在Python中运行random.randint(2,12)都会返回相同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 07:57