NAN and INFINITY in java, javaNANINFINITY
Java floating point operations have two special cases: NAN and INFINITY.
1. INFINITY:
In floating-point calculation, sometimes we encounter a division of 0. How does java solve this problem?
We know that in integer operations, the divisor cannot be 0, or an error occurs directly. However, the concept of "infinity" is introduced in floating point number operations. Let's take a look at the definitions in Double and Float.
Double:
public static final double POSITIVE_INFINITY = 1.0 / 0.0;public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
Float:
public static final float POSITIVE_INFINITY = 1.0f / 0.0f;public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
So what are the effects of these values on the operation:
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 }
From the above tests, we can draw some conclusions:
T1: the infinity in Float is equal to the infinity in Double.
T2: the value obtained by infinitely multiplying 0 is NAN, which is not a number.
T3: In addition to multiplying the value by 0, the calculated value for the infinite value is still infinite.
To determine whether a floating point is INFINITY, use the isInfinite method shown in t4.
2. NAN
public static final double NaN = 0.0d / 0.0;
NAN indicates a non-number. It is not equal to or even not equal to any value. Therefore, the isNAN method is used to determine whether a number is NAN:
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}