Python 如果输入是复数且所有虚部接近于零,则返回实部

Python 如果输入是复数且所有虚部接近于零,则返回实部

要返回实部,如果输入是复数且所有虚部接近于零,请使用Python中的numpy.real_if_close函数。 “接近于零” 定义为 tol * 类型 a 的机器epsilon。如果 a 是实数,则输出使用 a 的类型。如果 a 具有复数元素,则返回的类型是float。第一个参数是 输入数组 a,第二个参数是元素数组中复数部分的容差。

步骤

首先,导入所需的库 –

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的机器epsilon类型)。

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]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程