浮點數的除零(學習筆記)


所有的浮點數值計算都遵循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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM