Is it safe to compare two paired doubles using the equality operator?

I know that you should never compare a floating point value using the == equality operator in .NET, but is it safe to do this if the two numbers were overlapped using Math.Floor ?

I work with a matching program, and map fragments are stored in different "regional" files. I can determine which region to get by dividing the world coordinates by 16 and setting the result that gets the coordinates of the region.

I essentially ask if there will be two values ​​that have the same part of the integer (e.g. 4.3 and 4.8) that will overlap, will be compared as equal using the == operator.

+4
source share
3 answers

A common problem with floating point comparisons is that they can easily get a rounding error. When you take a value like 1.2 (which cannot be exactly represented as a decimal), multiply it by 100 and compare it for equality with 120 . The recommendation is to always compare the difference like this:

 var a = 1.2; a *= 100; if (a - 120 < 0.0001) { } 

However, the Math.Floor operation always results in an integer value. That is, any fractional values ​​will be truncated, and the exact integer value will remain.

So, if your semantics really should use gender, you're safe.

However, if you are really trying to round, use Math.Round () instead.

+5
source

Well, it depends on what you are trying to do.

This will tell you if the total values ​​are equal, but if one input was only smidge to 2, and one input was just combined over 2, then they will be perceived as different, despite the fact that the difference between them is potentially tiny.

Is this good for your scenario? In some cases it will be, in some it will not.

+4
source

I think your question is based on an erroneous assumption. It is completely safe to compare floating point values ​​using == in .Net. The only odd behavior associated with == and floating point values ​​is that Double.NaN and Single.NaN will return false compared to themselves with == (as dictated by the floating point specification).

Using Math.Floor does not make this situation better. If any of the special floating-point values ​​( NaN , NegativeInfinity , PositiveInfinity ) are passed to Math.Floor , they are returned unchanged. So comparing via == will still have odd behavior ( Link )

The main effect using Math.Floor will have more floating values ​​that will be compared with each other. For example, 7.1 and 7.5 will be equal after a Math.Floor . It is not initially better, but it may be in the context of your application, but it is difficult to say that it will be without additional information. Could you tell us more about why you think that == is unsafe?

+2
source

Source: https://habr.com/ru/post/1342036/


All Articles