Can I compare if two floating point numbers in Kotlin are equal?

The following code is from https://kotlinlang.org/docs/reference/functions.html?q=&p=0

This code calculates a fixed cosine point, which is a mathematical constant. He simply calls Math.cos several times, starting at 1.0, until the result no longer changes, giving the result 0.7390851332151607.

In my opinion, we cannot compare whether two floating-point numbers are equal, so I think that the result of if (x == y) always wrong, right?

 private fun findFixPoint(): Double { var x = 1.0 while (true) { val y = Math.cos(x) if (x == y) return y x = y } } 
+5
source share
2 answers

For further distribution to my comment and clarification, the documentation gives you the key.

Math.cos (double)

The calculated result must be within 1 ulp of the exact result. The results should be semi-monotonous.

. ulp is the difference between a coded floating-point number and the next number that can be encoded in a data type, in this case double.

If the result should be within 1 ulp, this means that the result can be one of at most two floating point values.

It follows that the only way that the calculation does not stop is that the input of one of these numbers will give you another number. But since the function is half-monotonous, this means that this cannot be. Otherwise, you will have a higher value of the two as input, giving you a lower value as the output, and a lower value will give you a higher result as the output. Half-monotonous means that it moves in only one direction (this is done very simply and somewhat inaccurately).

+3
source

In my opinion, we cannot compare whether two floating-point numbers are equal, so I think that the result of if (x == y) is always wrong, right?

No, this is wrong. You CAN compare whether two floating point numbers are equal, but this is basically pointless. Since floating point is by definition inaccurate. Even two different calculations have the same result in Math; it is not necessarily equal in the program due to a rounding error. It can still be equal.

+2
source

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


All Articles