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));
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));
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.
Because float supports negative zero. Changing the sign would cause a loss of information, however meaningless that information might be.
So basically it comes down a display problem, not a data representation; if you want the "correct" rendition, provide a formatting string for your output. This holds true for any sort of scenario where you dislike the default
ToString() representation.
The reason is to do with IEEE-754 signed zero rules. Specifically, because a floating point number is not "infinitely" precise and it "simplifies" handling complex numbers.