-2

Well I have following program. It is given by my teacher for fun. I got surprise about the result.

Code:

public class Testing {

    public static void main(String[] args) {

         float     piF =  3.141592653589793f;   // value assigned has float precision
         double    piD =  3.141592653589793;   //  value assigned has double precision
         final double THRESHOLD = .0001; 
         if( piF == piD) 
            System.out.println( "piF and piD are equal" ); 
         else 
            System.out.println( "piF and piD are not equal" ); 
         if( Math.abs( piF - (float) piD ) < THRESHOLD ) 
            System.out.println( "piF and piD are considered equal" ); 
         else 
            System.out.println( "piF and piD are not equal" ); 

    }

}

Result:

piF and piD are not equal
piF and piD are considered equal

Well why piF and piD are not equal ? And what actually Math.abs() do that makes both same ?

Junaid Don
  • 11
  • 1

1 Answers1

0

I ran this in my terminal, then added print statements for the values of piF and piD and here are the results:

piF and piD are not equal
piF and piD are considered equal
piF = 3.1415927
piD = 3.141592653589793

When you do a direct comparison between the two, they are not equal. But when you cast piD to a float type, it becomes this:

(float) piD = 3.1415927

Try using print statements on variables when you are not understanding the results, it's a great way to learn about this stuff!

Here are the print statements I added for your reference:

    System.out.println("piF = " + piF);
    System.out.println("piD = " + piD);

    System.out.println("(float) piD = " + (float) piD);
djs
  • 3,947
  • 3
  • 14
  • 28