【问题标题】:Overflow Error in Excel VBA with Type Double类型为 Double 的 Excel VBA 中的溢出错误
【发布时间】:2016-10-12 15:45:11
【问题描述】:

我在 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 )。如果在前几次迭代中没有遇到溢出错误,则很可能不会在任何后续迭代中遇到。

如您所见,我在进行任何计算之前将每个整数转换为双精度数。我知道数组大大增加了计算的字节大小,但这似乎不是当前的问题,因为我直接将上面的示例计算复制到即时窗口中并且仍然收到溢出错误。我试图在网上找到解决方案没有结果,所以我非常感谢任何意见。提前致谢!

【问题讨论】:

  • 42。 Mod 2. ^ 31 也崩溃了,不像 42. Mod (2. ^ 31 -1) ...也许是一个无证的(谷歌没有给出任何内容)mod 的弱点。谁用它呢? O.O
  • @DavidZemens 感谢您的链接!有趣的是,我已经尝试过创建自己的函数,但仍然会导致溢出错误。此外,伪随机数生成器以工作表形式工作,没有溢出,但我需要为它创建一个 VBA 函数。

标签: excel vba


【解决方案1】:

尝试使用 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

【讨论】:

  • 再次感谢!我曾尝试使用类似的函数创建然后仍然收到溢出错误。现在我已经复制并粘贴了 Pearson 的.. 仍然收到溢出错误。
  • 哇,nvm .. 在创建 Pearson 函数后的最初尝试中,我转换为 longs 而不是 doubles x)。 PRNG 函数现在可以在语法和语义上工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多