How to calculate square root in Numpy?

NumPy provides a convenient way to perform an array-wise square root calculation through its sqrt function. Let’s see how to calculate square root in Numpy Python module.

numpy square root

Single and Multi-Dimensional Arrays

Using np.sqrt() in NumPy is a straightforward way to calculate square roots, whether it’s for an array or a single number.

Import Numpy, use sqrt numpy function and calculate square root for your array just like in the numpy code below.

import numpy as np

my_array = np.array([2, 3, 4, 9, 16])

square_root = np.sqrt(my_array)
print("Square root equals: " + str(square_root))

numpy square root

Square root has been calculated and printed out.

See also  Swap Numpy row vector to column vector

Multi-Dimensional Arrays

NumPy’s sqrt function can be applied to multi-dimensional arrays, calculating the square root of each element:

multi_dimensional_array = np.array([[4, 16], [25, 36]])
md_array_sqrt = np.sqrt(multi_dimensional_array)
print("Multi-dimensional square root: \n" + str(md_array_sqrt))

The square root of each element in the multi-dimensional array is calculated and displayed.