Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

0.0 and -0.0 in Java (IEEE 754)

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?

like image 248
MagicFingr Avatar asked Jun 16 '14 07:06

MagicFingr


People also ask

How to distinguish between IEEE 754 positive and negative zero in Java?

In Java, to distinguish between IEEE 754 Positive Zero and IEEE 754 Negative Zero you can use the Double wrapper. Also java.lang.Math.min (-0.0,+0.0) evaluates to -0.0 and java.lang.Math.max (-0.0,+0.0) evaluates to +0.0.

What is IEEE 754 floating point number?

IEEE Standard 754 floating point is the most common representation today for real numbers on computers, including Intel-based PC’s, Macs, and most Unix platforms. There are several ways to represent floating point number but IEEE 754 is the most efficient in most cases.

What are the IEEE 754 rules of arithmetic for signed zeros?

The IEEE 754 rules of arithmetic for signed zeros state that +0.0 + -0.0 depends on the rounding mode. In the default rounding mode, it will be +0.0.

What is a signed zero in IEEE754?

IEEE754 specifies a signed zero. That is, -0.0 and +0.0 are represented individually. They are defined to compare true on equality. Java is implementing this correctly.


2 Answers

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

From the wikipedia article on the negative zero :

According to the IEEE 754 standard, negative zero and positive zero should compare as equal with the usual (numerical) comparison operators, like the == operators of C and Java.

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.

like image 86
Denys Séguret Avatar answered Sep 25 '22 16:09

Denys Séguret


IEEE754 specifies a signed zero. That is, -0.0 and +0.0 are represented individually.

They are defined to compare true on equality.

Java is implementing this correctly.

like image 26
Bathsheba Avatar answered Sep 25 '22 16:09

Bathsheba