float("nan") in set or as key

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jun 1 20:53:26 EDT 2011


On Tue, 31 May 2011 19:45:01 -0700, Carl Banks wrote:

> On Sunday, May 29, 2011 8:59:49 PM UTC-7, Steven D'Aprano wrote:
>> On Sun, 29 May 2011 17:55:22 -0700, Carl Banks wrote:
>> 
>> > Floating point arithmetic evolved more or less on languages like
>> > Fortran where things like exceptions were unheard of,
>> 
>> I'm afraid that you are completely mistaken.
>> 
>> Fortran IV had support for floating point traps, which are "things like
>> exceptions". That's as far back as 1966. I'd be shocked if earlier
>> Fortrans didn't also have support for traps.
>> 
>> http://www.bitsavers.org/pdf/ibm/7040/C28-6806-1_7040ftnMathSubrs.pdf
> 
> Fine, it wasn't "unheard of".  I'm pretty sure the existence of a few
> high end compiler/hardware combinations that supported traps doesn't
> invalidate my basic point.

On the contrary, it blows it out of the water and stomps its corpse into 
a stain on the ground. NANs weren't invented as an alternative for 
exceptions, but because exceptions are usually the WRONG THING in serious 
numeric work.

Note the "usually". For those times where you do want to interrupt a 
calculation just because of an invalid operation, the standard allows you 
to set a trap and raise an exception.

There's plenty of information available about how and why IEEE-754 was 
created. Go do some research and stop making up rubbish based on what you 
assume must have been their motives. Start with William Kahan, who has 
written extensively about it. If you can find a version of the Apple 
Numerics Manual 2nd Edition, it has an extremely entertaining forward by 
Professor Kahan about the mess that was floating point before IEEE-754.


> If your aim is to support every last clause of IEEE for better or
> worse, then yes that's what Python should do.  If your aim is to make
> Python the best language it can be, then Python should reject IEEE's
> obsolete notions, and throw exceptions when operating on NaN.

Python's usefulness for good numeric work is seriously hurt by the fact 
that it tries so hard to never generate a NAN, and rarely an INF, and 
instead keeps raising annoying exceptions that have to be caught (at 
great expense of performance) and turned into something useful.

You'll note that, out of the box, numpy generates NANs:

>>> import numpy
>>> x = numpy.array([float(x) for x in range(5)])
>>> x/x
Warning: invalid value encountered in divide
array([ nan,   1.,   1.,   1.,   1.])


The IEEE standard supports both use-cases: those who want exceptions to 
bail out early, and those who want NANs so the calculation can continue. 
This is a good thing. Failing to support the standard is a bad thing. 
Despite your opinion, it is anything but obsolete.


-- 
Steven



More information about the Python-list mailing list