[Numpy-discussion] a==b for numpy arrays

Tim Hochberg tim.hochberg at ieee.org
Mon Dec 11 15:09:50 CST 2006

Abel Daniel wrote:
> Robert Kern <robert.kern <at> gmail.com> writes:
>> Abel Daniel wrote:
>>> Now, I think that having a way of getting an element-wise comparison
>>> (i.e. getting an array of bools) is great. _But_ why make that the
>>> result of a '==' comparison? Is there any actual code that does, for
>>> example
>>>>>> result_array = a==b
>>> or any variant thereof?
>> Yes, a lot.
> And it would be much more cumbersome to use something like
> numpy.eq_as_array(a,b) or a.eq_as_array(b) in these cases?
> Could you show an example so that I can better appreciate the difference?
# Replace all zeros with something safe so some calculation doesn't go 
a[a==0] = DELTA

Keep in mind also that all of the comparison operators are overloaded. 
It would be difficult to explain if "a<=0" returned an array, but "a==0" 
returned a scalar.
> The thing I can't get into my head is that '=' in the mathematical sense has a
> well-defined meaning for matrices, this seems to be broken by the current
> behaviour.
Numpy is not really about matrices. Numpy is about array's which are 
different and, for the most part, more powerful. You can use arrays 
inside numpyif you insist, but I personally think you're better off just 
learning to use arrays. Tastes vary though.

>  That is, what "A+B" on a blackboard in a math class means maps nicely
> to what 'a+b' means with a and b being numpy arrays. But 'A=B' means something
> completely different than 'a==b'. 
One thing to keep in mind is that what you have in mind, which is 
equivalent to numpy.all(a==b) is almost always a bad idea when using 
floating point.


More information about the Numpy-discussion mailing list