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 IEEE float has both positive and negative zero values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With