[Python-bugs-list] long(+/- infinity) returns nonsense (PR#89)

tim_one@email.msn.com tim_one@email.msn.com
Mon, 27 Sep 1999 02:03:08 -0400 (EDT)


Full_Name: Tim Peters
Version: 1.5.2
OS: Win95
Submission from: 1cust47.tnt4.bos1.da.uu.net (63.21.45.47)


I've been meaning to fix this for years:  PyLong_FromDouble returns
platform-specific gibberish if given an infinity as input.  On Windows,
it returns 0(!):

>>> i = 1e200**2
>>> i
1.#INF
>>> long(i)
0L
>>>

That's because the Windows frexp returns an exponent of 0 given an
infinity.  frexp was defined before IEEE-754 came into vogue, so
there's no portable behavior you can count on here.  This one is
particularly nasty because converting an extremely large long
(like 1L << 5000) to float returns an infinity, then converting
that back to 0 is the most surprising result imaginable.

Anyway, the attached patch uses a cheap platform-independent test
to weed out infinities before frexp is called.  It may cause the
hardware underflow flag to get set, but so it goes; until C9X,
there are no "neutral" platform-independent ways to test for an
infinity either.

After the patch:

>>> i = 1e200**2
>>> i
1.#INF
>>> long(i)
Traceback (innermost last):
  File "<stdin>", line 1, in ?
OverflowError: cannot convert float infinity to long
>>>

I confirm that, to the best of my knowledge and belief, this
contribution is free of any claims of third parties under
copyright, patent or other rights or interests ("claims").  To
the extent that I have any such claims, I hereby grant to CNRI a
nonexclusive, irrevocable, royalty-free, worldwide license to
reproduce, distribute, perform and/or display publicly, prepare
derivative versions, and otherwise use this contribution as part
of the Python software and its related documentation, or any
derivative versions thereof, at no cost to CNRI or its licensed
users, and to authorize others to do so.

I acknowledge that CNRI may, at its sole discretion, decide
whether or not to incorporate this contribution in the Python
software and its related documentation.  I further grant CNRI
permission to use my name and other identifying information
provided to CNRI by me for use in connection with the Python
software and its related documentation.

*** Objects/Old/longobject.c	Wed Jan 27 11:48:26 1999
--- Objects/New/longobject.c	Mon Sep 27 01:33:06 1999
***************
*** 145,150 ****
--- 145,155 ----
  	double frac;
  	int i, ndig, expo, neg;
  	neg = 0;
+ 	if (dval && dval * 0.5 == dval) {
+ 		PyErr_SetString(PyExc_OverflowError,
+ 			"cannot convert float infinity to long");
+ 		return NULL;
+ 	}
  	if (dval < 0.0) {
  		neg = 1;
  		dval = -dval;