Why is comparing floats inconsistent in Java?

前端 未结 8 652
不思量自难忘°
不思量自难忘° 2020-11-30 23:16
class Test{  
    public static void main(String[] args){  
        float f1=3.2f;  
        float f2=6.5f;  

        if(f1==3.2){
            System.out.println(\"         


        
8条回答
  •  孤城傲影
    2020-12-01 00:19

    The difference is that 6.5 can be represented exactly in both float and double, whereas 3.2 can't be represented exactly in either type. and the two closest approximations are different.

    An equality comparison between float and double first converts the float to a double and then compares the two. So the data loss.


    You shouldn't ever compare floats or doubles for equality; because you can't really guarantee that the number you assign to the float or double is exact.

    This rounding error is a characteristic feature of floating-point computation.

    Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits.

    In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

    Check What Every Computer Scientist Should Know About Floating-Point Arithmetic for more!

提交回复
热议问题