在 Python 中,如果輸入是複數且所有虛部都接近於零,則返回實部
在 Python 中,如果輸入是複數且所有虛部都接近於零,則可以使用 numpy.real_if_close 返回實部。“接近於零”定義為 tol *(a 的型別對應的機器ε)。如果 a 是實數,則輸出型別為 a 的型別。如果 a 包含複數元素,則返回型別為浮點數。第一個引數是 a,即輸入陣列。第二個引數是 tol,表示陣列中元素複數部分的容差(以機器ε為單位)。
步驟
首先,匯入所需的庫 -
import numpy as np
使用 array() 方法建立 NumPy 陣列 -
arr = np.array([2.1 + 4e-14j, 5.2 + 3e-15j])
顯示陣列 -
print("Our Array...\n",arr)檢查維度 -
print("\nDimensions of our Array...\n",arr.ndim)
獲取資料型別 -
print("\nDatatype of our Array object...\n",arr.dtype)獲取形狀 -
print("\nShape of our Array object...\n",arr.shape)
在 Python 中,如果輸入是複數且所有虛部都接近於零,則可以使用 numpy.real_if_close 返回實部。“接近於零”定義為 tol *(a 的型別對應的機器ε)。
print("\nResult...\n",np.real_if_close(arr, tol = 1000))示例
import numpy as np
# Creating a numpy array using the array() method
arr = np.array([2.1 + 4e-14j, 5.2 + 3e-15j])
# Display the array
print("Our Array...\n",arr)
# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)
# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)
# Get the Shape
print("\nShape of our Array object...\n",arr.shape)
# To return real parts if input is complex with all imaginary parts close to zero, use the numpy.real_if_close in Python
print("\nResult...\n",np.real_if_close(arr, tol = 1000))輸出
Our Array... [2.1+4.e-14j 5.2+3.e-15j] Dimensions of our Array... 1 Datatype of our Array object... complex128 Shape of our Array object... (2,) Result... [2.1 5.2]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP