今天在排除代碼中的Bug的時候,在浮點數運算過程中遇到了NAN與INFINITY的問題。特此記錄一下。 首先明確一點的是,java浮點數中有兩個特殊情況:NAN,INFINITY
NAN是一個特殊的值。在JDK中,NAN是這么定義的:
/** * A constant holding a Not-a-Number (NaN) value of type * {@code double}. It is equivalent to the value returned by * {@code Double.longBitsToDouble(0x7ff8000000000000L)}. */ public static final double NaN = 0.0d / 0.0;特意將注釋也copy下來。相信加上注釋,同學們就都明白是什么意思了。Not-a-Number準確道出了NAN的含義。
@Test public void testNan() { double NaN1 = Double.NaN; double NaN2 = 0.0 / 0.0; System.out.PRintln(Double.isNaN(NaN1)); //true System.out.println(Double.isNaN(NaN2)); //true System.out.println(NaN1 == NaN1); //false }NAN表示非數字,它與任何值都不相等,甚至不等于它自己,所以要判斷一個數是否為NAN要用isNAN方法。
INFINITY主要是為了解決除數為0的情況。稍微有點數學基礎的同學,都應該明白無限這個概念。
/** * A constant holding the positive infinity of type * {@code double}. It is equal to the value returned by * {@code Double.longBitsToDouble(0x7ff0000000000000L)}. */ public static final double POSITIVE_INFINITY = 1.0 / 0.0; /** * A constant holding the negative infinity of type * {@code double}. It is equal to the value returned by * {@code Double.longBitsToDouble(0xfff0000000000000L)}. */ public static final double NEGATIVE_INFINITY = -1.0 / 0.0; /** * A constant holding the positive infinity of type * {@code float}. It is equal to the value returned by * {@code Float.intBitsToFloat(0x7f800000)}. */ public static final float POSITIVE_INFINITY = 1.0f / 0.0f; /** * A constant holding the negative infinity of type * {@code float}. It is equal to the value returned by * {@code Float.intBitsToFloat(0xff800000)}. */ public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;這是JDK中的相關定義。很容易看出來,double與float中都有INFINITY的相關定義。
@Test public void testInfinity() { double Inf1 = Double.POSITIVE_INFINITY; double Inf2 = Double.NEGATIVE_INFINITY; float Inf3 = Float.POSITIVE_INFINITY; float Inf4 = Float.NEGATIVE_INFINITY; System.out.println(Double.isInfinite(Inf1)); //true System.out.println(Float.isInfinite(Inf3)); //true System.out.println(Inf1 == Inf3); //true System.out.println(Inf2 == Inf4); //true System.out.println(Inf1 * 0); //NaN System.out.println(Inf1 + 1); //Infinity System.out.println(Inf1 * 0.4); //Infinity System.out.println(Inf1 / 0); //Infinity }從測試代碼中,可以得出如下結論: 1.double或者float判斷是不是INFINITY都使用isInfinite方法。 2.double中的INFINITY與float中的INFINITY是相等的。 3.INFINITY乘以0得到NAN。 4.INFINITY做除了乘以0意外的任何四則運算,得到的結果仍然是INFINITY。
第三點跟第四點,結果INFINITY的數學性質,很容易理解。
新聞熱點
疑難解答