问题描述
我一直在阅读Bruce Dawson的本文比较浮点值.但是他所有的例子都在检查
I've been reading this article by Bruce Dawson on how to compare floating point values. But all of his examples were checking if
floatA == floatB.
所以我想知道是否有适当的方法来比较
So I was wondering if there is a proper way to compare if either
floatA > floatB
或
floatA <floatB.
或者是< ,>运算符足以考虑浮点值?
Or is the < , > operator enough to consider the floating point values?
我不喜欢如何检查是否相等.我很想知道是否有一种方法可以检查一个浮点值是否小于另一个浮点值.
I'm not interesed in how to check for equals. I'm interested if there is a way to do checks for if one float value is smaller / greater than the other.
推荐答案
比较浮点数是否相等的问题是,许多数字在二进制浮点数中没有确切的表示形式.例如,0.1不能精确地表示为浮点数,只能非常非常接近.
The issue with comparing floats for equality is that many number have no exact representation in binary floating point. For example 0.1 cannot be represented exactly in floating point, only a very very close approximation.
因此,当您将近似值乘以10时,并不会得到您期望的1.0.
So when you take that approximation and multiply it by 10 you do not get exactly 1.0 as you might expect.
因此,如果您输入"if(0.1 * 10 == 1.0)",则不会获得预期的结果,很可能会得到错误的结果.
So if you write "if (0.1 * 10 == 1.0)" you won't get the result you expect, you'll get false most likely.
相同的问题适用于小于和大于.
The same issue applies to less than and greater than.
如果(0.1 * 10< 1.0)"-这应该是不正确的,因为值是相等的.但是实际上,这可能是正确的,因为0.1是一个近似值,它比0.1稍微小一点,然后乘以10,得出的值比1.0稍微小一点,这使得该检验为假时该检验为真.
"if (0.1 * 10 < 1.0) " - this should not be true because the values are equal.However in practice it probably will be true because 0.1 is an approximation that is very slightly smaller than 0.1 and multiplying it by 10 gives a value very slightly smaller than 1.0 making the test true when it shoulsd be false.
如果您的比较可能会受到此影响,那么您需要适当地处理它.
If your comparisons might be affected by this then you'll need to deal with it appropriately.
在某些情况下,这不是问题.if(distance_to_work< 10.0)//可能不会引起问题但在某些情况下
In may cases this is not an issue. if (distance_to_work < 10.0) // Probably not going to cause an issueBut in some it might be
这篇关于如果1个浮点值大于/小于另一个浮点值,是否可以正确比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!