在Python中用emath计算负输入的平方根
在这篇文章中,我们将介绍如何在Python中使用NumPy用emath计算负输入的平方根。
示例:
Input: [-3,-4]
Output: [0.+1.73205081j 0.+2.j ]
Explanation: Square root of a negative input.
NumPy.emath.sqrt 方法:
NumPy库中的np.emath.sqrt()方法可以计算复数输入的平方根。与numpy.sqrt.返回NaN不同,负的输入元素会返回一个复数值。
语法: np.emath.sqrt()
参数:
- x:类似对象的数组。
返回:out:标量或ndarray。
示例 1:
如果数组包含负的输入值,输出中会返回复数,数组的形状、数据类型和尺寸可以通过.shape、.dtype和.ndim属性找到。
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))
输出:
[-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 ]
示例 2:
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))
输出:
[-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]