Search code examples
pythonmathgeometryradians

How can I efficiently convert an angle (in radian) to an index from 0 to 7?


I have an angle in radian, and I'd like to convert it into a value indexed from 0 to 7 in the following manner :

enter image description here

Note that 0 rad should fall in the middle of the sector, etc.

What would be the most efficient way to do this, using simple math?


Solution

  • Each "slice" takes up pi/4. Following what @Beta said, you can do this:

    def rad2slice(rad):
        return int((4 * rad / np.pi + .5) % 8)
    
    # Quick test:
    In [22]: [rad2slice(i*np.pi/4) for i in range(8)]                               
    Out[22]: [0, 1, 2, 3, 4, 5, 6, 7]