简体   繁体   English

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

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

How to convert the value of one arbitrary angle x , in radians, from the interval ]-infinite, infinite[ to the equivalent angle in the interval [-pi, pi] ?如何将任意角度x的值(以弧度表示)从区间]-infinite,infinite[转换为区间[-pi, pi]中的等效角度?

Examples of such a conversion, in degrees:这种转换的例子,以度为单位:

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

If you have access to at least version 3.7 of Python, then the math module has a function math.remainder that does exactly what you want in a single function call.如果您至少可以访问 Python 的 3.7 版,则math模块有一个 function math.remainder可以在单个 ZC1C425268E683854F14Z 调用中完全满足您的需求。 Just use math.remainder(my_angle, 2*math.pi) (or for fun, use math.tau instead of 2 * math.pi ).只需使用math.remainder(my_angle, 2*math.pi) (或者为了好玩,使用math.tau而不是2 * math.pi )。

Example:例子:

>>> 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

One possible way:一种可能的方式:

import numpy as np

np.arctan2(np.sin(x), np.cos(x))  # converts x to [-np.pi, np.pi]

...and: ...和:

np.arctan2(np.sin(x), np.cos(x)) + np.pi  # converts x to [0, 2*np.pi]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM