[Python-Dev] Why is nan != nan?

Mark Dickinson dickinsm at gmail.com
Thu Mar 25 14:17:44 CET 2010

On Thu, Mar 25, 2010 at 12:36 PM, Jesus Cea <jcea at jcea.es> wrote:
> Hash: SHA1
> On 03/25/2010 07:54 AM, Georg Brandl wrote:
>>>>>>> float('nan') in [float('nan')]
>>>> False
>>> Sure, but just think of it as having two different nans there.  (You
>>> could imagine thinking of the id of the nan as part of the payload.)
>> That's interesting.  Thinking of each value created by float('nan') as
>> a different nan makes sense to my naive mind, and it also explains
>> nicely the behavior present right now.  Each nan comes from a different
>> operation and therefore is a "different" non-number.
> Infinites are "not equal" for a good reason, for example.

Well, that depends on your mathematical model.  The underlying
mathematical model for IEEE 754 floating-point is the doubly extended
real line:  that is, the set of all real numbers augmented with two
extra elements "infinity" and "-infinity", with the obvious total
order.  This is made explicit in section 3.2 of the standard:

"The mathematical structure underpinning the arithmetic in this
standard is the extended reals, that is, the set
of real numbers together with positive and negative infinity."

This is the same model that one typically uses in a first course in
calculus when studying limits of functions; it's an appropriate model
for dealing with computer approximations to real numbers and
continuous functions.  So the model has precisely two infinities, and
1/0, 2/0 and (1/0)**(1/0) all give the same infinity.   The decision
to make 1/0 "infinity" rather than "-infinity" is admittedly a little
arbitrary.  For floating-point (but not for calculus!), it makes sense
in the light of the decision to have both positive and negative
floating-point zeros;  1/(-0) is -infinity, of course.

Other models of "reals + one or more infinities" are possible, of
course, but they're not relevant to IEEE 754 floating point.  There's
a case for using a floating-point model with a single infinity,
especially for those who care more about algebraic functions
(polynomials, rational functions) than transcendental ones;  however,
IEEE 754 doesn't make provisions for this.


More information about the Python-Dev mailing list