Python 將弧度轉換為度數及相反操作
Manav Narula
2023年1月30日
Python
Python Math
度和弧度是表示角度的兩個常用單位。這兩個單位之間的表示如下所示。

在本教程中,我們將討論如何將度數轉換為弧度,反之亦然。
使用 Python 中的 math 模組將度數轉換為弧度和相反操作
在 Python 中手動實現它們的關係很簡單。如果我們不熟悉常量,可以使用 math 庫獲取所需的常量。例如,
print((math.pi / 2) * 180.0 / math.pi) # Rad to Deg
print(90 * math.pi / 180.0) # Deg to Rad
輸出:
90.0
1.5707963267948966
請注意,math.pi 返回數學常數 pi,並且可以用其值 3.141592…代替。
我們還可以使用 math 庫中的其他函式來進行這些轉換。
math.degrees() 函式會將傳遞給它的弧度值轉換為度。例如,
import math
print(math.degrees(math.pi / 2))
輸出:
90.0
math.radians() 函式將執行相反的操作,並將度值轉換為弧度。例如,
import math
print(math.radians(90))
輸出:
1.5707963267948966
使用 NumPy 模組將度數轉換為弧度和反向操作
NumPy 模組還配備了不同的函式,可在弧度和度值之間進行轉換。numpy.degrees() 函式將弧度轉換為度,並且可以一次接受陣列或值列表。
類似地,numpy.radians() 函式將度轉換為弧度,並且還可以接受陣列或值列表。
以下程式碼顯示了這兩個功能的示例。
import numpy
lst1 = [math.pi / 2, math.pi]
print(numpy.degrees(lst1)) # Rad to Deg
lst2 = [90, 180]
print(numpy.radians(lst2)) # Deg to Rad
輸出:
[ 90. 180.]
[1.57079633 3.14159265]
該模組還具有用於執行相同功能的 deg2rad() 和 rad2deg() 函式,但其名稱更具描述性。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Manav Narula
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn