folks,
If I have a list of floats and I want to make them within the range 0 to 2pi by adding or subtracting 2pi. What is a good way to do it?
Thanks very much.
Use %
operator:
>>> pi = 3.1415
>>> angle = 2*pi+0.5
>>> angle % (2*pi)
0.5
>>> angle = -4*pi + 0.5
>>> angle % (2*pi)
0.5
For a list of angles just use list comprehensions:
>>> L = [2*pi + 0.5, 4*pi + 0.6]
>>> [i % (2*pi) for i in L]
[0.5, 0.5999999999999996]
>>>
You can take the answers mod 2 pi:
>>> import random
>>> from math import pi
>>> xx = list(random.uniform(-10,10) for i in range(4))
>>> xx
[-3.652068894375777, -6.357128588604748, 9.896564215080154, -6.298659336390939]
>>> yy = list(x % (2*pi) for x in xx)
>>> yy
[2.6311164128038094, 6.209242025754424, 3.613378907900568, 6.267711277968234]