在types为Double的Excel VBA中发生溢出错误

我遇到了Excel VBA中的溢出错误,无法find解决方法。 虽然微软的文件显示双打的范围应该达到〜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 (ie w/ seed = 1): Debug.Print((CDbl(48271) * CDbl(48271)) Mod (CDbl(2 ^ 31 - 1))) 'results in an overflow error 

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

正如你所看到的,在计算之前,我将每个整数转换为double。 我意识到数组大大增加了计算的字节大小,但这似乎并不是当前的问题,因为我直接将上面的示例计算复制到直接窗口中,仍然收到溢出错误。 我在网上find一个解决scheme的尝试没有任何结果,所以我真的很感激任何意见。 提前致谢!

尝试使用Chip Pearson的XModfunction:

 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:

 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