返回 NumPy 中复数类型的元素级符号指示


要返回复数类型的元素级符号指示,请在 Python NumPy 中使用 **numpy.sign()** 方法。

sign 函数如果 x < 0 则返回 -1,如果 x==0 则返回 0,如果 x > 0 则返回 1。对于 nan 输入,返回 nan。对于复数输入,如果 x.real != 0,则 sign 函数返回 sign(x.real) + 0j,否则返回 sign(x.imag) + 0j。

对于复数 nan 输入,返回 complex(nan, 0)。在常用中,复数的符号有多种定义。这里使用的定义等效于 x/x*x,这与常见的替代方法 x/|x| 不同。

步骤

首先,导入所需的库:

import numpy as np

使用 array() 方法创建一个包含复数类型的数组:

arr = np.array([56.+0.j, 27.+0.j, 68.-2.j, 49.+0.j, 120.-5.j,3 + 4.j])

显示数组:

print("Array...
", arr)

获取数组的类型:

print("
Our Array type...
", arr.dtype)

获取数组的维度:

print("
Our Array Dimension...
",arr.ndim)

获取数组的形状:

print("
Our Array Shape...
",arr.shape)

要返回复数类型的元素级符号指示,请使用 numpy.sign() 方法:

print("
Result...
",np.sign(arr))

示例

import numpy as np

# Create an array with complex type using the array() method
arr = np.array([56.+0.j, 27.+0.j, 68.-2.j, 49.+0.j, 120.-5.j,3 + 4.j])

# Display the array
print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimension...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # To return an element-wise indication of the sign of complex types, use the numpy.sign() method in Python Numpy print("
Result...
",np.sign(arr))

输出

Array...
[ 56.+0.j 27.+0.j 68.-2.j 49.+0.j 120.-5.j 3.+4.j]

Our Array type...
complex128

Our Array Dimension...
1

Our Array Shape...
(6,)

Result...
[1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j]

更新于:2022年2月8日

138 次查看

启动您的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.