简体   繁体   English

使用 Doubles (Excel) 的 VBA 溢出不正确

[英]Incorrect VBA Overflow using Doubles (Excel)

For some reason, the following statement evaluates to zero.出于某种原因,以下语句的计算结果为零。 I assume it's due to overflow, but all the interim values seem to be well within the limits of a double.我认为这是由于溢出,但所有临时值似乎都在双精度的范围内。

DiffieHellmanKey = (43 ^ 47) - (53 * Fix((43 ^ 47) / 53))

I think it's overflow because when I execute it with different numbers (below), it results in the correct value of 29.我认为这是溢出,因为当我用不同的数字(如下)执行它时,它会产生正确的值 29。

DiffieHellmanKey = (5 ^ 22) - (53 * Fix((5 ^ 22) / 53))

What gives?是什么赋予了? Now, back to the original numbers that are giving me overflow.现在,回到让我溢出的原始数字。 All variables involved are Doubles.所有涉及的变量都是双打。 It doesn't even work if I calculate it as a Worksheet formula instead of in VBA:如果我将它计算为工作表公式而不是 VBA,它甚至不起作用:

=(43 ^ 47) - (53 * ROUNDDOWN(((43 ^ 47) / 53), 0))

And if I implement the above example in VBA using the equivalent form (below), I get an incorrect result of -1.75357E+62.如果我使用等效形式(如下)在 VBA 中实现上面的示例,我会得到 -1.75357E+62 的错误结果。

DiffieHellmanKey = (43 ^ 47) - (53 * WorksheetFunction.RoundDown(((43 ^ 47) / 53), 0))
? (43^47) 
 5.92949097309764E+76

? 53*Fix((43^47)/53)
 5.92949097309764E+76 

? (53*Fix((43^47)/53)) = (43^47)
True

You are kind of right but your problem is not with overflow, but with significant digits.你是对的,但你的问题不是溢出,而是有效数字。

Numbers in Microsoft Excel can never have more than 15 significant digits, but decimals can be as large as 127. Microsoft Excel 中的数字不能超过 15 位有效数字,但小数可以大到 127。

source: http://msdn.microsoft.com/en-us/library/office/ff838588.aspx来源: http : //msdn.microsoft.com/en-us/library/office/ff838588.aspx

This is what was happening with your original formula:这是您的原始公式发生的情况:

(43 ^ 47) - (53 * Fix((43 ^ 47) / 53)) simplifies to (43 ^ 47) - fix(43 ^ 47) Then the (43^47) has about 76 digits long so they are both getting cut down to the same amount and equating to 0. (43 ^ 47) - (53 * Fix((43 ^ 47) / 53))简化为(43 ^ 47) - fix(43 ^ 47)那么 (43^47) 大约有 76 位长,所以它们都是减少到相同的数量并等于 0。

The largest variable type in VBA is 'Decimal' Which only holds 29 digits of significance. VBA 中最大的变量类型是“十进制”,它只包含 29 位有效数字。 You won't be able to perform math this large using visual basic natively.您将无法在本机使用 Visual Basic 执行这么大的数学运算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM