Java中含有正无穷(Double.POSITIVE_INFINITY = 1.0 / 0.0)、负无穷(Double.NEGATIVE_INFINITY = -1.0 / 0.0)和非数字(Double.NaN = 0.0d / 0.0)的定义,这些定义都是Double类中的静态常量,如果在我们的一般的算术运算中加入了这些常量,那么算术的结果是否符合数学上的正确性呢?测试代码如下:
- double a = Double.POSITIVE_INFINITY;
- System.out.println("a="+a);
- System.out.println("a+100.0=" + (a + 100.0));
- System.out.println("a+Double.MAX_VALUE=" + (a + Double.MAX_VALUE));
- System.out.println("a - Double.MAX_VALUE=" + (a - Double.MAX_VALUE));
- System.out.println("-a=" + (-a));
- System.out.println("a - a=" + (a - a));
- System.out.println("NaN+100=" + (Double.NaN+100));
- System.out.println("NaN==NaN="+(Double.NaN==Double.NaN));
- System.out.println("NaN+Double.MAX_VALUE=" + (Double.NaN+Double.MAX_VALUE));
- System.out.println("NaN<Double.MAX_VALUE="+(Double.NaN<Double.MAX_VALUE));
- System.out.println("NaN>Double.MAX_VALUE="+(Double.NaN>Double.MAX_VALUE));
- System.out.println("NaN==Double.MAX_VALUE="+(Double.NaN==Double.MAX_VALUE));
- System.out.println("a == a=" + (a == a));
- System.out.println("100 < a=" + (100 < a));
- System.out.println("-a < 0=" + (-a < 0));
- System.out.println("Double.MAX_VALUE < a=" + (Double.MAX_VALUE < a));
输出结果为:
- a=Infinity
- a+100.0=Infinity
- a+Double.MAX_VALUE=Infinity
- a - Double.MAX_VALUE=Infinity
- -a=-Infinity
- a - a=NaN
- NaN+100=NaN
- NaN==NaN=false
- NaN+Double.MAX_VALUE=NaN
- NaN<Double.MAX_VALUE=false
- NaN>Double.MAX_VALUE=false
- NaN==Double.MAX_VALUE=false
- a == a=true
- 100 < a=true
- -a < 0=true
- Double.MAX_VALUE < a=true
结论:
(1)正无穷和负无穷仍然保持数学上的定义;
(2)NaN是非数字,参与算术运算都为NaN,与其他数字比较结果都为false(包括自己)。