java - 为什么 float 有符号零?

标签 java floating-point zero negative-zero

为什么 double 有 -0+0?有什么背景和意义?

最佳答案

-0 (通常)被视为 0 *******。当一个 negative float 非常接近于零以至于它可以被认为是 0 时,它可能会导致(要清楚,我指的是 arithmetic underflow ,并且以下计算的结果被解释为正好 ±0,而不仅仅是非常小的数字)。例如

System.out.println(-1 / Float.POSITIVE_INFINITY);
-0.0

If we consider the same case with a positive number, we will receive our good old 0:

System.out.println(1 / Float.POSITIVE_INFINITY);
0.0

******* Here's a case where using -0.0 results in something different than when using 0.0:

System.out.println(1 / 0.0);
System.out.println(1 / -0.0);
Infinity
-Infinity

如果我们考虑函数 1/x,这是有道理的。当 x+ 一侧接近 0 时,我们应该得到 positive 无穷大,但是当它从 - 一侧接近时,我们应该得到 negative 无穷大。函数图应该清楚地说明这一点:

( source )

用数学术语:

enter image description here

enter image description here

这说明了 0-0 在计算意义上的一个显着区别。


这里有一些相关资源,其中一些已经提出。为了完整起见,我将它们包括在内:

关于java - 为什么 float 有符号零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13544342/

相关文章:

java - 选项卡式 Activity 中 fragment 之间的交互

java - 我可以通过 JSON 在运行时动态创建 Java 对象吗?

java - 防止 jackson 将 float 序列化为 double

sql-server - T-SQL,零和连接不匹配

java - 将 ZipEntry 写入文件的最易读方式?

java - 如何在本地覆盖特定的Spring bean,而不是允许全局bean定义覆盖?

matlab - 为什么这个指数方程返回一个全零数组?

md5 - MD5 哈希可以以零开头吗?

c - 是否可以用空格而不是 C 中的零来填充前导零?

php - 接受包含多点系统的值