What's wrong with using == to compare floats in Java?

后端 未结 21 1933
你的背包
你的背包 2020-11-22 01:00

According to this java.sun page == is the equality comparison operator for floating point numbers in Java.

However, when I type this code:



        
21条回答
  •  死守一世寂寞
    2020-11-22 01:16

    The following automatically uses the best precision:

    /**
     * Compare to floats for (almost) equality. Will check whether they are
     * at most 5 ULP apart.
     */
    public static boolean isFloatingEqual(float v1, float v2) {
        if (v1 == v2)
            return true;
        float absoluteDifference = Math.abs(v1 - v2);
        float maxUlp = Math.max(Math.ulp(v1), Math.ulp(v2));
        return absoluteDifference < 5 * maxUlp;
    }
    

    Of course, you might choose more or less than 5 ULPs (‘unit in the last place’).

    If you’re into the Apache Commons library, the Precision class has compareTo() and equals() with both epsilon and ULP.

提交回复
热议问题