在 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