gpt4 book ai didi

python - 随机数算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:44:34 25 4
gpt4 key购买 nike

我需要按组生成随机数:100、500、1000 和 10000 个数字制服和高斯分布。这对于创建一些直方图和其他统计资料是必要的。

条件是不使用python自带的随机函数,所以想着用这个方法(线性同余生成器):Xn+1 ≡ (aXn + c) mod m。这里我需要 4 个变量。有人可以告诉我如何实现这个算法吗?我假设 m 变量第一次是 100

最佳答案

您已经知道这是 Linear congruential generator , 那么读起来有什么难的呢?

它告诉你你已经知道的公式enter image description here以及如何选择它们的解释:

The period of a general LCG is at most m, and for some choices of factor a much less than that. Provided that the offset c is nonzero, the LCG will have a full period for all seed values if and only if:

1) c and m are relatively prime

2) a - 1 is divisible by all prime factors of m

3) a - 1 is a multiple of 4 if m is a multiple of 4.

他们甚至在下表中为您提供了这些值的一些示例。这足以实现一个简单的功能:

def LCG(seed, n, a=1664525, c=1013904223, m=2**32):
numbers = []
for i in xrange(n):
seed = (a * seed + c) % m
numbers.append(seed)

return numbers

print LCG(3, 5)

关于python - 随机数算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31824045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com