所有的浮點數值計算都遵循IEEE 754規範,用於表示溢出和出錯情況的三個特殊的浮點數值,±inf、NaN。 源碼註釋: If the argument is {@code 0x7ff0000000000000L}, the result is positive infinity.If the ar ...
所有的浮點數值計算都遵循IEEE 754規範,用於表示溢出和出錯情況的三個特殊的浮點數值,±inf、NaN。
源碼註釋:
If the argument is {@code 0x7ff0000000000000L}, the result is positive infinity.
If the argument is {@code 0xfff0000000000000L}, the result is negative infinity.
If the argument is any value in the range
* {@code 0x7ff0000000000001L} through
* {@code 0x7fffffffffffffffL} or in the range
* {@code 0xfff0000000000001L} through
* {@code 0xffffffffffffffffL}, the result is a NaN.
Demo:1.0、0.0和0的浮點數值輸出:
double d1 = Double.parseDouble("1.0"); BigDecimal bd1 = new BigDecimal(d1); System.out.println(bd1);//1 double d2 = Double.parseDouble("0.0"); BigDecimal bd2 = new BigDecimal(d2); System.out.println(bd2);//0 double d3 = Double.parseDouble("0"); BigDecimal bd3 = new BigDecimal(d3); System.out.println(bd3);//0
從結果可以看出,1.0、0.0、0都不能使用二進位來準確的表示,所以只能使用最接近的浮點值來代替。
1)1.0/0的結果是什麼?為什麼?
Infinity
原因:類型不同,低精度向高精度轉化,相當於1.0/0.0(public static final double POSITIVE_INFINITY = 1.0 / 0.0;和Double.LongBitsToRawLongDouble(0x7ff0000000000000L))。
通過doubleToRawLongBits方法來證明:
double a = 1.0 / 0; long b = Double.doubleToRawLongBits(a); System.out.println(b);//9218868437227405312 Long c=0x7ff0000000000000L; System.out.println(c.longValue());//9218868437227405312
另一種解釋:無限接近於1的數除以無限接近於0的數,舉例:1/0.1=10;1/0.01=100;1/0.001=1000;1/0.0001=10000......無窮大。
2)0/0的結果是什麼?為什麼?
ArithmeticException
原因:類型相同,無需轉化。
文檔說明,Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class.