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

Robert Kern robert.kern at gmail.com
Mon Dec 11 16:17:39 EST 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?

numpy.equal() is the ufunc corresponding to the == operation.

> Could you show an example so that I can better appreciate the difference?

a[a < 0] = 0
a[less(a, 0)] = 0

ma.masked_array(crufty_data, mask=(crufty_data==9999))
ma.masked_array(crufty_data, mask=equal(crufty_data, 9999))

(a >= b) & (a <= c)
greater_equal(a,b) & less_equal(a,c)

null_space = a[s <= eps]
null_space = u[less_equal(s, eps)]

> 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. 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'.

Well, yes. Computer languages reuse symbols that have other meanings in other
contexts. For that matter 'a = b' in Python is definitely not the same thing as
'A = B' on the blackboard.

Suffice it to say that a large majority of people felt that rich comparisons
(and specifically rich comparisons for Numeric arrays) were enough of an
improvement over the use of functions to do the same thing that we got the
language changed to support it. Perhaps it is simply a matter of taste as to
whether or not one thinks it is a improvement, but enough people think it is
that it won't be changing back.

> I tried to dig up something about this "'a==b' return an array" decision from
> the discussion surrounding PEP 207 (on comp.lang.python or on python-dev) but I
> got lost in that thread.

Most of the results of that discussion are in the PEP itself.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list