[Numpy-discussion] rank-0 arrays
eric jones
eric at enthought.com
Sun Sep 15 11:51:01 CDT 2002
Hey Konrad,
>
> "eric jones" <eric at enthought.com> writes:
>
> > Reductions and indexing return different types based on the number
of
> > dimensions of the input array:
> >
> > >>> b = sum(a)
> > >>> l = len(b) # or whatever
> >
> > This code works happily if "a" is 2 or more dimensions, but will
fail if
> > it is 1d because the sum(a) will return a scalar in this case. To
write
>
> And it should fail, because a rank-0 array is not a sequence, so it
> doesn't have a length.
>
I disagree. You should not have to write special code to check for a
specific case. It breaks one of the beauties of Numeric -- i.e. you can
write generic code that handles arrays of any size and type. Any method
that works on a 1 or more d array should also work on 0d arrays. If you
ask for its shape, it returns a tuple. If you ask for its size it
returns its length along its "first" axis. This will always be 1. It
allows for generic code.
On this note:
I do not see the benefit of making a scalar type object that is separate
for 0d arrays. It seems to remove instead of enhance capabilities.
What does a scalar object buy that simply using 0d arrays for that
purpose does not?
>
> But there are valid examples in which it would be nice if scalars
> were arrays (but probably if *all* scalars supported array
operations,
> not just those that were generated by indexing from arrays):
>
> - a.shape should return () for a scalar (and (len(a),) for any
> sequence type)
>
> - a.astype(N.Float) should also work for scalars
>
> Similarly, it would be nice if complex operations (real/imaginary
> part) would work on integers and floats.
Yes, this is needed. And I think the argument for it is similar as
having len() work on 0d arrays. It allows for generic code.
>
> There's one more annoying difference between scalars and arrays of
> any rank which I think should be removed in numarray:
>
> >>> 3 % -2
> -1
> >>> array(3) % 2
> 1
> >>> fmod(3, -2)
> 1.0
>
> I.e. the mod operation uses fmod() for arrays, but different rules
> for standard Python numbers.
I think you meant,
> >>> array(3) % -2
> 1
That is unfortunate. It would be nice to clean this up.
eric
More information about the Numpy-discussion
mailing list