[Numpy-discussion] Conversion float64->int bugged?
saintmlx at apstat.com
Mon Jul 9 18:13:34 EDT 2007
The conversion from a numpy scalar to a python int is not consistent
with python's native conversion (or numarray's): if the scalar is out
of bounds for an int, python and numarray automatically create a long
while numpy still creates an int... with the wrong value.
N.B. I am new to numpy, so please forgive me if this issue has already
been discussed. I've quickly searched the archives and Travis's "Guide
to NumPy", with no success.
e.g. (using numpy 1.0.3):
Python 2.4.3 (#2, Apr 27 2006, 14:43:58)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy import *
>>> l= [1e3, 1e9, 1e15, -1e3, -1e9, -1e15]
>>> a= array(l)
>>> map(int, l)
[1000, 1000000000, 1000000000000000L, -1000, -1000000000,
>>> map(int, a)
[1000, 1000000000, -2147483648, -1000, -1000000000, -2147483648]
>>> map(long, a)
[1000L, 1000000000L, 1000000000000000L, -1000L, -1000000000L,
IMHO, numpy's conversions to int should behave like Python's 'float_int'
or 'long_int' functions (see $PYTHON_SRC_DIR/Objects/floatobject.c,
$PYTHON_SRC_DIR/Objects/longobject.c): if it doesn't fit in an int,
return a long. For now (svn), it seems that numpy is always using
PyInt_FromLong after an implicit C cast to long (which silently fails;
Is there any reason not to change this?
More information about the NumPy-Discussion