Search code examples
c#floating-pointinfinity

When do we need to use float.PositiveInfinity and float.NegativeInfinity?


When do we need to use the Infinity values, kindly add a real-world sample if available.


Solution

  • For example, negative infinity is a natural maximum value of an empty list. With this, you have: max(l1 + l2) = max(max(l1), max(l2)), where l1 and l2 are arbitrary lists, possibly empty.

    A real-world application of this principle:

    float Max(IEnumerable<float> list)
    {
        // invariant: max contains maximum over the part of the list
        // considered so far
        float max = float.NegativeInfinity;
        foreach (float v in list)
            if (v > max)
                max = v;
        return max;
    }