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

Ber*_*sta 1 python trigonometry numpy angle

如何将一个任意角度x(以弧度为单位)的值从区间]-infinite,Infinite[转换为区间[-pi , pi]中的等效角度?

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

  • 45 度 => 45 度
  • 180 度 => 180 度
  • 181 度 => -179 度
  • -200 度 => 160 度
  • 380 度 => 20 度

Mar*_*son 5

如果您至少可以访问 Python 3.7 版本,则该math模块具有的函数math.remainder可以在单个函数调用中完全执行您想要的操作。只需使用math.remainder(my_angle, 2*math.pi)(或者为了好玩,使用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
Run Code Online (Sandbox Code Playgroud)