使用math.round比较数字 [英] Compare numbers using math.round
问题描述
我使用VB.Net比较两个小数最多4位小数。
Dim Num1为Double = 12.34562
Dim Num2 as Double = 12.34567
问题(1)以下哪种方法使用正确:
''----------------------------------------- -
如果Math.Round(Num1,4)> = Math.round(Num2,4)那么
...
结束如果
''-----或者-----
Private AccuracyValue As Double = 0.0001
如果Math.Abs(Num1 - Num2)< = AccuracyValue那么
.. 。
结束如果
''--------------------- ----------------------
否则,比较两个数字的正确方法应该是什么在准确度范围内?
问题(2)如果这两个数字是什么
12.3456789和
/>
12.3456782
小数部分为mu ch大于所需的精度。
使用Math.Round会安全吗?
我尝试过:
如果Math.Round(Num1,4)> = Math.round(Num2,4)那么
...
结束如果
I am using VB.Net to compare two numbers upto 4 decimal places.
Dim Num1 as Double = 12.34562
Dim Num2 as Double = 12.34567
Question (1) Which of these methods would be correct to use:
''------------------------------------------
If Math.Round(Num1, 4) >= Math.round(Num2, 4) Then
...
End If
''----- OR -----
Private AccuracyValue As Double = 0.0001
If Math.Abs(Num1 - Num2) <= AccuracyValue Then
...
End If
''-------------------------------------------
Else, what should be the correct way to compare two number within a accuracy range ?
Question (2) What if the two numbers are
12.3456789 and
12.3456782
where the decimal part is much larger than the required accuracy.
Will using Math.Round be safe ?
What I have tried:
If Math.Round(Num1, 4) >= Math.round(Num2, 4) Then
...
End If
推荐答案
1)
比较差异的绝对值与数量值(通常表示为ε - 小希腊字母epsilon)是常用方法:
1) Comparing the absolute of the difference with a quantity value (often denoted ε - small greek letter epsilon) is the common method:
diff = num1 - num2
if (abs(diff) <= epsilon)
# numbers are similar
else
# may use sign of diff here to check if larger or smaller
这种方法也比比较舍入值快得多。
2)
忽略其他数字。在您的示例中,两个值都将四舍五入为 12.3457
。
This method is also much faster than comparing rounded values.
2)
Additional digits are ignored. With your example, both values will be rounded to 12.3457
.
这篇关于使用math.round比较数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!