NaN again - and IEEE arithmatics

Tim Peters tim_one at email.msn.com
Sat May 13 00:56:32 EDT 2000


[posted and mailed]

[Huaiyu Zhu]
> Sometime ago I asked about reading back from a file containing arrays with
> NaN as elements.  Someone kindly suggested
>
> >>> from math import exp
> >>> NaN = exp(1000)/exp(1000)
> >>> NaN
> nan
>
> However this breaks in 1.6 (or maybe because it is installed on another
> machine).

Different machine sounds more plausible.  Python itself knows nothing about
NaNs, and all visible behavior wrt them is a platform-dependent accident.

> >>> import math
> >>> NaN = math.exp(1000) / math.exp(1000)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   OverflowError: math range error
>
> Any suggestion of how to deal with it in this case?  Is there a
> generic way?

THere's nothing you can do that's guaranteed to work.  Here's a way to make
a NaN that's quite *likely* to work on any IEEE-754 platform, though:

>>> Inf = 1e300**2
>>> NaN = Inf - Inf
>>> NaN
-1.#IND
>>> Inf
1.#INF
>>>

Since that was a Windows session, that's how Microsoft happens to spell NaN
and infinity these days.

> If I understand correctly, NaN is a standard feature in IEEE
> floating point arithmatics.

Yes.

> So why isn't there a predefined class or object for NaN?

Basically because IEEE-754 is primarily a hardware standard.  The things it
defines may as well not exist if your *software* doesn't know about them.
In Python's case, Python is implemented in C, and it's C that provides no
portable way to get at this stuff.  So Python can't either, at least not
without a huge pile of #ifdef's, one for each platform, and enough different
people volunteering with the right combination of platform + 754 expertise
to write all that crap.

The next iteration of the C standard is supposed to address this.  Then it
will be much easier to address it in Python too.  In the meantime, you're
really on your own with this stuff, be it from Python, Perl, C, C++,
Fortran, ...

hard-to-express-what-there-are-no-words-for-ly y'rs  - tim






More information about the Python-list mailing list