Why is comparing floats inconsistent in Java?

前端 未结 8 637
不思量自难忘°
不思量自难忘° 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-11-30 23:59

    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)

    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.
    

提交回复
热议问题