Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a -0 result in floating point calculations and distinguish it from +0 in C#?

The MSDN documentation mentions that double type includes negative zero. However, both -1.0 / double.PositiveInfinity and -double.Epsilon / 2 appear to return normal 0 (and compare equal to it). How can I get -0?

like image 203
Alexey Romanov Avatar asked Jun 25 '09 13:06

Alexey Romanov


1 Answers

Here is a practical example of differentiating between the two without examining the bits. MSDN links here and here assisted me in constructing this example.

static void Main(string[] args)
{
    float a = 5 / float.NegativeInfinity;
    float b = 5 / float.PositiveInfinity;
    float c = 1 / a;
    float d = 1 / b;
    Console.WriteLine(a);
    Console.WriteLine(b);
    Console.WriteLine(c);
    Console.WriteLine(d);
}

Output:

0
0
-Infinity
Infinity

Take note that -0 and 0 both look the same for comparisons, output, etc. But if you divide 1 by them, you get a -Infinity or Infinity, depending on which zero you have.

like image 151
Brian Avatar answered Oct 21 '22 00:10

Brian