gpt4 book ai didi

python - python中Random模块如何生成一个新的数字

转载 作者:太空宇宙 更新时间:2023-11-04 02:15:49 24 4
gpt4 key购买 nike

所以我一直在研究线性同余生成器,但我坚持认为一旦脚本运行,它总是以相同的方式生成。如果我运行这样的脚本;

import random

print(random.randrange(0,9))

每次运行脚本都会生成一个新的随机数。我想知道它是如何做到这一点的。

这就是我到目前为止所得到的;

from collections import Counter

class linearCongruentialGenerator(object):
def __init__(self, lowBound, highBound, length):
self.lowBound, self.highBound, self.length = lowBound, highBound, length
self.modulus = 20226231145#modulus
self.multiplier = 104743412357321567#multiplier
self.increment = 1049592131123467#increment
self.seed = 43123211114#seed

def __iter__(self):
while self.length > 0:
self.length -= 1
self.seed = (self.multiplier*self.seed + self.increment) % self.modulus
yield (self.seed % self.highBound)

def linearCongruentialGenerator(self, first, last):
self.seed = (self.multiplier*self.seed + self.increment) % self.modulus
return self.seed

def binary(self):
self.seed = (self.multiplier*self.seed + self.increment) % self.modulus
self.seedLength = len(str(seed))
return (self.seed // 10**1 % 10) % 2

if __name__ == "__main__":
random = linearCongruentialGenerator(0, 9, 100)
random1 = linearCongruentialGenerator(0, 9, 100)
list1 = []
list2 = []
for i in random:
list1.append(i)
for j in random1:
list2.append(j)
print(Counter(list1))
print(len(set(list1)))
print(Counter(list2))
print(len(set(list2)))

此脚本计算 linearCongruentialGenerator 类生成的数字,然后打印分布:number:count。

我希望脚本在每次运行脚本时都生成新值。不使用python自带的random类。因为那是作弊 :D

不确定如何解决这个问题,有什么提示吗?

最佳答案

只是做我们所做的以确保这个问题不会随机发生,在 init 中将种子设置为 time.time() 以便它始终以当前时间 seed=time.time() 为种子

关于python - python中Random模块如何生成一个新的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52687199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com