类型为Double

时间:2016-10-12 15:45:12

标签: excel-vba vba excel

我在Excel VBA中遇到了溢出错误,无法找到解决方法。虽然Microsoft的文档表明双精度范围应该达到~1.8E308,但是我收到的溢出错误显着低于该阈值。我的代码如下:

Public Function Fixed_Sample_Nums(ByVal n As Long, seed As Long) As Double()

    Dim x() As Double, y() As Double, i As Long
    ReDim y(1 To n)
    ReDim x(1 To n)

    x(1) = (CDbl(48271) * seed) Mod CDbl(2 ^ 31 - 1)

    For i = 2 To n
        x(i) = (CDbl(48271) * CDbl(x(i - 1))) Mod (CDbl(2 ^ 31 - 1))
        y(i) = CDbl(x(i)) / CDbl(2 ^ 31 - 1)
    Next i

    Fixed_Sample_Nums = y

End Function

'I receive the error in the first iteration of the for loop with 
'seed equal to any value >= 1 (i.e. w/ seed = 1): 

Debug.Print((CDbl(48271) * CDbl(48271)) Mod (CDbl(2 ^ 31 - 1))) 

'results in an overflow error 

我正在尝试创建一个伪随机数生成器,它可以接收任何'种子'值,包括2 ^ 31 - 1. for循环应该能够迭代至少9,999次(即n = 10000) )。如果在前几次迭代中没有遇到溢出错误,则很可能不会遇到任何后续迭代。

如您所见,我在计算之前将每个整数转换为double。我知道数组大大增加了计算的字节大小,但这似乎不是当前的问题,因为我直接将上面的示例计算复制到了立即窗口并仍然收到溢出错误。我尝试在线找到解决方案无济于事,所以我非常感谢任何意见。提前谢谢!

1 个答案:

答案 0 :(得分:3)

尝试使用Chip Pearson的XMod功能:

x(i) = XMod((CDbl(48271) * seed), CDbl(2 ^ 31 - 1))

正如他所说:

  

您还可以使用Mod运算符在VBA中获取溢出错误   非常大的数字。例如,

Dim Number As Double
Dim Divisor As Double
Dim Result As Double

Number = 2 ^ 31
Divisor = 7
Result = Number Mod Divisor ' Overflow error here.

功能代码:

Function XMod(ByVal Number As Double, ByVal Divisor As Double) As Double
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' XMod
' Performs the same function as Mod but will not overflow
' with very large numbers. Both Mod and integer division ( \ )
' will overflow with very large numbers. XMod will not.
' Existing code like:
'       Result = Number Mod Divisor
' should be changed to:
'       Result = XMod(Number, Divisor)
' Input values that are not integers are truncated to integers. Negative
' numbers are converted to postive numbers.
' This can be used in VBA code and can be called directly from 
' a worksheet cell.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Number = Int(Abs(Number))
    Divisor = Int(Abs(Divisor))
    XMod = Number - (Int(Number / Divisor) * Divisor)
End Function

其他详情:

http://www.cpearson.com/excel/ModFunction.aspx