我正在尝试在VBA中复制线性同余生成器,但我的程序返回给我一个错误'6':溢出......
Sub test()
Dim a As Long, c As Long, period As Long
Dim seed As Long, sample As Long, max As Long
Dim i As Long
seed = 1234
sample = 2
max = 100
a = 48271
c = 0
period = 2 ^ 31 - 1
For i = 1 To sample
seed = (a * seed + c) Mod period
Next i
End Sub
我认为问题出现在for循环的第一个表达式中,详见
a*seed
在循环的第二步。 任何建议解决问题而不分裂
a*seed
in
(100*seed+100*seed+100*seed+...+(a-100*n)*seed
答案 0 :(得分:2)
您可以使用变体的decimal subtype并为小数编写自己的mod函数:
Function DecMod(a As Variant, n As Variant) As Variant
Dim q As Variant
q = Int(CDec(a) / CDec(n))
DecMod = a - n * q
End Function
Sub test()
Dim a As Variant, c As Variant, period As Variant
Dim seed As Variant, sample As Long, max As Long
Dim i As Long
seed = CDec(1234)
sample = 5
max = 100
a = CDec(48271)
c = 0
period = CDec(2 ^ 31 - 1)
For i = 1 To sample
Debug.Print seed
seed = DecMod(seed * a + c, period)
Next i
End Sub
输出:
1234
59566414
1997250508
148423250
533254358