看JDK源码时看到Math下边有个函数:
public static float max(float a, float b) { if (a != a) return a; // a is NaN if ((a == 0.0f) && (b == 0.0f) && (Float.floatToRawIntBits(a) == negativeZeroFloatBits)) { // Raw conversion ok since NaN can't map to -0.0. return b; } return (a >= b) ? a : b; }
注意 if (a != a) return a; // a is NaN
a竟然可能不等于a,这是什么逻辑?查了一下,NaN表示非数值,它不与任何数值相等,包括它自己。注意这一点跟
POSITIVE_INFINITY、NEGATIVE_INFINITY不一样,写个demo验证一下:
public static void main(String[] args) { System.out.println(Float.POSITIVE_INFINITY * 0); System.out.println(Float.NEGATIVE_INFINITY * 0); System.out.println((Float.POSITIVE_INFINITY * 0) == Float.POSITIVE_INFINITY); System.out.println((Float.NEGATIVE_INFINITY * 0) == Float.NEGATIVE_INFINITY); System.out.println(Float.POSITIVE_INFINITY / 0); System.out.println(Float.NEGATIVE_INFINITY / 0); System.out.println((Float.POSITIVE_INFINITY / 0) == Float.POSITIVE_INFINITY); System.out.println((Float.NEGATIVE_INFINITY / 0) == Float.NEGATIVE_INFINITY); float a = Float.POSITIVE_INFINITY; System.out.println(a == a); float b = Float.NaN; System.out.println(b == b); System.out.println(Double.isNaN(b)); }
输出:
NaN
NaN
false
false
Infinity
-Infinity
true
true
true
false
true