用Python写的伪随机数生成模块
本帖最后由 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(迭代次数)
急报:
这个程序输出的最大值不是输入的最大值,而是
输入的最大值 - 1 + 种子 帮顶 @liuhongrun2022
@sfqxx
页:
[1]