floating point - Why is comparing floats inconsistent in Java? -


class test{       public static void main(string[] args){           float f1=3.2f;           float f2=6.5f;            if(f1==3.2){             system.out.println("same");           }else{             system.out.println("different");           }         if(f2==6.5){             system.out.println("same");           }else{               system.out.println("different");           }     }   }   

output:

different same 

why output that? expected same result in first case.

the difference 6.5 can represented in both float , double - whereas 3.2 can't represented in either type... , 2 closest approximations different. equality comparison between float , double first converts float double , compares two. data loss.


you shouldn't ever compare floats or doubles equality; because, can't guarantee number assign float or double exact. this rounding error characteristic feature of floating-point computation.

squeezing infinitely many real numbers finite number of bits requires approximate representation. although there infinitely many integers, in programs result of integer computations can stored in 32 bits.

in contrast, given fixed number of bits, calculations real numbers produce quantities cannot represented using many bits. therefore result of floating-point calculation must rounded in order fit finite representation. rounding error characteristic feature of floating-point computation.

check what every computer scientist should know floating-point arithmetic more!


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -