返回 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.