在Python中计算x1/x2的逐元素反正切,并正确选择象限


选择象限的方法是,arctan2(x1, x2) 是以原点为起点,经过点(1,0)的射线与以原点为起点,经过点(x2, x1)的射线之间所成的有符号弧度角。

第一个参数是y坐标,第二个参数是x坐标。如果x1.shape != x2.shape,则它们必须可广播到一个共同的形状。该方法返回一个弧度角数组,范围在[-pi, pi]。如果x1和x2都是标量,则返回标量。

步骤

首先,导入所需的库:

import numpy as np

使用array()方法创建数组。这些是不同象限的四个点:

x = np.array([-1, +1, +1, -1])
y = np.array([-1, -1, +1, +1])

显示array1:

print("Array1 (x coordinates)...\n", x)

显示array2:

print("\nArray2 (y coordinates)...\n", y)

为了计算x1/x2的逐元素反正切并正确选择象限,请在Python中使用numpy的arctan2()方法:

print("\nResult...",np.arctan2(y, x) * 180 / np.pi)

示例

import numpy as np

# The quadrant is chosen so that arctan2(x1, x2) is the signed angle in radians between the ray
# ending at the origin and passing through the point (1,0), and the ray ending at the origin and
# passing through the point (x2, x1).

# Creating arrays using the array() method
# These are four points in different quadrants
x = np.array([-1, +1, +1, -1])
y = np.array([-1, -1, +1, +1])

# Display the array1
print("Array1 (x coordinates)...\n", x)

# Display the array2
print("\nArray2 (y coordinates)...\n", y)

# To compute element-wise arc tangent of x1/x2 choosing the quadrant correctly, use the numpy, arctan2() method in Python
print("\nResult...",np.arctan2(y, x) * 180 / np.pi)

输出

Array1 (x coordinates)...
[-1 1 1 -1]

Array2 (y coordinates)...
[-1 -1 1 1]

Result... [-135. -45. 45. 135.]

更新于:2022年2月25日

141次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告