在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次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告