Search code examples
pythoninfinity

Why does float('inf') == float('inf') return True, but float('inf') - float('inf') == float('inf') returns False?


Why does this happen in Python?

  • float('inf') == float('inf') returns True,
  • float('inf') + float('inf') == float('inf') returns True,
  • float('inf') * float('inf') == float('inf') returns True,
  • float('inf') - float('inf') == float('inf') returns False,
  • float('inf') / float('inf') == float('inf') returns False.

My best guess, if I think about limits, is related with the result of this operation:

limx→+∞(f(x) ▢ g(x)) where limx→+∞ f(x) = +∞ and limx→+∞ g(x) = +∞, which returns +∞ if ▢ is + or *, but it is not defined (it could return every value) if ▢ is - or /.

I am very puzzled, though.


Solution

  • Before the comparison of

    float('inf') - float('inf') == float('inf')
    

    can be made, the result of

    float('inf') - float('inf')
    

    will be calculated. That result is NaN.

    It is NaN because the amounts of infinity may differ. It's explained on the Stack Overflow sister site Math.SE, known as the Hilbert hotel paradox:

    From a layman's perspective, imagine that I have an infinite number of hotel rooms, each numbered 1, 2, 3, 4, ...

    Then I give you all of them. I would have none left, so ∞−∞=0

    On the other hand, if I give you all of the odd-numbered ones, then I still have an infinite number left. So ∞−∞=∞.

    Now suppose that I give you all of them except for the first seven. Then ∞−∞=7. While this doesn't explain why this is indeterminate, hopefully you can agree that it is indeterminate!

    The best number to represent indeterminate is NaN. Comparing NaN to anything is always False, even comparing NaN against itself.

    Besides that quite "logical" explanation, we find that Python uses IEEE754 representation for floating point calculation.

    You'd typically need to buy the IEEE754 specification, but luckily we see some draft version online. The relevant chapter IMHO is 7.2:

    For operations producing results in floating-point format, the default result of an operation that signals the invalid operation exception shall be a quiet NaN [...]

    [...]

    d) addition or subtraction or fusedMultiplyAdd: magnitude subtraction of infinities, such as: addition(+∞, −∞)