go to previous page   go to home page   hear noise   go to next page


12 + 4 > 16 5.2 - 1.2 <= 2.0+22*3-4 == 1+1
false true true

Danger with Comparing Doubles

What do you imagine is the result of evaluating the Boolean expression:

4.0/3.0 == 1.0 + 1.0/3.0

Probably you think that it is true. Possibly it is. But not certainly. Floating point arithmetic is not exact. Never trust an "exactly equals" comparison with floats. The problem is that some numbers require an unlimited number of bits to be represented exactly. For these numbers, even a 64 bit double is not exact.

You are familiar with this situation with paper-and-pencil arithmetic. For example, is the following true?

1.0/3.0 == 0.3333333

This is not true. The decimal on the right is only an approximation. With more decimal places the approximation gets better, but it is never exactly equal to the fraction. The same occurs with Java (and all other computer programming languages). For example, the following might come out to be false:

1.0/10.0 == 0.1

Sometimes when unquestionable precision is needed, integer arithmetic is used. This is one reason why Java has 64 bit long integers.


What is the output of the following:

class DecimalFraction
  public static void main (String[] args)
    float x = 1.0f;    // 1.0f means 1.0 float
    float y = 10.0f;
    if ( x/y == 0.1 )
      System.out.println("Buy the cookie!"  );
      System.out.println("No cookie for you.");