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])
Run

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

Example 1: Find Squre Root of Number 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

Output

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

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

Example 2: Square root of 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

Output

[1.41421356 1.73205081 2.23606798]
Run

Example 3: Find 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

Output

[2.01532946+0.24809839j 3.69848346+2.16304875j]
Run

Example 4: Square 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

Output

[nan  3.]
Run

Summary

In this tutorial of Python Examples, we learned how to calculate square root of numbers using numpy.sqrt() function, with the help of well detailed example programs.