国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Double 中的 NAN與INFINITY

2019-11-08 01:45:11
字體:
來源:轉載
供稿:網友

今天在排除代碼中的Bug的時候,在浮點數運算過程中遇到了NAN與INFINITY的問題。特此記錄一下。 首先明確一點的是,java浮點數中有兩個特殊情況:NAN,INFINITY

1.NAN

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方法。

2.INFINITY

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的數學性質,很容易理解。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 乡城县| 洪江市| 三明市| 都昌县| 嘉禾县| 泰和县| 南投市| 灵川县| 华亭县| 广水市| 花莲县| 大城县| 图们市| 鹰潭市| 交口县| 汾西县| 新竹县| 周至县| 鹿邑县| 青海省| 垫江县| 新泰市| 长葛市| 芜湖县| 西乌珠穆沁旗| 云浮市| 都安| 四子王旗| 乐安县| 仁怀市| 白城市| SHOW| 英超| 乌鲁木齐市| 湛江市| 长寿区| 闵行区| 平定县| 确山县| 中江县| 凤冈县|