How to get a -0 result in floating point calculations and distinguish it from +0 in C#?
c#, floating-point, zero
Solution
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.
Problem
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?