Compute the square root of negative input with emath in Python
Last Updated :
01 May, 2022
In this article, we will cover how to compute the square root of negative inputs with emath in Python using NumPy.
Example:
Input: [-3,-4]
Output: [0.+1.73205081j 0.+2.j ]
Explanation: Square root of a negative input.
NumPy.emath.sqrt method:
The np.emath.sqrt() method from the NumPy library calculates the square root of complex inputs. A complex value is returned for negative input elements unlike numpy.sqrt. which returns NaN.
Syntax: np.emath.sqrt()
Parameters:
Return: out: scalar or ndarray.
Example 1:
If the array contains negative input values, complex numbers are returned in the output, and the shape, datatype, and dimensions of the array can be found by .shape, .dtype, and .ndim attributes.
Python3
import numpy as np
arr = np.array([ - 3 , - 4 ])
print (array)
print ( "Shape of the array is : " ,arr.shape)
print ( "The dimension of the array is : " ,arr.ndim)
print ( "Datatype of our Array is : " ,arr.dtype)
print (np.emath.sqrt(arr))
|
Output:
[-3 -4]
Shape of the array is : (2,)
The dimension of the array is : 1
Datatype of our Array is : int64
[0.+1.73205081j 0.+2.j ]
Example 2:
Python3
import numpy as np
array = np.arr([ complex ( - 2 , - 1 ), complex ( - 5 , - 3 )])
print (array)
print ( "Shape of the array is : " ,arr.shape)
print ( "The dimension of the array is : " ,arr.ndim)
print ( "Datatype of our Array is : " ,arr.dtype)
print (np.emath.sqrt(arr))
|
Output:
[-2.-1.j -5.-3.j]
Shape of the array is : (2,)
The dimension of the array is : 1
Datatype of our Array is : complex128
[0.34356075-1.45534669j 0.64457424-2.32711752j]
Please Login to comment...