Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of output of a java program

Tags:

java

boolean

I came across the following program

class Boolean {  
  public static void main(String argv[]) {  
    boolean x;  
    x = 4.4f == 4.4;  
    System.out.println(x);  
  }  
} 

The output of the following program is false

But if we write the program in the following fashion, then

class Boolean {  
    public static void main(String argv[]) {  
      boolean x;  
      x = 4.5f == 4.5;  
      System.out.println(x);  
    }  
}

In this case the output is true

Can somebody explain me why ??

like image 553
pradeepchhetri Avatar asked Jul 28 '11 08:07

pradeepchhetri


2 Answers

You generally shouldn't compare floating point values with == operator. You should use 'close enough' comparison like checking if values differ by some small value:

double epsilon = 0.000001

boolean equal = Math.abs(value1-value2) < epsilon

In your example, 4.4f is not equal to 4.4, because java defaults floating point values to double type, which is 64bit, and to compare them java casts 4.4f to double, which causes it to be slightly different from original double value 4.4(because of problems representing decimal fractions with binary).

Here's a good link on floating point numbers.

like image 130
Krns Avatar answered Sep 23 '22 00:09

Krns


The problem is that computers like numbers to be based on base 2 and not base 10 like us.

4.4 is an infinite fraction (like 0.333333333... for us) in binary, and floats have fewer digits than doubles, so there are fewer digits in 4.4f than in 4.4 making them different.

4.5 is not an infinite fraction.

Note: Whenever you need to compare floats or doubles you should always check the size of the difference, not just check for equality.

like image 28
Thorbjørn Ravn Andersen Avatar answered Sep 25 '22 00:09

Thorbjørn Ravn Andersen