gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:19:35 29 4
gpt4 key购买 nike

我正在阅读 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com