[Numpy-discussion] Unexpected integer overflow handling
Zachary Pincus
zpincus@stanford....
Mon Jan 7 15:03:14 CST 2008
Hello all,
On my (older) version of numpy (1.0.4.dev3896), I found several
oddities in the handling of assignment of long-integer values to
integer arrays:
In : numpy.array([2**31], dtype=numpy.int8)
------------------------------------------------------------------------
---
ValueError Traceback (most recent call
last)
/Users/zpincus/<ipython console>
ValueError: setting an array element with a sequence.
While this might be reasonable to be an error condition, the precise
error raised seems not quite right! But not all overflow errors are
caught in this way:
In : numpy.array([2**31-1], dtype=numpy.int8)
Out: array([-1], dtype=int8)
As above, numpy is quite happy allowing overflows; it just breaks
when doing a python long-int to int conversion. The conversion from
numpy-long-int to int does the "right thing" though (if by "right
thing" you mean "allows silent overflow", which is a matter of
discussion elsewhere right now...):
In : numpy.array(numpy.array([2**31], dtype=numpy.int64),
dtype=numpy.int8)
Out: array([0], dtype=int8)
At least on item assignment, the overflow exception is less odd:
In : a = numpy.empty(shape=(1,), dtype=numpy.int8)
In : a[0] = 2**31
------------------------------------------------------------------------
---
OverflowError Traceback (most recent call
last)
/Users/zpincus/<ipython console>
OverflowError: long int too large to convert to int
Things work right with array element assignment:
In : a[0] = numpy.array([2**31], dtype=numpy.int64)[0]
But break again with array scalars, and with the strange ValueError
again!
In : a[0] = numpy.array(2**31, dtype=numpy.int64)
------------------------------------------------------------------------
---
ValueError Traceback (most recent call
last)
/Users/zpincus/<ipython console>
ValueError: setting an array element with a sequence.
Note that non-long-int-to-int array scalar conversions work:
In : a[0] = numpy.array(2**31-1, dtype=numpy.int64)
Is this still the case for the current version of numpy?
Best,
Zach
More information about the Numpy-discussion
mailing list