float("nan") in set or as key

Chris Torek nospam at torek.net
Mon May 30 15:58:35 EDT 2011


In article <4de3358b$0$29990$c3e8da3$5496439d at news.astraweb.com>
Steven D'Aprano  <steve+comp.lang.python at pearwood.info> wrote:
>Better than a float method is a function which takes any number as 
>argument:
>
>>>> import math, fractions, decimal
>>>> math.isnan(fractions.Fraction(2, 3))
>False
>>>> math.isnan(decimal.Decimal('nan'))
>True

Ah, apparently someone's been using Larry Wall's time machine. :-)

I should have looked at documentation.  In my case, though:

    $ python
    Python 2.5.1 (r251:54863, Dec 16 2010, 14:12:43) 
    [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import math
    >>> math.isnan
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'module' object has no attribute 'isnan'

>You can even handle complex NANs with the cmath module:
>
>>>> import cmath
>>>> cmath.isnan(complex(1, float('nan')))
>True

Would it be appropriate to have isnan() methods for Fraction,
Decimal, and complex, so that you do not need to worry about whether
to use math.isnan() vs cmath.isnan()?  (I almost never work with
complex numbers so am not sure if the "or" behavior -- cmath.isinf
and cmath.isnan return true if either real or complex part are
Infinity or NaN respectively -- is appropriate in algorithms that
might be working on any of these types of numbers.)

It might also be appropriate to have trivial always-False isinf and
isnan methods for integers.
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)      http://web.torek.net/torek/index.html



More information about the Python-list mailing list