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

所有的浮点数值计算都遵循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.

posted @   江河湖泊  阅读(2001)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
点击右上角即可分享
微信分享提示