numpy

How to Calculate Square Root in NumPy (np.sqrt for 1D and Multi-Dimensional Arrays)

NumPy’s np.sqrt() function makes it easy to calculate square root in NumPy for entire arrays, applying the square root operation element-wise to 1D or multi-dimensional arrays. Let’s see how to calculate square root in Numpy Python module.

numpy square root

Single and Multi-Dimensional Arrays

Whether you need to calculate square root in NumPy for a simple scalar, 1D array, or complex multi-dimensional arrays, np.sqrt() handles element-wise computation efficiently.

See also  How to Calculate Mode in Python (statistics.mode, NumPy bincount/argmax, and Examples)

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.

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.