[Numpy-discussion] Numeric/numarray compatibility issue
Perry Greenfield
perry at stsci.edu
Fri Mar 4 07:49:14 EST 2005
On Mar 3, 2005, at 12:31 PM, konrad.hinsen at laposte.net wrote:
> Following a bug report concerning ScientificPython with numarray, I
> noticed an incompatibility between Numeric and numarray, and I am
> wondering if this is intentional.
>
> In Numeric, the result of a comparison operation is an integer array.
> In numarray, it is a Bool array. Bool arrays seem to behave like Int8
> arrays when arithmetic operations are applied. The net result is that
>
> print n.add.reduce(n.greater(n.arange(128), -1))
>
> yields -128, which is not what I would expect.
>
> I can see two logically coherent points of views:
>
> 1) The Numeric view: comparisons yield integer arrays, which may be
> used freely in arithmetic.
>
> 2) The "logician's" view: comparisons yield arrays of boolean values,
> on which no arithmetic is allowed at all, only logical operations.
>
> The first approach is a lot more pragmatic, because there are a lot of
> useful idioms that use the result of comparisons in arithmetic,
> whereas an array of boolean values cannot be used for much else than
> logical operations.
>
> And now for my pragmatic question: can anyone come up with a solution
> that will work under both Numeric an numarray, won't introduce a speed
> penalty under Numeric, and won't leave the impression that the
> programmer had had too many beers? There is the quick hack
>
> print n.add.reduce(1*n.greater(n.arange(128), -1))
>
> but it doesn't satisfy the last two criteria.
First of all, isn't the current behavior a little similar to Python in
that Python Booleans aren't pure either (for backward compatibility
purposes)?
I think this has come up in the past, and I thought that one possible
solution was to automatically coerce all integer reductions and
accumulations to Int32 to avoid overflow issues. That had been
discussed before and apparently many preferred avoiding automatic
promotion (the reductions allow specifying a new type for the
reduction, but I don't believe that helps your specific example for
code that works for both). Using .astype(Int32) should work for both,
right? (or is that too much of a speed hit?) But it is a fair question
to ask if arithmetic operations should be allowed on booleans without
explicit casts.
Perry
More information about the NumPy-Discussion
mailing list