Python math.degrees() 方法将角度从弧度转换为度数。通常,角度以 3 个单位测量:转数、弧度和度数。然而,在三角学中,测量角度的常用方法是弧度或度数。因此,能够将这些测量单位从一种转换为另一种测量单位变得非常重要。
degrees() 方法接受弧度值作为参数,并将其转换为相应的度数。
注意 − 这个函数不能直接访问,所以我们需要导入 math 模块,然后我们需要使用 math 静态对象调用这个函数。
语法
以下是 Python math.degrees() 方法的语法 -
math.degrees(x)
参数
- x − 这必须是一个数值。
返回值
此方法返回角度的 degree 值。
例以下示例显示了 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
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
File "main.py", line 7, in
deg = math.degrees(x)
TypeError: must be real number, not list
例
为了使用此方法将序列中的对象转换为度数,我们必须在每次调用此方法时将序列中的每个值作为参数传递。因此,我们可以使用 loop 语句来迭代所述的可迭代对象。
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
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