Why is comparing floats inconsistent in Java?

前端 未结 8 610
不思量自难忘°
不思量自难忘° 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:21

    It is not possible to compare values of type float and double directly. Before the values can be compared, it is necessary to either convert the double to float, or convert the float to double. If one does the former comparison, the conversion will ask "Does the the float hold the best possible float representation of the double's value?" If one does the latter conversion, the question will be "Does the float hold a perfect representation of the double's value". In many contexts, the former question is the more meaningful one, but Java assumes that all comparisons between float and double are intended to ask the latter question.

    I would suggest that regardless of what a language is willing to tolerate, one's coding standards should absolutely positively forbid direct comparisons between operands of type float and double. Given code like:

    float f = function1();
    double d = function2();
    ...
    if (d==f) ...
    

    it's impossible to tell what behavior is intended in cases where d represents a value which is not precisely representable in float. If the intention is that f be converted to a double, and the result of that conversion compared with d, one should write the comparison as

    if (d==(double)f) ...
    

    Although the typecast doesn't change the code's behavior, it makes clear that the code's behavior is intentional. If the intention was that the comparison indicate whether f holds the best float representation of d, it should be:

    if ((float)d==f)
    

    Note that the behavior of this is very different from what would happen without the cast. Had your original code cast the double operand of each comparison to float, then both equality tests would have passed.

    0 讨论(0)
  • 2020-12-01 00:21

    In general is not a good practice to use the == operator with floating points number, due to approximation issues.

    0 讨论(0)
提交回复
热议问题