[Numpy-discussion] Scalar array - a trap for the unwary

Colin J. Williams cjw at sympatico.ca
Sun Jan 22 14:25:01 CST 2006

```Travis Oliphant wrote:

> Colin J. Williams wrote:
>
>> In the script below, b is presented as an integer, either with str or
>> repr, but it is an array and needs further processing to treat it as
>> in integer.
>
>
> I think there is a misunderstanding here---or, at least you need to
> clarify what your concern is.

Travis,
You are right, it was an incomplete understanding on my part.  Sasha
helped to explain things.

> In the code you provided, b is not an array.  It is a scalar that has
> the attributes of an array (but it is also subclassed from a Python
> integer and acts like one everywhere).

Yes, it is dressed like an array but behaves as an integer.

>>
>> I much prefer the numarray treatment, particularly in a matrix context.
>
>
> What do you mean by "in a matrix context?"

numarray returns a simple scalar, without the ArrayType dressing.  numpy
would appear to be operationally equivalent and thus adequate.

In exploring these matters, it seems that numpy does not broadcast
scalar operations on arrays, as numarray does.  Is this intended?
Please see the script below and the result under that.

# tArray.py

from numpy.core import multiarray as _mu

import numarray.numarraycore as _na
naa= _na.array([1, 2])
print type(naa[1]),
print naa * 3
mua= _mu.array([3, 4])
print type(mua[1]),
print mua * 3            # Grief here

*** Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit
(Intel)] on win32. ***
>>>
<type 'int'> [3 6]
<type 'int32_arrtype'>
Traceback (most recent call last):
File "<string>", line 63, in run_nodebug
File "C:\Python24\Lib\site-packages\PyMatrix\Misc\Test\tArray.py",
line 11, in ?
print mua * 3            # Grief here
TypeError: unsupported operand type(s) for *: 'numpy.ndarray' and 'int'

```