python - 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()
谁能帮我?
解决方案
这将给出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)
推荐阅读
- android - 如何使颤动的音频播放器更加一致
- kubernetes - Kubernetes Service Resource 需要先应用 Deployment Resource Manifest 才能转发流量
- sql - 在sql中查找新帐户的计数
- power-automate - 如何输入密码 HTTP 潮流
- c# - 实体框架随机 InvalidCastException - 类型字符串,需要 int64
- r - 如果我的原始数据集中不存在这些日期,如何将某些日期的 geom_vline 添加到我的绘图中?
- amazon-web-services - AWS Transcribe Streaming BadRequestException:“无法解码音频流...”
- r - 将自定义图例添加到 R 中的 geom_line()
- r - 在 geom_sf 中填充连续颜色
- javascript - 使用 React refs 处理鼠标事件