java - 为什么我们不能使用 '==' 比较两个 float 或 double

标签 java floating-point double equals

我正在阅读 Joshua Bloch 的 Effective java,在 Item 8: Obey the general contract when overriding equals 中写了这个语句

for float fields, use the Float.compare method; and for double fields, use Double.compare. The special treatment of float and double fields is made necessary by the existence of Float.NaN, -0.0f and the analogous double constants;

谁能举例说明为什么我们不能使用 == 进行浮点或双重比较

最佳答案

来自 apidoc, Float.compare :

Compares the two specified float values. The sign of the integer value returned is the same as that of the integer that would be returned by the call:

new Float(f1).compareTo(new Float(f2))

Float.compareTo :

Compares two Float objects numerically. There are two ways in which comparisons performed by this method differ from those performed by the Java language numerical comparison operators (<, <=, ==, >= >) when applied to primitive float values:

  • Float.NaN is considered by this method to be equal to itself and greater than all other float values (including Float.POSITIVE_INFINITY).
  • 0.0f is considered by this method to be greater than -0.0f.

This ensures that the natural ordering of Float objects imposed by this method is consistent with equals.

考虑以下代码:

    System.out.println(-0.0f == 0.0f); //true
    System.out.println(Float.compare(-0.0f, 0.0f) == 0 ? true : false); //false      
    System.out.println(Float.NaN == Float.NaN);//false
    System.out.println(Float.compare(Float.NaN, Float.NaN) == 0 ? true : false); //true
    System.out.println(-0.0d == 0.0d); //true
    System.out.println(Double.compare(-0.0d, 0.0d) == 0 ? true : false);//false     
    System.out.println(Double.NaN == Double.NaN);//false
    System.out.println(Double.compare(Double.NaN, Double.NaN) == 0 ? true : false);//true        

输出不正确,因为不是数字的东西,根本就不是数字,从数字比较的角度来看,应该被视为相等。也很清楚 0=-0 .

让我们看看 Float.compare 确实:

public static int compare(float f1, float f2) {
   if (f1 < f2)
        return -1;           // Neither val is NaN, thisVal is smaller
    if (f1 > f2)
        return 1;            // Neither val is NaN, thisVal is larger

    int thisBits = Float.floatToIntBits(f1);
    int anotherBits = Float.floatToIntBits(f2);

    return (thisBits == anotherBits ?  0 : // Values are equal
            (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
             1));                          // (0.0, -0.0) or (NaN, !NaN)
}

Float.floatToIntBits :

Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "single format" bit layout. Bit 31 (the bit that is selected by the mask 0x80000000) represents the sign of the floating-point number. Bits 30-23 (the bits that are selected by the mask 0x7f800000) represent the exponent. Bits 22-0 (the bits that are selected by the mask 0x007fffff) represent the significand (sometimes called the mantissa) of the floating-point number.

If the argument is positive infinity, the result is 0x7f800000.

If the argument is negative infinity, the result is 0xff800000.

If the argument is NaN, the result is 0x7fc00000.

In all cases, the result is an integer that, when given to the intBitsToFloat(int) method, will produce a floating-point value the same as the argument to floatToIntBits (except all NaN values are collapsed to a single "canonical" NaN value).

来自 JLS 15.20.1. Numerical Comparison Operators <, <=, >, and >=

The result of a floating-point comparison, as determined by the specification of the IEEE 754 standard, is:

  • If either operand is NaN, then the result is false.

  • All values other than NaN are ordered, with negative infinity less than all finite values, and positive infinity greater than all finite values.

  • Positive zero and negative zero are considered equal. For example, -0.0<0.0 is false, but -0.0<=0.0 is true.

  • Note, however, that the methods Math.min and Math.max treat negative zero as being strictly smaller than positive zero.

对于操作数为正零和负零的严格比较,结果将是错误的。

来自 JLS 15.21.1. Numerical Equality Operators == and != :

The result of a floating-point comparison, as determined by the specification of the IEEE 754 standard, is:

Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:

  • If either operand is NaN, then the result of == is false but the result of != is true. Indeed, the test x!=x is true if and only if the value of x is NaN. The methods Float.isNaN and Double.isNaN may also be used to test whether a value is NaN.

  • Positive zero and negative zero are considered equal. For example, -0.0==0.0 is true.

  • Otherwise, two distinct floating-point values are considered unequal by the equality operators. In particular, there is one value representing positive infinity and one value representing negative infinity; each compares equal only to itself, and each compares unequal to all other values.

对于两个操作数都是 NaN 的相等比较结果会出错。

自从 total ordering ( = , < , > , <= , >= )被许多重要的算法使用(见 all the classes that implement the Comparable interface )最好使用比较方法,因为它会产生更一致的行为。

total ordering in the context of the IEEE-754 standard 的后果是正零与负零之差。

例如,如果您使用相等运算符而不是比较方法,并且有一些值集合,并且您的代码逻辑根据元素的顺序做出一些决定,并且您以某种方式开始获得多余的 NaN 值,那么它们'将被视为不同的值,而不是相同的值。

这可能会在程序的行为中产生与 NaN 值的数量/比率成比例的错误。如果你有很多正零和负零,那只是一对会影响你的逻辑错误。

float uses IEEE-754 32 位格式和 double uses IEEE-754 64 位格式。

关于java - 为什么我们不能使用 '==' 比较两个 float 或 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17898266/

相关文章:

python-2.7 - numpy 浮点开始和停止的范围

java - Java中的双数组初始化

ios - 从 Swift 中的字典中读取 - 不工作

java - 如何在Java中播放Ogg文件?

MacOS 上的 Java.lang.UnsupportedClassVersionError

c - 是否可以替换 double 并仅使用 C 中的整数编写程序,并具有相同的输出?

c - 读入一个数组

java - 将嵌入式插件 jar 文件添加到项目中

java - 在java中扩展包含抽象泛型方法的基类

java - 解析整数和 double 之间的不同 NullExceptionHandling