Next / Previous / Contents / Shipman's homepage

6. Universal functions (ufuncs)

The usual mathematical operators (+ - * /) generalize to NumPy arrays, as well as a number of ufuncs (universal functions) defined by NumPy.

For example, to add two vectors v1 and v2 of the same length, the “+” operator gives you an element-by-element sum.

>>> v1 = np.arange(0.6, 1.6, 0.1)
>>> print v1
[ 0.6  0.7  0.8  0.9  1.   1.1  1.2  1.3  1.4  1.5]
>>> v2 = np.arange(40.0, 50.0, 1.0)
>>> print v2
[ 40.  41.  42.  43.  44.  45.  46.  47.  48.  49.]
>>> print v1+v2
[ 40.6  41.7  42.8  43.9  45.   46.1  47.2  48.3  49.4  50.5]

The other common operators generalize in the same way.

>>> print v1*v2
[ 24.   28.7  33.6  38.7  44.   49.5  55.2  61.1  67.2  73.5]
>>> print v1-v2
[-39.4 -40.3 -41.2 -42.1 -43.  -43.9 -44.8 -45.7 -46.6 -47.5]
>>> print v1**2
[ 0.36  0.49  0.64  0.81  1.    1.21  1.44  1.69  1.96  2.25]

You can also use the “+” operator to add a constant value to every element of an array. This is called broadcasting.

>>> print v1
[ 0.6  0.7  0.8  0.9  1.   1.1  1.2  1.3  1.4  1.5]
>>> print v1 + 0.4
[ 1.   1.1  1.2  1.3  1.4  1.5  1.6  1.7  1.8  1.9]

All the usual Python mathematical operators will broadcast across arrays.

>>> print v1 * 10
[  6.   7.   8.   9.  10.  11.  12.  13.  14.  15.]
>>> print v1*10+100
[ 106.  107.  108.  109.  110.  111.  112.  113.  114.  115.]

In addition, these NumPy functions can be used on arrays, either to operate element-by-element or to broadcast values.

np.abs(a) Absolute value.
np.arccos(a) Inverse cosine.
np.arcsin(a) Inverse sine.
np.arctan(a) Inverse tangent.
np.arctan2(y, x) Computes the arctangent of the slope whose Δy is y and whose Δx is x.
np.cos(a) Cosine.
np.exp(a) Exponential, ea.
np.log(a) Natural log.
np.log10(a) Common log (base 10).
np.sin(a) Sine.
np.sqrt(a) Square root.
np.tan(a) Tangent.

Examples:

>>> print np.abs(np.arange(-4, 5))
[4 3 2 1 0 1 2 3 4]
>>> angles = np.arange(0.0, np.pi*9.0/4.0, np.pi/4.0)
>>> print angles/np.pi
[ 0.    0.25  0.5   0.75  1.    1.25  1.5   1.75  2.  ]
>>> print np.sin(angles)
[  0.00000000e+00   7.07106781e-01   1.00000000e+00   7.07106781e-01
   1.22460635e-16  -7.07106781e-01  -1.00000000e+00  -7.07106781e-01
  -2.44921271e-16]
>>> print np.cos(angles)
[  1.00000000e+00   7.07106781e-01   6.12303177e-17  -7.07106781e-01
  -1.00000000e+00  -7.07106781e-01  -1.83690953e-16   7.07106781e-01
   1.00000000e+00]
>>> print np.tan(angles)
[  0.00000000e+00   1.00000000e+00   1.63317787e+16  -1.00000000e+00
  -1.22460635e-16   1.00000000e+00   5.44392624e+15  -1.00000000e+00
  -2.44921271e-16]
>>> deltaYs = np.array((0, 1, 0, -1))
>>> deltaXs = np.array((1, 0, -1, 0))
>>> quadrants = np.arctan2(deltaYs, deltaXs)
>>> print quadrants
[ 0.          1.57079633  3.14159265 -1.57079633]
>>> print quadrants/np.pi
[ 0.   0.5  1.  -0.5]