简体   繁体   中英

python: make the elements of a list within a certain range

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]

Consider using math.fmod() since it's better at handling rounding of floats than the % operator. See discussion here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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