Arithmetics

5.3. Arithmetics#

All Python arithmetic operators (+, -, *, /, **) work directly on NumPy arrays, assuming both arrays have the same shape. Operations are performed between each element of a same position. For example, using a + b, the 1st element of a is summed with the 1st element of b, the 2nd of a with the 2nd of b, etc.:

import numpy as np

a = np.array(
    [
        [1.0, 2.0, 3.0],
        [1.0, 2.0, 3.0],
    ]
)

b = np.array(
    [
        [1.0, 1.0, 1.0],
        [2.0, 2.0, 2.0],
    ]
)

Addition:

a + b
array([[2., 3., 4.],
       [3., 4., 5.]])

Subtraction:

a - b
array([[ 0.,  1.,  2.],
       [-1.,  0.,  1.]])

Multiplication:

a * b
array([[1., 2., 3.],
       [2., 4., 6.]])

Division:

a / b
array([[1. , 2. , 3. ],
       [0.5, 1. , 1.5]])

Exponent:

a**b
array([[1., 2., 3.],
       [1., 4., 9.]])

It is also possible to perform operations between an array and a single number.

Addition:

a + 1
array([[2., 3., 4.],
       [2., 3., 4.]])

Subtraction:

a - 1
array([[0., 1., 2.],
       [0., 1., 2.]])

etc.