[Numpy-discussion] Scalar-ndarray arguments passed to not_equal
Friedrich Romstedt
friedrichromstedt@gmail....
Thu Feb 11 09:27:47 CST 2010
Keith Goodman:
> No one answered my post either :(
>
> http://old.nabble.com/arrays-and-__eq__-td26987903.html#a26987903
>
> Is it the same issue?
First, before I post the package on github, I dived into Keith's
problem, and here comes the explanation to the wreid behaviour:
I used the code:
class myclass(object):
def __init__(self, arr):
self.arr = arr
def __eq__(self, other):
print "Instance", id(self), "testing with", other, "..."
print "type =", type(other)
if numpy.isscalar(other) or isinstance(other, numpy.ndarray):
x = myclass(self.arr.copy())
x.arr = x.arr == other
else:
raise TypeError()
return x
Then, the session is:
>>> m = myclass([1, 2, 3])
>>> a = numpy.asarray([9, 2, 3])
>>> (m == a).arr
Instance 12345 testing with [9, 2, 3] ...
type = <type 'numpy.ndarray'>
array([False, True, True], dtype = bool)
So far, everything ok. And now, to something completely different ...
>>> a == m
Instance 12345 testing with 9 ...
type = <type 'int'>
Instance 12345 testing with 2 ...
type = <type 'int'>
Instance 12345 testing with 3 ...
type = <type 'int'>
So, the "a" applies the "m" to each of its elements. This is the
Numpy behaviour, because "m" seems scalar to Numpy. The result is a
myclass instance for each element. But it doesn't matter what this
myclass result instance holds, because Numpy uses Python's truth
interpretation to yield the elements of the call to (a == m). This
yields True for each element, because only False, None, 0, and 0.0 are
False in Python. As there is no truth testing operator in "class
myclass", this is the only option for Numpy. So no bug, only features
...
And it is not the same as my problem. In my case, one operand is
changed before being handed over to my replacement for
numpy.not_equal, set by numpy.set_numerical_ops(). The problems seem
to be distinct.
Remark: Note that the second Python answer on
http://old.nabble.com/arrays-and-__eq__-td26987903.html#a26987903
isn't a myclass instance, but a plain array. I noticed this in the
very end ...
Friedrich
More information about the NumPy-Discussion
mailing list