|
发表于 2023-12-23 22:02:35
|
显示全部楼层
首先,你的代码有一些错误和改进的地方。
1. 在Random类的构造函数中,你使用了`pass`语句,它表示不执行任何操作。你可以把它删除掉。
2. 在Random类的`__Next`方法中,你没有使用给定的`step`参数。你应该在计算下一个伪随机数之前,先检查是否需要跳过一些步数。
3. 在SRandom类和TRandom类中,你需要重写`__Next`方法,以确保你的伪随机数生成算法是根据你的要求进行的。
4. 在TRandom类中,你使用了`datetime.datetime.today().second`作为随机数种子,这意味着每秒都会生成相同的随机数序列。你可以考虑使用更精确的时间戳,例如`datetime.datetime.now().timestamp()`。
接下来,我们来更新你的代码:
- import datetime
- class Random:
- def __init__(self, max_out: int, true_max: int, init: int, step: int=0):
- self.max = max_out
- self.true_max = true_max
- self.x1 = init
- self.x2 = init
- self.step = step
- self.steped = 0
- def __Next(self):
- x = ((self.x1 * self.x2) % self.true_max + 1) % 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, true_max: int, init: int, step: int=0):
- super().__init__(max_out, true_max, init, step)
- self.x3 = init
- def __Next(self):
- x = ((self.x1 * self.x2 * self.x3) % self.true_max + 1) % 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 * int(datetime.datetime.now().timestamp())) % self.true_max + 1) % 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
复制代码
现在,你可以使用这些类来生成伪随机数。假设你要生成一个范围在1到100之间的伪随机数,你可以按照下面的方式进行操作:
- random_generator = Random(100, 10**256, 1) # 创建一个Random的实例,设定最大值为100,true_max为10的256次方,初始值为1
- random_number = next(random_generator) # 生成下一个伪随机数
- print(random_number) # 打印该伪随机数
复制代码
你还可以使用`Setstep`方法设置每次跳过的步数,例如:
- random_generator.Setstep(10) # 每次跳过10个数
复制代码
同样地,你也可以使用`SRandom`和`TRandom`来生成伪随机数。
希望这能帮到你!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|