在学习JavaScript时看到了Number类型中的NaN和Infinity,因为概念本身是通用的,所以趁机总结了一下Java中的NaN和Infinity。
基本
Java的Float型和Double型各有三个很特别的常量:NaN(非数),POSITIVE_INFINITY(正无穷),NEGATIVE_INFINITY(负无穷)
Float1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20/**
* 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;
/**
* A constant holding a Not-a-Number (NaN) value of type
* {@code float}. It is equivalent to the value returned by
* {@code Float.intBitsToFloat(0x7fc00000)}.
*/
public static final float NaN = 0.0f / 0.0f;
Double1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20/**
* 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 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;
NaN
NaN是Not a Number
的缩写,表示未定义或者不可表示的值,NaN有一个特性,那就是它与任何数都不相等,包括它自己。判断一个数是不是NaN,只能使用Float或者Double的isNaN()
方法,那么这个方法是怎么判断的呢?我们看一看(查看的是Float版,Double除了参数类型都一样,下面二者没有区别的部分都直接使用Float的内容来说明):1
2
3
4
5
6
7
8
9
10
11/**
* Returns {@code true} if the specified number is a
* Not-a-Number (NaN) value, {@code false} otherwise.
*
* @param v the value to be tested.
* @return {@code true} if the argument is NaN;
* {@code false} otherwise.
*/
public static boolean isNaN(float v) {
return (v != v);
}
所以,跟自己不相等的数字,就是NaN.
计算中产生的NaN
什么时候会产生NaN呢?首先,任何与NaN进行的运算,其结果都是NaN.比如下面的运算,不要去想太多,结果就是NaN
1
2
3
4
5
6
7public class Test {
public static void main(String[] args) {
var x = Float.NaN;
var y = x - x + 1;
System.out.println(y);
}
}
其次,从数学角度讲,无法进行的运算(N/0
)或者会产生复数的运算(sqrt(-N)
),都会产生NaN。
(咕咕咕,后面的笔记被鸽了)