NumPy sqrt()

The sqrt() function computes the square root of each element in an array.

import numpy as np

array1 = np.array([4, 9, 16, 25])

# compute square root of each element in array1 result = np.sqrt(array1)
print(result) # Output: [2. 3. 4. 5.]

sqrt() Syntax

The syntax of sqrt() is:

numpy.sqrt(array, out=None, where=True)

sqrt() Arguments

The sqrt() function takes following arguments:

  • array - the input array for which the square root is computed
  • out (optional) - the output array where the result will be stored
  • where (optional) - condition specifying which elements should be updated

sqrt() Return Value

The sqrt() function returns an array that contains the square root of each element in the input array.


Example 1: Find Square Root of Array Elements

import numpy as np

array1 = np.array([36, 49, 100, 256])

# compute square root of each element in array1 result = np.sqrt(array1)
print(result)

Output

[ 6.  7. 10. 16.]

In the above example, we have used the sqrt() function to compute the square root of each element in array1.

In our case, the square root of 36 is 6, the square root of 49 is 7, the square root of 100 is 10, and the square root of 256 is 16. So the resulting array is [ 6. 7. 10. 16.].

Note: Even though the resulting values are floating-point numbers, they are the exact square roots of the corresponding integers in the input array


Example 2: Use out to Store Result in a Desired Array

import numpy as np

# create a 2-D array
array1 = np.array([[4, 9, 16],
                                [25, 36, 49]])

# create an empty array with the same shape as array1
result = np.zeros_like(array1, dtype=float)

# calculate the square root of each element in array1 and store the result in result np.sqrt(array1, out=result)
print(result)

Output

[[2. 3. 4.]
 [5. 6. 7.]]

Here, sqrt() is used with the out argument set to result. This ensures that the result of calculating the square root is stored in result.


Example 3: Use where to Compute Square Root of Filtered Array

import numpy as np

array1 = np.array([4, 9, 16, 25])

# compute the square root of each element in array1 # where the element is odd (arr%2==1) result = np.sqrt(array1, where=(array1 % 2 == 1))
print(result)

Output

[0. 3. 0. 5.]