java 浮点型 除零_浮点数的除零(学习笔记)

所有的浮点数值计算都遵循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= newBigDecimal(d1);

System.out.println(bd1);//1

double d2 = Double.parseDouble("0.0");

BigDecimal bd2= newBigDecimal(d2);

System.out.println(bd2);//0

double d3 = Double.parseDouble("0");

BigDecimal bd3= newBigDecimal(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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值