[Numpy-discussion] numpy migration
Duncan Smith
buzzard@urubu.freeserve.co...
Mon Apr 23 10:55:29 CDT 2007
Hello,
Since moving to numpy I've had a few problems with my existing
code. It basically revolves around the numpy scalar types. e.g.
------------------------------------------------
>>> import Numeric as N
>>> a = N.array([[0,1],[2,3]])
>>> a
array([[0, 1],
[2, 3]])
>>> i = a[0,0]
>>> 1/i
Traceback (most recent call last):
File "<pyshell#30>", line 1, in -toplevel-
1/i
ZeroDivisionError: integer division or modulo by zero
>>> b = a * 1.5
>>> b
array([[ 0. , 1.5],
[ 3. , 4.5]])
>>> N.floor(b)
array([[ 0., 1.],
[ 3., 4.]])
>>> ================================ RESTART
================================
>>> import numpy as N
>>> a = N.array([[0,1],[2,3]])
>>> a
array([[0, 1],
[2, 3]])
>>> i = a[0,0]
>>> 1/i
0
>>> b = a * 1.5
>>> b
array([[ 0. , 1.5],
[ 3. , 4.5]])
>>> N.floor(b)
array([[ 0., 1.],
[ 3., 4.]])
>>> a = N.array([[0,1],[2,3]], dtype='O')
>>> a
array([[0, 1],
[2, 3]], dtype=object)
>>> i = a[0,0]
>>> 1/i
Traceback (most recent call last):
File "<pyshell#45>", line 1, in -toplevel-
1/i
ZeroDivisionError: integer division or modulo by zero
>>> b = a * 1.5
>>> b
array([[0.0, 1.5],
[3.0, 4.5]], dtype=object)
>>> N.floor(b)
Traceback (most recent call last):
File "<pyshell#48>", line 1, in -toplevel-
N.floor(b)
AttributeError: 'float' object has no attribute 'floor'
>>>
----------------------------------------------
An additional problem involves classes that have e.g. __rmul__ methods
defined and are sufficiently similar to numpy arrays that my classes'
__rmul__ methods are not invoked when using numpy scalars.
Using the 'O' dtype gives me Python types that raise zero division
errors appropriately (for my code) and the desired calls to e.g.
__rmul__ methods, but reduced functionality in other repects.
I might (I hope) be missing something obvious; but it seems like, to be
safe, I'm going to have to do a lot of explicit conversions to Python
types (or abandon catching zero division errors, and documenting some of
my classes to highlight that whether scalar * a equals a * scalar
depends on whether a.__rmul__ is called, which depends on the type of
scalar).
I suppose I might get round both issues by subclassing existing numpy
dtypes. Any ideas? Cheers. TIA.
Duncan
More information about the Numpy-discussion
mailing list