Python math.atan2() 方法



Python 的 math.atan2() 方法返回 atan(y / x) 的值(以弧度表示)。換句話說,此方法將笛卡爾座標對 (x, y) 轉換為極座標對 (r, θ) 並返回 θ 值。

此方法僅接受浮點值作為引數;如果傳遞給此方法的值不是浮點值,則會引發 TypeError。

注意 - 此函式無法直接訪問,因此我們需要匯入 math 模組,然後才能使用 math 靜態物件呼叫此函式。

語法

以下是 Python math.atan2() 方法的語法:

math.atan2(y, x)

引數

  • x, y - 必須是浮點型別的數值。

返回值

此方法返回 atan(y / x) 的值(以弧度表示)。

示例

以下示例演示了 Python math.atan2() 方法的使用。在這裡,我們建立了兩個包含兩個浮點值的 物件,並將它們作為引數傳遞給此方法。獲得的返回值必須以弧度表示。

import math

# Create two objects of floating-point numbers
x = 0.6
y = 1.2

# Calculate the atan(y/x) value
theta = math.atan2(y, x)

# Print the theta value
print("The theta value is calculated as:", theta)

執行上述程式時,會產生以下結果:

The theta value is calculated as: 1.1071487177940904

示例

如果我們將負值作為引數傳遞給此方法,則將返回這些矩形座標所包圍的角度。

import math

# Create two objects of floating-point numbers
x = -1.6
y = -3.5

# Calculate the atan(y/x) value
theta = math.atan2(y, x)

# Print the theta value
print("The theta value is calculated as:", theta)

如果我們編譯並執行

The theta value is calculated as: -1.999574354240913

示例

在下面的示例中,我們建立了兩個列表物件 x、y。使用迴圈語句,我們試圖從列表中找到對應 x 和 y 值的 θ 值。

import math

# Create two lists of floating-point numbers
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]

# Calculate the atan(y/x) value of all objects in the list
for n in range(0, len(x)):
   theta = math.atan2(y[n], x[n])
   print("The theta value of", y[n], "and", x[n], "is calculated as:", theta)

編譯並執行上面的程式後,輸出顯示為:

The theta value of 5 and 1 is calculated as: 1.373400766945016
The theta value of 6 and 2 is calculated as: 1.2490457723982544
The theta value of 7 and 3 is calculated as: 1.1659045405098132
The theta value of 8 and 4 is calculated as: 1.1071487177940904

示例

如果直接將上面的列表作為引數傳遞給該方法,則會引發 TypeError。因此,我們使用迴圈語句訪問其中的浮點物件。

import math

# Create two lists of floating-point numbers
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]

# Calculate the atan(y/x) value of all objects in the list
theta = math.atan2(y, x)
print("The theta value is calculated as:", theta)

如果我們編譯並執行給定的程式,則會引發如下 TypeError:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
theta = math.atan2(y, x)
TypeError: must be real number, not list
python_maths.htm
廣告