Sunday, July 6, 2008

Difference: positive zero 0 and negative zero -0 ?



Recently I have come across some strange things. I know that java language takes positive and negative zero differently than our logical mathematical brain will take. Well the two are certainly different but how does java identifies them? Or more basic question... does java even differenciate between positive and negative zero? The truth is that IEEE floating point specification differentiates between positive and negative zero, but the java specification says that positive zero is equal to negative zero. Please go through the following code and see if you can satisfy your questions...

I am still not able to understand why I am not getting -0 at 2nd and 4th place. I have posted this in javaranch forums, lets see if I can get some clarification. If you have the answer please comment.

1 comment:

brindha said...

Hi Saurabh,

See the below code and output:

public class FloatCheck {

public static void main(String args[])
{
float y= 56.8f;
System.out.println("the value of y after multiplying with positive zero:" +(y*(0.0)));
System.out.println("the value of y after multiplying with positive zero:" +(y*(-0.0)));
}
}

Result:
the value of y after multiplying with positive zero:0.0
the value of y after multiplying with positive zero:-0.0

From this example, you can infer that the positive and negative zeros are taken care in java only if they are floating point numbers and the same is not valid for integers.

Kindly update me with your valuable comments.