special case (inf,-inf,nan) float problems.
Tim Peters
tim.one at home.com
Fri Apr 6 04:36:34 EDT 2001
[Jeremy R Van Haren]
> Let me start of by saying I'm using 1.5.2, so maybe the problem's have
> been fixed in 2.0, but searches don't seem to help.
All IEEE-754 behavior visible from Python is a platform-dependent accident,
meaning that Python inherits whatever the platform C compiler and libraries
happen to do with the 754-*un*aware C code Python is coded in. It can and
does vary across platforms, and across releases, and there's nothing
intentional about any of it.
> Problem #1:
> A float that is set to Nan compares == to just about any other floating
> number. I would think that
Entirely platform-dependent. On WinTel, for example, in Python 2.1 NaN will
just happen to compare *less* than anything, including another NaN:
C:\Code\python\dist\src\PCbuild>python
Python 2.1b2 (#12, Mar 30 2001, 16:46:51) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> inf = 1e300**2
>>> inf
1.#INF
>>> nan = inf - inf
>>> nan
-1.#IND
>>> nan < 3
1
>>> nan < nan
1
>>> nan < inf
1
>>>
It so happens this is because MS's C compiler doesn't generate correct 754
comparison code (the Pentium FPU supports correct comparison, but MS doesn't
generate the Pentium's 754-aware comparison instruction sequence).
> to test:
> python
> >>> print float ('nan') == 0.0
> 1
> >>> print float ('nan') == 0.1
> 1
>
>
> which lead me to my second problem. In order to actually compare
> against nan I compare against the string representation, however:
>
> Problem #2
> on 1.5.2 on RedHat linux 6.2 I get
> >>> print `float('-inf')`,`float('inf')`,`float('nan')`
> -inf inf nan
You get whatever the platform C library's sprintf happens to produce when fed
an inf or nan under a %.17g or %.12g format. As above, WinTel produces yet
another set of strings for these things. In addition, MS's *input* routines
can't read back the strings MS's output routines produce, so you're doubly
hosed there.
> however with 1.5.2 on Solaris 7 I get
> >>> print `float('-inf')`,`float('inf')`,`float('nan')`
> -Infinaty Infinaty NaN
It's certainly funny that the Solaris C library even misspells infinity
<wink -- but that's not coming from Python!>. That should tell you, though,
how seriously C vendors take this stuff.
> I've worked around both of these issues, but I think they are both
> problems. Does anybody know if this has been taken care of in 2.0?
Sorry, it has not. Providing a consistent 754 story across platforms is a
pain in the ass, because none of this behavior is covered by C89, and every
vendor does it a different way. So it requires a large pile of platform
#ifdef'ed code, and platform experts to write and contribute that stuff. But
so far, nobody has volunteered any actual work (talk, yes; code, no).
for-a-small-subset-of-portable-754-features-try-java-ly y'rs - tim
More information about the Python-list
mailing list