Python Numpy.sqrt() - Square Root

Jinku Hu Jan 30, 2023
  1. Syntax of numpy.sqrt()
  2. Example Codes: numpy.sqrt()
  3. Example Codes: numpy.sqrt() With out Parameter
  4. Example Codes: numpy.sqrt() With Negative Numbers
  5. Example Codes: numpy.sqrt() With Complex Numbers
Python Numpy.sqrt() - Square Root

Numpy.sqrt() function calculates the square root of every element in the given array.

It is the inverse operation of Numpy.square() method.

Syntax of numpy.sqrt()

numpy.sqrt(arr, out=None)

Parameters

arr input array
out If out is given, the result will be stored in out. out should have the same shape as arr.

Return

It returns an array of the square root of each element in the input array, even if out is given.

Example Codes: numpy.sqrt()

import numpy as np

arr = [1, 9, 25, 49]

arr_sqrt = np.sqrt(arr)

print(arr_sqrt)

Output:

[1. 3. 5. 7.]

Example Codes: numpy.sqrt() With out Parameter

import numpy as np

arr = [1, 9, 25, 49]
out_arr = np.zeros(4)

arr_sqrt = np.sqrt(arr, out_arr)

print(out_arr)
print(arr_sqrt)

Output:

[1. 3. 5. 7.]
[1. 3. 5. 7.]

out_arr has the same shape as arr, and the square root of arr is saved in it. And the numpy.sqrt() method also returns the square root array, as shown above.

If out doesn’t have the same shape as arr, it raises a ValueError.

import numpy as np

arr = [1, 9, 25, 49]
out_arr = np.zeros((2, 2))

arr_sqrt = np.sqrt(arr, out_arr)

print(out_arr)
print(arr_sqrt)

Output:

Traceback (most recent call last):
  File "C:\Test\test.py", line 6, in <module>
    arr_sqrt = np.sqrt(arr, out_arr)
ValueError: operands could not be broadcast together with shapes (4,) (2,2) 

Example Codes: numpy.sqrt() With Negative Numbers

import numpy as np

arr = [-1, -9, -25, -49]

arr_sqrt = np.sqrt(arr)

print(arr_sqrt)

Output:

Warning (from warnings module):
  File "..\test.py", line 5
    arr_sqrt = np.sqrt(arr)
RuntimeWarning: invalid value encountered in sqrt
[nan nan nan nan]

It throws a RuntimeWarning when the input is a negative number and returns nan as a result.

Example Codes: numpy.sqrt() With Complex Numbers

import numpy as np

arr = [3 + 4j, -5 + 12j, 8 - 6j, -15 - 8j]

arr_sqrt = np.sqrt(arr)

print(arr_sqrt)

Output:

[2.+1.j 2.+3.j 3.-1.j 1.-4.j]

A complex number has two square roots. For example,

numpy sqrt example

numpy.sqrt() method returns only one square root, which has a positive real number.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook