我正在用 Python 编写一个 LCG 函数,我将使用它来进行蒙特卡罗类型的硬币翻转和生成运行模拟。我面临的问题是,当我生成一个随机数列表时,这些数字的模式会使得赔率和偶数交替出现。我不知道这是 LCG 函数本身的属性还是我生成数字的错误。
这是我的代码:
def seedLCG(initVal):
global rand
rand = initVal
def lcg():
a = 1140671485
c = 128201163
m = 2**24
global rand
rand = (a*rand + c) % m
return rand
seedLCG(1)
for i in range(10):
print lcg()
Run Code Online (Sandbox Code Playgroud)
返回值:
10581448
11595891
1502322
14136437
11348076
1403015
9622582
11013417
11529808
15836891
Run Code Online (Sandbox Code Playgroud)
我假设我不需要担心溢出和大小,因为 int 和 long 会根据 Python 的需要进行互换。
a*rand乘以rand一个奇数,所以结果总是奇数时rand为奇数,偶数时rand为偶数。然后添加奇数c,奇数变为偶数,反之亦然。模数对最后一位没有影响。因此,每次调用lcg翻转rand从奇连或甚至奇数。
如果您对随机数很认真(但您不需要加密强度的随机数),请考虑使用numpy.random.