本文介绍了Java中的0.0和-0.0(IEEE 754)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java与IEEE 754是完全兼容的吗?但是我对java如何决定浮点数加法和减法的符号感到困惑。



这里是我的测试结果:

  double a = -1.5 ; 
double b = 0.0;
double c = -0.0;
System.out.println(b * a); //-0.0
System.out.println(c * a); //0.0
System.out.println(b + b); //0.0
System.out.println(c + b); //0.0
System.out.println(b + c); //0.0
System.out.println(b - c); //0.0
System.out.println(c - b); //-0.0
System.out.println(c + c); // -0.0

我认为在乘法和除法中,符号是这样决定的:sign(a )xor sign(b),
但是我想知道为什么0.0 + -0.0 = 0.0,Java如何决定加法和减法的符号?是否在IEEE 754中描述?



另外我发现Java可以以某种方式区分0.0和-0.0之间的相似性,因为

  System.out.println(c == b); // true 
System.out.println(b == c); // true

java中的==是如何工作的?
是否被视为一种特殊情况?

解决方案

这里没有任何特定于Java的内容,它由IEEE754指定。 / p>

维基百科关于负零的文章应与通常的(数字)值相比较,比较
运算符,就像C和Java的==运算符一样。

所以下面的数字相等:

 (+ 0) - (-0)== +0 

在处理原始浮点数时,您将在所有现代语言中获得相同的行为。


Java is totally compatible with IEEE 754 right? But I'm confused about how java decide the sign of float point addition and substraction.

Here is my test result:

double a = -1.5;
double b = 0.0;
double c = -0.0;
System.out.println(b * a);  //-0.0
System.out.println(c * a);  //0.0
System.out.println(b + b);  //0.0
System.out.println(c + b);  //0.0
System.out.println(b + c);  //0.0
System.out.println(b - c);  //0.0
System.out.println(c - b);  //-0.0
System.out.println(c + c);  //-0.0

I think in the multiplication and division, the sign is decided like: sign(a) xor sign(b),but I wonder why 0.0 + -0.0 = 0.0, how does Java decide the sign in addition and substraction? Is it described in IEEE 754?

Also I found Java can somehow distinguish the similarities between 0.0 and -0.0, since

System.out.println(c == b);    //true
System.out.println(b == c);    //true

How does "==" in java works?Is it treated as a special case?

解决方案

There's nothing here specific to Java, it's specified by IEEE754.

From the wikipedia article on the negative zero :

So the following numbers compare equal:

(+0) - (-0) == +0

You'll get the same behavior in all modern languages when dealing with raw floating point numbers.

这篇关于Java中的0.0和-0.0(IEEE 754)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 11:42