If you have a keen eye, you have noticed that some of the previous examples did something new: they added a number to an array. Indeed, most Python operations applicable to numbers are directly applicable to arrays:
>>> print a [1 2 3] >>> print a * 3 [3 6 9] >>> print a + 3 [4 5 6]
>>> print sin(a) [ 0.84147096 0.90929741 0.14112 ] >>> print -a [-1 -2 -3]
>>> print a + a [2 4 6]
>>> print a [1 2 3] >>> b = array([4,5,6,7]) # note this has four elements >>> print a + b Traceback (innermost last): File "<stdin>", line 1, in ? ValueError: Arrays have incompatible shapes
(3,)
shaped array and a (4,)
shaped array.
Note what happens when adding arrays with different rank:
>>> print a [1 2 3] >>> print b [[ 4 8 12] [ 5 9 13] [ 6 10 14] [ 7 11 15]] >>> print a + b [[ 5 10 15] [ 6 11 16] [ 7 12 17] [ 8 13 18]]
>>> a.getshape() (3,) >>> b.getshape() (4,3)
a
is the same length as that of b
(i.e. compare the last elements in their shape tuples). Because a
's
and b
's last dimensions both have length 3, those two dimensions were
``matched'', and a new dimension was created and automatically ``assumed'' for
array a. The data already in a were ``replicated'' as many times as needed (4,
in this case) to make the shapes of the two operand arrays conform. This
replication ( broadcasting) occurs when arrays are operands
to binary operations and their shapes differ, based on the following algorithm:
Beginning with Python 2.0, Python supports the in-place operators
+=
, -=
, *=
, and
/=
. Numarray supports these operations, but you need to be
careful. The right-hand side should be of the same type. Some violation of this
is possible, but in general contortions may be necessary for using the smaller
``kinds'' of types.
>>> x = array ([1, 2, 3], type=Int16) >>> x += 3.5 >>> print x [4 5 6]
Send comments to the NumArray community.