Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test for negative zero?

Initially I thought Math.Sign would be the proper way to go but after running a test it seems that it treats -0.0 and +0.0 the same.

like image 388
ChaosPandion Avatar asked Jan 19 '11 19:01

ChaosPandion


People also ask

How do you get negative zero?

One may obtain negative zero as the result of certain computations, for instance as the result of arithmetic underflow on a negative number (other results may also be possible), or −1.0×0.0 , or simply as −0.0 .

Is it possible zero be negative?

The number zero is neither positive nor negative.


2 Answers

Here's a grotty hack way of doing it:

private static readonly long NegativeZeroBits =     BitConverter.DoubleToInt64Bits(-0.0);  public static bool IsNegativeZero(double x) {     return BitConverter.DoubleToInt64Bits(x) == NegativeZeroBits; } 

Basically that's testing for the exact bit pattern of -0.0, but without having to hardcode it.

like image 184
Jon Skeet Avatar answered Sep 17 '22 19:09

Jon Skeet


After a bit of searching I finally made it to Section 7.7.2 of the C# specification and came up with this solution.

private static bool IsNegativeZero(double x) {     return x == 0.0 && double.IsNegativeInfinity(1.0 / x); } 
like image 45
ChaosPandion Avatar answered Sep 17 '22 19:09

ChaosPandion