Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Examples of such a conversion, in degrees:

  • 45 deg => 45 deg
  • 180 deg => 180 deg
  • 181 deg => -179 deg
  • -200 deg => 160 deg
  • 380 deg => 20 deg
like image 436
Bernardo Costa Avatar asked Sep 02 '25 06:09

Bernardo Costa


1 Answers

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. Just use math.remainder(my_angle, 2*math.pi) (or for fun, use math.tau instead of 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
like image 58
Mark Dickinson Avatar answered Sep 04 '25 19:09

Mark Dickinson