1

This is what I got to know about Floating point equals operation:

To actually compare floating-point numbers for equality, it is generally desirable to compare them within some tiny range of allowable differences; this range is often re‐garded as a tolerance or as epsilon.

Ie,

/** Compare two doubles, using default  epsilon */
public static boolean equals(double a, double b) {
    return equals(a, b, EPSILON);
}

Is this the only method or is there any other way to compare the exact value floating point numbers without any tolerance.

fabian
  • 80,457
  • 12
  • 86
  • 114
Aajan
  • 927
  • 1
  • 10
  • 23

4 Answers4

3

The == operator compares two double values for exact equality.

Example:

1.0 == 2.0 - 1.0 // true
0.1 + 0.2 == 0.3 // false
0.25 == 0.125 + 0.125 // true
1.0 / 3.0 == 2.0 / 6.0 // true
Clashsoft
  • 11,553
  • 5
  • 40
  • 79
2

Please note that there is no such thing as exactness in floating points due to the fundamental limitation of the binary code. You cannot express decimal in binary exactly, instead halves, quarters (and other ratios with denominator being a power of two) are used to express values that are 'close enough' within some acceptable tolerance. You cannot remove this tolerance and compare exact values, because otherwise you cannot express decimals in binary.

Useful link.

UPDATE: Just found on the stackoverflow this great response, so that I don't have to write it all over. Read this and maybe you will consider using BigDecimal for the task at hand.

Community
  • 1
  • 1
Kudin
  • 456
  • 4
  • 7
1

Use static Double#compare(double d1, double d2) method for internal double representation comparison if you really need it.

Andriy Kryvtsun
  • 3,220
  • 3
  • 27
  • 41
1

Advice to just use ==, or to use a tolerance (epsilon) are wrong. They will give unexpected results if the float values are NaN (not a number). You should instead use floatToIntBits Why use Float.floatToIntBits() in Java float comparisons?

Community
  • 1
  • 1
Raedwald
  • 46,613
  • 43
  • 151
  • 237