📜  Python中的 numpy.degrees() 和 rad2deg()(1)

📅  最后修改于: 2023-12-03 15:34:23.890000             🧑  作者: Mango

Python 中的 numpy.degrees() 和 rad2deg()

在数学和物理学中,经常需要对弧度和角度进行转换。

在 Python 中,可以使用 numpy 库中的 degrees() 函数和 rad2deg() 函数来进行弧度和角度的转换。

degrees() 函数

numpy.degrees(x) 函数将输入数组 x 中的元素从弧度转换为角度,输出数组中的值是度数。

import numpy as np

# 定义一个弧度数组
x = np.array([0, np.pi/2, np.pi])
print("弧度数组:", x)

# 使用 degrees() 转换为角度数组
y = np.degrees(x)
print("角度数组:", y)

输出结果:

弧度数组: [0.         1.57079633 3.14159265]
角度数组: [ 0. 90. 180.]
rad2deg() 函数

numpy.rad2deg(x) 函数和 numpy.degrees(x) 函数的作用是一样的,将输入数组 x 中的元素从弧度转换为角度。

import numpy as np

# 定义一个弧度数组
x = np.array([0, np.pi/2, np.pi])
print("弧度数组:", x)

# 使用 rad2deg() 转换为角度数组
y = np.rad2deg(x)
print("角度数组:", y)

输出结果:

弧度数组: [0.         1.57079633 3.14159265]
角度数组: [ 0. 90. 180.]

值得注意的是,这两个函数的参数必须是弧度值,否则会出错。

import numpy as np

# 定义一个角度数组
x = np.array([0, 90, 180])
print("角度数组:", x)

# 使用 degrees() 转换为弧度数组,会出现错误
y = np.degrees(x)
print("弧度数组:", y)

输出结果:

角度数组: [  0  90 180]
Traceback (most recent call last):
  File "numpy_degrees_rad2deg.py", line 7, in <module>
    y = np.degrees(x)
TypeError: ufunc 'degrees' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''