java中的NAN和INFINITY

java浮點數運算中有兩個特殊的狀況:NAN、INFINITY。java

一、INFINITY:測試

在浮點數運算時,有時咱們會遇到除數爲0的狀況,那java是如何解決的呢?it

咱們知道,在整型運算中,除數是不能爲0的,不然直接運行異常。可是在浮點數運算中,引入了無限這個概念,咱們來看一下Double和Float中的定義。float

Double:方法

public static final double POSITIVE_INFINITY = 1.0 / 0.0;

public static final double NEGATIVE_INFINITY = -1.0 / 0.0;

 

Float:im

public static final float POSITIVE_INFINITY = 1.0f / 0.0f;

public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;

 

那麼這些值對運算會有什麼影響呢?異常

咱們先思考一下下面幾個問題:static

Float和Double中的無限有什麼區別?img

無限乘以0會是什麼?思考

0除以0又會有什麼結果?

 

再來看下面的示例:

複製代碼

public static void main(String[] args) {

         float fPos=Float.POSITIVE_INFINITY;
         float fNeg=Float.NEGATIVE_INFINITY;
         double dPos=Double.POSITIVE_INFINITY;
         double dNeg=Double.NEGATIVE_INFINITY;
         
         //t1
         System.out.println(fPos==dPos);  //output: true
         System.out.println(fNeg==dNeg);  //output: true
         
         //t2
         System.out.println(fPos*0);  //output: NAN
         System.out.println(fNeg*0);  //output: NAN
         
         //t3
         System.out.println(fPos==(fPos+10000));  //output: true
         System.out.println(fPos==(fPos*10000));  //output: true
         System.out.println(fPos==(fPos/0));  //output: true

         //t4
         System.out.println(Double.isInfinite(dPos));  //output: true
         
    }

複製代碼

從上面幾組測試中咱們可得出一些結論:

t1: Float中的無限和Double中的無限是相等的。

t2: 無限乘以0獲得的值爲NAN,即非數字。

t3: 除了乘以0外,對無限值作運算所得的值仍是無限

要判斷一個浮點數是否爲INFINITY,可用t4中所示的isInfinite方法。

二、NAN

java中的NAN是這麼定義的:

public static final double NaN = 0.0d / 0.0;

NAN表示非數字,它與任何值都不相等,甚至不等於它本身,因此要判斷一個數是否爲NAN要用isNAN方法:

public static void main(String[] args) {
        double nan=Double.NaN;
        System.out.println(nan==nan);  //output: false
        System.out.println(Double.isNaN(nan));  //output: true
}
相關文章
相關標籤/搜索