Numpy sqrt() – Find Square Root of Numbers

Numpy sqrt()

To find the square root of a list of numbers, you can use numpy.sqrt() function.

sqrt() functions accepts a numpy array (or list), computes the square root of items in the list and returns a numpy array with the result.

Syntax

The syntax of sqrt() function is:

output = numpy.sqrt(array_like)

Provide an array like argument to sqrt() and it returns an ndarray.

Examples

1. Find square root of numbers in a list

In this example, we shall initialize a list of numbers and find the square root of these numbers.

Python Program

import numpy as np

# Initialize a list
listA = [4, 16, 9, 1, 25, 49]

# Find square root of items in the list
output = np.sqrt(listA)

print(output)
Run Code Copy

Output

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

We have provided perfect squares in the list, hence we got their square roots without any decimal value.

2. Square root of non-perfect square numbers

In this program, we shall provide numbers that are not perfect squares and find their square root.

Python Program

import numpy as np

# Initialize a list
listA = [2, 3, 5]

# Find square root of items in the list
output = np.sqrt(listA)

print(output)
Run Code Copy

Output

[1.41421356 1.73205081 2.23606798]

3. Square root of complex numbers

You can also provide complex numbers as elements of list to compute their square roots.

Python Program

import numpy as np

# Initialize a list
listA = [4+1j, 9+16j]

# Find square root of items in the list
output = np.sqrt(listA)

print(output)
Run Code Copy

Output

[2.01532946+0.24809839j 3.69848346+2.16304875j]

4. Square root of negative numbers

In this example, we shall provide some negative numbers. sqrt() throws a RuntimeWarning. Just a warning. And returns nan (not a number) for the negative element in the list.

Python Program

import numpy as np

# Initialize a list
listA = [-4, 9]

# Find square root of items in the list
output = np.sqrt(listA)

print(output)
Run Code Copy

Output

[nan  3.]

Summary

In this NumPy Tutorial, we learned how to calculate square root of numbers using numpy.sqrt() function, with detailed example programs.

Code copied to clipboard successfully 👍