Comparing floating point numbers in Java

Possible duplicate:
Manipulating and comparing floating points in java

Should I use Epsilon when comparing floating point numbers in Java? Is it safe to use the static method Float.compare (float f1, float f2)?

Thank!

EDIT: I think I get it.

When I write, say, 3.6f in eclipse, the compiler interprets this number as 3.6. However, when I write 1.2f * 3.0f, the result is 3.6000001. Although mathematically incorrect, these two results are obviously inequalities. Therefore, you must have epsilon when checking equality.

However, when I write 0.0f in eclipse, the compiler interprets this as 0 strictly, because IEEE 754 is able to handle it correctly. Therefore, ensuring the float is strictly positive with (value> 0.0f) is correct.

The only problem I see is when the computer does not use the IEEE 754 view and instead uses the view that does not correctly handle 0.

I'm right?

+3
source share
2 answers

The Math.ulp () method has practical application in testing. As you undoubtedly know, you usually should not compare floating point numbers for exact equality. Instead, you verify that they are equal within a certain tolerance. For example, in JUnit, you are comparing expected actual floating point values, for example:

assertEquals(expectedValue, actualValue, 0.02);

, 0,02 . 0,02 ? 10,5 -107,82, 0,02, , . , , 0.02 . , , ​​ ULP. , , 1 10 ULP. , , 5 ULP :

assertEquals(expectedValue, actualValue, 5*Math.ulp(expectedValue));

http://www.ibm.com/developerworks/java/library/j-math2/index.html

+12

, .

Compare , double , . , , , , ==.

+3

All Articles