[Numpy-discussion] Truth value of an array
Fri Apr 18 13:10:55 CDT 2008
On 18/04/2008, Olivier <firstname.lastname@example.org> wrote:
> Let's restrict the discussion the case to boolean arrays (dtype bool),
> since all the comparisons (A==B, A!=B, A<B etc. return boolean
> So I have an array filled with booleans. Is there a reason not to map
> "bool(A)" to "A.all()" but instead raise an exception?
> As far as I can see, "if A==B" is clear enough; one always means
> "(A==B).all()". Isn't that so?
> I would like to see examples where there is clearly an ambiguity so
> that I understand the benefit of having an exception raised for
> boolean matrices instead of simply using all().
> If there is no such clear example, then why not map "bool(A)" to
> "A.all()" in numpy?
In : import numpy as np
In : A = np.array([0,1])
In : B = np.array([0,0])
In : (A==B).all()
In : (A!=B).all()
One would expect A!=B to be the logical opposite of A==B, but with
your proposed suggestion it is not.
In math, when comparing functions, one can compare the functions as a
whole, or one can compare them pointwise. numpy's implementation does
pointwise comparison, for a variety of good reasons. As for why
converting an array to a boolean doesn't automatically do all(), if
you don't know you are dealing with an array and using all(), you will
surely shoot yourself in the foot sooner rather than later (as the
above example shows). If you do, simply wrapping it in all() is easy
More information about the Numpy-discussion