[Numpy-discussion] Why is the truth value of ndarray not simply size>0 ?
Sun Sep 13 14:35:48 CDT 2009
On Sun, Sep 13, 2009 at 05:30, Robert <email@example.com> wrote:
> Neil Martinsen-Burrell wrote:
>> On 2009-09-07 07:11 , Robert wrote:
>>> Is there a reason why ndarray truth tests (except scalars)
>>> deviates from the convention of other Python iterables
>>> list,array.array,str,dict,... ?
>>> Furthermore there is a surprising strange exception for arrays
>>> with size 1 (!= scalars).
>> Historically, numpy's predecessors used "not equal to zero" as the
>> meaning for truth (consistent with numerical types in Python). However,
>> this introduces an ambiguity as both any(a != 0) and all(a != 0) are
>> reasonable interpretations of the truth value of a sequence of numbers.
> well, I can familiarize with that "not equal to zero" philosophy
> for a math-centric array type (different from a container / size>0
> However I don't see that all(a) (or "all(a != 0)") is something
> which anybody would ever expect with .__nonzero__() / if a: ... .
> Does anybody? And the current behavior with all those strange
> exceptions and exceptions from exceptions still seems awkward and
> The any() interpretion is outstandingly "right" in my opinion, and
> doesn't need to be guessed: anything/any part non-zero disturbs
> the clean "zeroness". Zero must be wholly pure zero. This is so
> everywhere in math and informatics. a number/memory is zero when
> all bits/bytes are zero. a matrix is a zero matrix when all
> elements are zero... This way only the test is also seamlessly
> consistent with a zero length array (while all(zerolengtharray !=
> 0) would be True surprisingly!)
> This kind of any(a) truth test (only) is also often needed, and it
> would be also fast executable this way. It would be compatible
> with None/False init/default variable tests during code evolution
> in Python style and would behave well everywhere as far as I can
> see. It would also not break old code.
> Would a feature request in that direction have any chance?
No. Numeric used to use the any() interpretation, and it led to many,
many errors in people's code that went undetected for years. For
example, people seem to usually want "a == b" to be True iff *all*
elements are equal. People also seem to usually want "a != b" to be
True if *any* elements are unequal. These desires are inconsistent and
cannot be realized at the same time, yet people seem to hold both
mental models in their head without thoroughly thinking through the
logic or testing it. No amount of documentation or education seemed to
help, so we decided to raise an exception instead.
"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