Programmings

BrainTeaser Question: What will be output of following Program-
public class MyBrainTeaser1
{
    public static void main(String[] args) 
{
    float f1 = 3.2f;
    float f2 = 6.5f;
    if (f1 == 3.2)
  {
      System.out.println("f1 is True");
  }
  else
  {
      System.out.println("f1 is False");
   }
   if (f2 == 6.5)
   {
       System.out.println("f2 is True");
    }
   else
   {
       System.out.println("f2 is False");
    }
  }

}


Ans is :

             f1 is False
             f2 is True

Solution: 

As Ian pointed out, 6.5 can be represented exactly in binary, whereas 3.2 can't. That's why the difference in precision doesn't matter for 6.5, so 6.5 == 6.5f. 

To quickly refresh how binary numbers work: 


100 -> 4 

10 -> 2 
1 -> 1 
0.1 -> 0.5 (or 1/2) 
0.01 -> 0.25 (or 1/4) 
etc. 

6.5 in binary: 110.1 (exact result, the rest of the digits are just zeroes) 

3.2 in binary: 11.001100110011001100110011001100110011001100110011001101... (here precision matters!) 

A float only has 24 bits precision (the rest is used for sign and exponent), so: 


3.2f in binary: 11.0011001100110011001100 (not equal to the double precision approximation) 



There's a handy calculator for things like this at http://www.digitconvert.com/ 



Basically it's the same as when you're writing 1/5 and 1/7 in decimal numbers: 


1/5 = 0,2 

1,7 = 0,14285714285714285714285714285714...

2) PHP starting tag Phanda




No comments:

Post a Comment