NumPy Square: Understanding np.square()

Ben Cook • Posted 2021-01-01 • Last updated 2021-10-15

The np.square() function returns the element-wise square of its input:

import numpy as np

x = np.array([1, 2, 3])
np.square(x)

# Expected result
# array([1, 4, 9])

The function accepts any array-like input. If the input is a scalar, it will return a scalar. If the input is an array, it will return an array. It will also convert Python sequences to np.ndarray if necessary.

But note: although similar in most cases, this operatoin is not exactly the same as x ** 2. When x is a np.ndarray, then np.square() is indeed equivalent to x ** 2, but when x is a np.matrix, then x ** 2 will actually be the matrix multiplied by itself with matrix multiplication:

x_matrix = np.matrix(np.stack([x] * 3))
x_matrix

# Expected result
# matrix([[1, 2, 3],
#         [1, 2, 3],
#         [1, 2, 3]])

np.square(x_matrix)

# Expected result
# matrix([[1, 4, 9],
#         [1, 4, 9],
#         [1, 4, 9]])

x_matrix ** 2

# Expected result
# matrix([[ 6, 12, 18],
#         [ 6, 12, 18],
#         [ 6, 12, 18]])

A couple other notes about np.square()

  • Data type will be left alone by the operation. If you input integer types you’ll get integer types out.
  • It works on complex NumPy types.