[Python-Dev] Why is nan != nan? (original) (raw)

Mark Dickinson dickinsm at gmail.com
Thu Mar 25 13:24:14 CET 2010


On Thu, Mar 25, 2010 at 11:22 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:

So, I'm specifically putting that proposal on the table for both float and Decimal NaNs in Python:

 "Not a Number" is not a single floating point value. Instead each  instance is a distinct value representing the precise conditions that  created it. Thus, two "NaN" values x and y will compare equal iff they  are the exact same NaN object (i.e. "if isnan(x) then x == y iff  x is y".

I'd also suggest that the language make no guarantees about whether two distinct calls to float('nan') or Decimal('nan') (or any other function call returning a nan) return identical values or not, but leave implementations free to do what's convenient or efficient.

For example, with the current decimal module: Decimal('nan') returns a new nan each time, but Decimal(-1).sqrt() always returns the same nan object (assuming that InvalidOperation isn't trapped). I think it's fine to regard this as an implementation detail.

Python 2.6.2 (r262:71600, Aug 26 2009, 09:40:44) [GCC 4.2.1 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information.

from decimal import * getcontext().traps[InvalidOperation] = 0 x, y = Decimal('nan'), Decimal('nan') id(x), id(y) (47309953516000, 47309930620880) x, y = Decimal(-1).sqrt(), Decimal(-1).sqrt() id(x), id(y) (9922272, 9922272)

Mark



More information about the Python-Dev mailing list