How are Inf and NaN implemented?

Viewed 1062

As mathematical concepts, I am well aware of what inf and nan actually are. But what I am really interested in is how they are implemented in programming languages.

In python, I can use inf and nan in arithmetic and conditional expressions, like this:

>>> nan = float('nan')
>>> inf = float('inf')
>>> 1 + inf
inf
>>> inf + inf
inf
>>> inf - inf
nan

This would lead me to believe that python internally has a special reserved bit sequence for these two mathematical quantities, and no other number can assume these positions. Is my assumption correct? Can you please enlighten me in this regard?

If my assumption is correct, then this can be explained easily:

>>> inf == inf
True

However, this is not:

>>> nan == nan
False

Obviously, in mathematics, this is the right answer. But how does python know that it should spit out False in this instance?

Furthermore, how does python's implementation differ from that of java or c++?

2 Answers
Related