比较运算,"If Then“循环中的">=”语句首先正确计算2-3次,然后错误,然后在For Next外部循环的最后一个循环中正确计算。正在比较的变量在数组中,并且在我逐步调试循环时具有正确的值。我不明白为什么会发生这样的事情。
我想改变数组变量的数据类型,但我认为我必须为Excel VBA数组使用"variant“。
'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
发布于 2019-10-17 17:54:02
这可能是一个浮点错误,因为计算机不能在固定的空间中准确地表示数字。但是,通常情况下,此错误非常小,不会形成问题。更多阅读请访问:https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
下面的例子显示了浮点错误: sub计算2,n次的平方根,然后用两种不同的方法计算总和。
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
但是,local variable选项卡有时会显示数字相等,因为它们是四舍五入的。
https://stackoverflow.com/questions/53887839
复制相似问题