Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I compare whether two floating-point number are equal in Kotlin?

Tags:

kotlin

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

This code calculates the fixpoint of cosine, which is a mathematical constant. It simply calls Math.cos repeatedly starting at 1.0 until the result doesn't change any more, yielding a result of 0.7390851332151607.

In my mind, we can't compare whether two floating-point number are equal, so I think that the result of if (x == y) is always false, right?

private fun findFixPoint(): Double {
    var x = 1.0
    while (true) {
        val y = Math.cos(x)
        if (x == y) return y
        x = y
    }
}
like image 620
HelloCW Avatar asked Sep 19 '17 00:09

HelloCW


2 Answers

To further extend on my comment and getting more precise, the documentation gives you the key.

Math.cos(double)

The computed result must be within 1 ulp of the exact result. Results must be semi-monotonic.

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

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

It follows that the only way that the computation wouldn't stop is if an input of one of these numbers will give you the other number. But since the function is semi-monotonic that means that can't happen. Otherwise you would have the higher value of the two as input giving you the lower value as output, and the lower value giving you the higher one as output. Semi-monotonic means it only goes in one direction (to put it very simply and somewhat inaccurately).

like image 129
DPM Avatar answered Sep 19 '22 16:09

DPM


In my mind, we can't compare whether two floating-point number are equal, so I think that the result of if (x == y) is always false, right?

No, this is wrong. You CAN compare whether two floating-point number are equal but it is mostly meaningless. Because floating point by definition is not accurate. Even two different calculations have same result in Math, it does not necessary equal in program because of rounding error. It still may a chance to be equal.

like image 40
Joshua Avatar answered Sep 21 '22 16:09

Joshua