excel - 大于等于评估不正确
问题描述
比较操作,“If Then”循环中的 ">=" 语句首先正确计算 2-3 次,然后错误,然后在 For Next 外循环的最后一个循环中正确计算。当我通过循环逐步调试时,正在比较的变量位于数组中并且具有正确的值。我很困惑为什么会发生这种情况。
想过更改数组变量的数据类型,但我认为我必须对 Excel VBA 数组使用“变体”。
'Calculate Deviance
S3 = 0
For i = 1 To N
S4 = 0
If A(i, 4) <= 0 Then
S3 = S3 + S4
S4 = 0
Else
E2 = A(i, 5) * X
If E2 < E1 Then
E2 = Exp(-E2)
S4 = A(i, 4) * Log(A(i, 4) / (A(i, 3) * (1 - E2)))
S3 = S3 + S4
S4 = 0
Else
E2 = 0
S4 = A(i, 4) * Log(A(i, 4) / (A(i, 3) * (1 - E2)))
S3 = S3 + S4
S4 = 0
End If
End If
If A(i, 4) >= A(i, 3) Then 'problem is right here. this statement.!
S3 = S3 + S4
Else
S4 = A(i, 3) - A(i, 4)
S4 = S4 * (Log(S4 / A(i, 3)) + A(i, 5) * X)
S3 = S3 + S4
End If
Next i
'Array input
' 1 2 3 4 5 6 7
'a(i,1) 0.25 0.25 0.5 0.5 1 1 1
'a(i,2) 1 0.1 0.01 0.001 0.001 0.0001 0.00001
'a(I,3) 10 10 8 10 12 12 12
'a(i,4) 10 10 8 5 7 2 0
'a(i,5) a(i,1)*a(i,2)
'N=7
解决方案
这可能是一个浮点错误,因为计算机无法在固定空间中准确地表示数字。然而,通常这个错误非常小并且不会形成问题。更多阅读请访问:https ://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
以下示例显示了浮点误差: sub 计算 2 的平方根,n 次,并以 2 种不同的方式计算总和。
sub FloatingPointError()
Dim x As Double, y As Double, n As Integer
x = 0
n = 100
y = n * (2 ^ 0.5) 'expected result is 1,4142135623731 * 100 = 141,42135623731
For i = 1 To n
x = x + (2 ^ 0.5) 'Calculate square root of 2 and add to the previous value
Next i
Debug.Print "value of x: "; x
Debug.Print "value of n * sqrt(2): "; n * (2 ^ 0.5)
If y - x = 0 Then
Debug.Print "They are equal"
Else
Debug.Print "They are not equal"
End If
End Sub
sub的输出显示:
value of x: 141,421356237309
value of n * sqrt(2): 141,42135623731
They are not equal
但是,局部变量选项卡有时会显示数字相等,因为它们是四舍五入的。
推荐阅读
- angular - 在自动完成(材料)中进行默认选择
- redis - 不同之处在于 REDIS 使用了多少内存
- node.js - 如何将内存中的 RTSP 流文件上传到谷歌云?
- react-native - 小吃博览会登录错误
- python - 我有表格格式的数据,想转换成元组格式
- javascript - 我想在反应原生中访问另一个数组中的一个数组并将其添加到列表视图中
- random - 在 stm32f4xx 中使用 RNG 库
- assembly - 在线编译器中无法编译的汇编代码
- vue.js - vue element el-select不能根据v-model显示标签
- php - JSON 响应中的布尔值在生产服务器上转换为字符串