鱼C论坛

 找回密码
 立即注册
查看: 2589|回复: 3

[作品展示] 用Python写的伪随机数生成模块

[复制链接]
发表于 2023-8-22 09:51:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 KeyError 于 2023-8-22 21:15 编辑
  1. import datetime

  2. class Random:
  3.     def __init__(self, max_out: int, init: int, step: int=0):
  4.         self.max = max_out
  5.         self.x1 = init
  6.         self.x2 = init
  7.         self.step = step
  8.         self.steped = 0
  9.         pass

  10.     def __Next(self):
  11.         x = (self.x1 * self.x2) % self.max + 1
  12.         self.x1 = self.x2
  13.         self.x2 = x
  14.         return x

  15.     def Setstep(self, step):
  16.         self.step = step

  17.     def __iter__(self):
  18.         return self

  19.     def __next__(self):
  20.         if self.steped < self.step:
  21.             self.steped += 1
  22.             return self.__Next()
  23.         self.steped = 0
  24.         raise StopIteration

  25. class SRandom(Random):
  26.     def __init__(self, max_out: int, init: int, step: int=0):
  27.         super().__init__(max_out, init, step)
  28.         self.x3 = init

  29.     def __Next(self):
  30.         x = (self.x1 * self.x2 * self.x3) % self.max + 1
  31.         self.x1 = self.x2
  32.         self.x2 = self.x3
  33.         self.x3 = x
  34.         return x
  35.    
  36.     def __next__(self):
  37.         if self.steped < self.step:
  38.             self.steped += 1
  39.             return self.__Next()
  40.         self.steped = 0
  41.         raise StopIteration

  42. class TRandom(Random):
  43.     def __Next(self):
  44.         x = (self.x1 * self.x2 * datetime.datetime.today().second) % self.max + 1
  45.         self.x1 = self.x2
  46.         self.x2 = x
  47.         return x

  48.     def __next__(self):
  49.         if self.steped < self.step:
  50.             self.steped += 1
  51.             return self.__Next()
  52.         self.steped = 0
  53.         raise StopIteration
复制代码



初始化方法:
  1. a = Random(最大输出, 种子[, 迭代次数])
复制代码

(SRandom, TRandom相同,只是数更随机)

使用方法:
  1. value = next(a)
复制代码

也可以迭代:
  1. for i in a:
  2.     print(i)
复制代码

他会循环(我们最初输入的迭代次数)次。

最后,还可以调整迭代次数:
  1. a.Setstep(迭代次数)
复制代码


评分

参与人数 4荣誉 +15 鱼币 +6 贡献 +9 收起 理由
sfqxx + 3
python爱好者. + 5 + 3 鱼C有你更精彩^_^
zhangjinxuan + 5 + 5 无条件支持楼主!
cjjJasonchen + 5 + 1 + 3 无条件支持楼主!

查看全部评分

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2023-8-25 20:08:21 | 显示全部楼层
急报:
这个程序输出的最大值不是输入的最大值,而是
  1. 输入的最大值 - 1 + 种子
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-8-22 13:29:40 | 显示全部楼层
帮顶
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2023-8-22 20:47:05 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-18 16:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表