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:
- x: array like object.
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 # Creating an array arr = np.array([ - 3 , - 4 ]) print (array) # shape of the array is print ( "Shape of the array is : " ,arr.shape) # dimension of the array print ( "The dimension of the array is : " ,arr.ndim) # Datatype of the array print ( "Datatype of our Array is : " ,arr.dtype) # computing the square root of negative inputs 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 # Creating an array array = np.arr([ complex ( - 2 , - 1 ), complex ( - 5 , - 3 )]) print (array) # shape of the array is print ( "Shape of the array is : " ,arr.shape) # dimension of the array print ( "The dimension of the array is : " ,arr.ndim) # Datatype of the array print ( "Datatype of our Array is : " ,arr.dtype) # computing the square root of complex inputs 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]