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

前端 未结 5 1694
难免孤独
难免孤独 2021-01-05 17:44

The MSDN documentation mentions that double type includes negative zero. However, both -1.0 / double.PositiveInfinity and -double.Epsilon / 2

5条回答
  •  盖世英雄少女心
    2021-01-05 18:34

    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.

提交回复
热议问题