Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java print a negative sign in front of 0 when 0 with no sign is equal and more commonly accepted as correct?

Tags:

java

In java the output of the following code is 0.0,-0.0,-0.0. what is the reason for these different answers?

System.out.print((0.0 % -1)+","+(-0.0 % 1)+","+ (-0.0 % -1));
like image 916
Sammy Avatar asked Mar 21 '23 04:03

Sammy


2 Answers

The modulo operator just takes the remainder once you divide a number by that.

Divide 0 by -1 and you get 0, so the result is 0.

Floating points and doubles do actually know the difference between -0 and +0 though, so when you take the remainder of a -0 you get -0 as that is still a valid number between 0 and 1 (or -1).

This is a quirk of the way floating point numbers work, and of the special properties of 0 as the same does not hold true for other numbers:

System.out.println((0.0 % -1)+","+(-0.0 % 1)+","+ (-0.0 % -1));

System.out.println((0 % -1)+","+(-0 % 1)+","+ (-0 % -1));

System.out.println((3 % -1)+","+(-3 % 1)+","+ (-3 % -1));

Displays:

0.0,-0.0,-0.0 
0,0,0 
0,0,0

Since references were requested:

Floating points are defined in IEEE_754-1985:

http://en.wikipedia.org/wiki/IEEE_754-1985

There is a whole wikipedia page discussing Negative Zero:

http://en.wikipedia.org/wiki/Negative_zero

This also at least partly explains why the modulo works as:

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.

Since modulo produces a number >= to 0 and < than the given value then -0 already satisfies the >= requirement (since -0 == 0) and the operation can just end immediately.

like image 76
Tim B Avatar answered Apr 06 '23 03:04

Tim B


Because IEEE float has both positive and negative zero values.

like image 28
Hot Licks Avatar answered Apr 06 '23 03:04

Hot Licks