Python math.degrees() 方法



Python 的 math.degrees() 方法用於將弧度轉換為角度。通常,角度用三種單位來測量:轉數、弧度和角度。然而,在三角學中,測量角度的常用方法是用弧度或角度。因此,能夠將這些度量單位從一個轉換為另一個變得很重要。

degrees() 方法接收一個弧度值作為引數,並將其轉換為相應角度。

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

語法

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

math.degrees(x)

引數

  • x - 必須是數值。

返回值

此方法返回角度的度數值。

示例

以下示例顯示了 Python math.degrees() 方法的用法。在這裡,我們將以弧度為單位的角度“pi”作為引數傳遞給此方法。預期將其轉換為相應的角度。

import math

# Take the angle in radians
x = 3.14
y = -3.14

# Convert it into degrees using math.degrees() function
deg_x = math.degrees(x)
deg_y = math.degrees(y)

# Display the degrees
print("The degrees value of x is:", deg_x)
print("The degrees value of y is:", deg_y)

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

The degrees value of x is: 179.9087476710785
The degrees value of y is: -179.9087476710785

示例

但是,如果我們將無效數字(或 NaN)作為引數傳遞給該方法,則返回值也將無效(或 NaN)。

import math

# Take the nan value in float
x = float("nan")

# Convert it into degrees using math.degrees() function
deg = math.degrees(x)

# Display the degrees
print("The degrees value of x is:", deg)

如果我們編譯並執行給定的程式,則輸出將顯示如下:

The degrees value of x is: nan

示例

此方法僅接受浮點值作為其引數。如果將類似於數字序列的物件作為其引數傳遞,則該方法會引發 TypeError。

在以下示例中,我們建立一個包含一系列弧度角的列表物件。然後我們將此列表作為引數傳遞給此方法。即使列表包含以弧度為單位的角度,該方法也會返回 TypeError。

import math

# Take the angle list in radians
x = [1, 2, 3, 4, 5]

# Convert it into degrees using math.degrees() function
deg = math.degrees(x)

# Display the degrees
print("The degrees value of the list is:", deg)

Traceback (most recent call last):
  File "main.py", line 7, in 
deg = math.degrees(x)
TypeError: must be real number, not list

示例

為了使用此方法將序列中的物件轉換為度數,我們必須每次呼叫此方法時都將序列中的每個值作為引數傳遞。因此,我們可以使用迴圈語句來迭代所述可迭代物件。

import math

# Take the angle list in radians
x = [1, 2, 3, 4, 5]

for n in range (0, len(x)):
   # Convert it into degrees using math.degrees() function
   deg = math.degrees(x[n])
   # Display the degrees
   print("The degree value of", x[n], "is:", deg)

編譯並執行上述程式,以產生以下結果:

The degree value of 1 is: 57.29577951308232
The degree value of 2 is: 114.59155902616465
The degree value of 3 is: 171.88733853924697
The degree value of 4 is: 229.1831180523293
The degree value of 5 is: 286.4788975654116
python_maths.htm
廣告