我正在尝试在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




(100*seed+100*seed+100*seed+...+(a-100*n)*seed

最佳答案

您可以使用variant的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

07-24 09:28