将任意角度转换为区间 [ -pi , pi ]

Convert any angle to the interval [ -pi , pi ]

如何将一个任意角度x的值,以弧度为单位,从区间]-无限,无限[转换为区间[-pi , pi]?

这种转换的示例,以度为单位:

输入域]-inf, inf[:

a1 = np.array([45, 180, 181, -200, 380, -721])

输出域]-180, 180[:

a2 = np.rad2deg(np.arctan2(np.sin(np.deg2rad(a1)), np.cos(np.deg2rad(a1))))
print(a2)  # [45., 180., -179., 160., 20., -1.]

输出域]0, 360[:

a3 = [i if i>=0 else i+360 for i in a2]
print(a3)  # [45., 180., 181., 160., 20., 359.]

如果您至少可以访问 Python 的 3.7 版,那么 math 模块具有函数 math.remainder that does exactly what you want in a single function call. Just use math.remainder(my_angle, 2*math.pi) (or for fun, use math.tau 而不是 2 * math.pi)。

示例:

>>> from math import remainder, tau
>>> math.remainder(2.7, tau)
2.7
>>> math.remainder(3.7, tau)  # note wraparound to 3.7 - 2*pi
-2.583185307179586
>>> math.remainder(1000.0, tau)
0.9735361584457891