Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 /.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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(+∞, −∞)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading