random.seed():它有什么作用? [英] random.seed(): What does it do?

查看:31
本文介绍了random.seed():它有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 random.seed() 在 Python 中的作用有点困惑.例如,为什么下面的试验会(一致地)做他们所做的事情?

<预><代码>>>>随机导入>>>随机种子(9001)>>>random.randint(1, 10)1>>>random.randint(1, 10)3>>>random.randint(1, 10)6>>>random.randint(1, 10)6>>>random.randint(1, 10)7

我找不到关于此的好的文档.

解决方案

伪随机数生成器通过对值执行一些操作来工作.通常,此值是生成器生成的前一个数字.但是,第一次使用生成器时,没有以前的值.

给一个伪随机数生成器做种子给它第一个前一个"值.每个种子值将对应于给定随机数生成器的一系列生成值.也就是说,如果您两次提供相同的种子,您将获得两次相同的数字序列.

通常,您希望为随机数生成器设置一些值,以改变程序的每次执行.例如,当前时间是一个经常使用的种子.这不会自动发生的原因是,如果您愿意,您可以提供特定的种子来获取已知的数字序列.

I am a bit confused on what random.seed() does in Python. For example, why does the below trials do what they do (consistently)?

>>> import random
>>> random.seed(9001)
>>> random.randint(1, 10)
1
>>> random.randint(1, 10)
3
>>> random.randint(1, 10)
6
>>> random.randint(1, 10)
6
>>> random.randint(1, 10)
7

I couldn't find good documentation on this.

解决方案

Pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value.

Seeding a pseudo-random number generator gives it its first "previous" value. Each seed value will correspond to a sequence of generated values for a given random number generator. That is, if you provide the same seed twice, you get the same sequence of numbers twice.

Generally, you want to seed your random number generator with some value that will change each execution of the program. For instance, the current time is a frequently-used seed. The reason why this doesn't happen automatically is so that if you want, you can provide a specific seed to get a known sequence of numbers.

这篇关于random.seed():它有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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