首页 > 解决方案 > python如何在不使用随机库的情况下根据给定的输入生成随机数?

问题描述

想象有一个rand8函数返回 [0 - 7] 之间的随机数。现在我想rand11根据我从rand8. 像这样:

 Input from rand8     : 1, 3 , 5  , 7 , 0 , 7 , 2 , 1 , 6 , ...
Output given by rand11: 0, 5 , 10 , 7 , 6 , 0 , 2 , 9 , 8 , ...

到目前为止,我在网上找到了这个:

def lcg(modulus, a, c, seed):
    while True:
        seed = (a * seed + c) % modulus
        yield seed

a = lcg(5, 0, 8, 1)
next(a)

但我不熟悉如何修改函数以获取 0 到 7 之间的数字并返回 0 到 10 之间的数字。请注意,我不需要实现rand8函数。我只需要照顾rand11功能?请记住,我不允许random在 python 或任何其他随机库中使用库,例如numpy.random()

谁能帮我?

标签: pythongenerator

解决方案


这将给出result您期望的输出列表。如您所见,如果您运行此程序,它会给出 0 到 10 之间的值的均匀分布。随机库仅用于生成更大的rand8种子列表。

from random import randint
import collections

result = []

#seeds = [1, 3 , 5  , 7 , 0 , 7 , 2 , 1 , 6]
seeds = [randint(0,7) for i in range(1000000)]
gen = 1
for se in seeds:
    gen = (se  + gen) % 11
    result.append(gen)

counter =collections.Counter(result)
print(counter)

如果您希望函数每次运行时都有不同的结果,您可以添加一个乘数。没有显示均匀分布的最终代码:

result = []
c = int(input("Seed?"))
seeds = [1, 3 , 5  , 7 , 0 , 7 , 2 , 1 , 6]
gen = 1
for se in seeds:
    gen = (se * c + gen) % 11
    result.append(gen)

print(result)

推荐阅读