鱼C论坛

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

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

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

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

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

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

class Random:
    def __init__(self, max_out: int, init: int, step: int=0):
        self.max = max_out
        self.x1 = init
        self.x2 = init
        self.step = step
        self.steped = 0
        pass

    def __Next(self):
        x = (self.x1 * self.x2) % self.max + 1
        self.x1 = self.x2
        self.x2 = x
        return x

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

    def __iter__(self):
        return self

    def __next__(self):
        if self.steped < self.step:
            self.steped += 1
            return self.__Next()
        self.steped = 0
        raise StopIteration

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

    def __Next(self):
        x = (self.x1 * self.x2 * self.x3) % self.max + 1
        self.x1 = self.x2
        self.x2 = self.x3
        self.x3 = x
        return x
    
    def __next__(self):
        if self.steped < self.step:
            self.steped += 1
            return self.__Next()
        self.steped = 0
        raise StopIteration

class TRandom(Random):
    def __Next(self):
        x = (self.x1 * self.x2 * datetime.datetime.today().second) % self.max + 1
        self.x1 = self.x2
        self.x2 = x
        return x

    def __next__(self):
        if self.steped < self.step:
            self.steped += 1
            return self.__Next()
        self.steped = 0
        raise StopIteration


初始化方法:
a = Random(最大输出, 种子[, 迭代次数])
(SRandom, TRandom相同,只是数更随机)

使用方法:
value = next(a)
也可以迭代:
for i in a:
    print(i)
他会循环(我们最初输入的迭代次数)次。

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

评分

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

查看全部评分

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2023-8-25 20:08:21 | 显示全部楼层
急报:
这个程序输出的最大值不是输入的最大值,而是
输入的最大值 - 1 + 种子
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-8-22 13:29:40 | 显示全部楼层
帮顶
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2023-8-22 20:47:05 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-9-21 15:37

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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