[Numpy-discussion] a==b for numpy arrays
robert.kern at gmail.com
Mon Dec 11 13:32:27 CST 2006
Abel Daniel wrote:
> My unittests got broken because 'a==b' for numpy arrays returns an
> array instead of returning True or False:
>>>> import numpy
>>>> a = numpy.array([1, 2])
>>>> b = numpy.array([1, 4])
> array([True, False], dtype=bool)
> This means, for example:
>>>> if a==b:
> ... print 'equal'
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> ValueError: The truth value of an array with more than one element is ambiguous.
> Use a.any() or a.all()
> 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
>>>> result_array = a==b
> or any variant thereof?
Yes, a lot.
Rich comparisons have been in Numeric for quite a long time, now. I'm not sure
what version of Numeric you were transitioning from that didn't do this, but it
must have been extremely old. I suspect, however, that you were using a
relatively recent version of Numeric and simply did not know that the rich
comparisons were taking place.
Now, what did change from Numeric to numpy (also, from Numeric to numarray) is
that arrays can no longer be used as a truth value. It used to be that Numeric
arrays' truth value was the same as Numeric.sometrue(arr). It is likely that
your unit tests were expecting (a == b) to be the same as Numeric.alltrue(a ==
b). Since this is not the case, your unit tests had bugs.
"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