简体   繁体   English

播种Python的随机数生成器

[英]Seeding Python's random number generator

I am using irand=randrange(0,10) to generate random numbers in a program. 我正在使用irand=randrange(0,10)在程序中生成随机数。 This random number generator is used multiple times in the code. 该随机数生成器在代码中多次使用。 At the beginning of the code, I initiate the seed with random.seed(1234) . 在代码的开头,我使用random.seed(1234)初始化种子。 Is this the right practice? 这是正确的做法吗?

Seeding the random number generator at the beginning will ensure that the same random numbers are generated each time you run the code. 在开始时为随机数生成器播种将确保每次运行代码时都生成相同的随机数。 This may or may not be 'the right practice' depending on how you plan to use the random numbers. 根据您打算如何使用随机数,这可能是“正确的做法”,也可能不是“正确的做法”。

import random

# Initial seeding
random.seed(1234)
[random.randrange(0, 10) for _ in range(10)]
# [7, 1, 0, 1, 9, 0, 1, 1, 5, 3]

# Re-seeding produces the same results
random.seed(1234)
[random.randrange(0, 10) for _ in range(10)]
# [7, 1, 0, 1, 9, 0, 1, 1, 5, 3]

# Continuing on the same seed produces new random numbers
[random.randrange(0, 10) for _ in range(10)]
# [0, 0, 0, 5, 9, 7, 9, 7, 2, 1]

If you do not seed the random number generator at the beginning of your code, then it is seeded with the current system time which will ensure that it produces different random numbers each time you run the code. 如果您没有在代码开始时为随机数生成器设置种子,那么它将使用当前系统时间作为种子,这将确保每次运行代码它都会生成不同的随机数。

As documentation say, when you use random.seed you have two options: 如文档所述,当您使用random.seed时,有两种选择:

random.seed() - seeds from current time or from an operating system specific randomness source if available random.seed()-当前时间或操作系统特定的随机性源(如果有)中的种子

random.seed(a) - hash(a) is used instead as seed random.seed(a)-代替使用hash(a)作为种子

Using time as seed is better practice if you want to have different numbers between two instances of your program, but for sure is much harder to debug. 如果您希望在程序的两个实例之间使用不同的数字,则最好使用时间作为种子,但是可以肯定,调试起来要困难得多。

Using hardcoded number as seed makes your random numbers much more predictable. 使用硬编码数字作为种子可以使您的随机数更具可预测性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM