Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to elegantly find if an angle is between a range?

Tags:

python

math

angle

For example, if my angle is 20 degrees, I can check if it is within [0, 40] like so:

lower = 0
upper = 40
if angle > lower and angle < upper:
        print('done')

However this logic will not work if my range crosses the 360 degree boundary (e.g. lower=350 and upper=40). I know I can handle this with additional if/else block but is there any elegant way?

like image 454
Selva Avatar asked Oct 16 '25 17:10

Selva


2 Answers

An easy way to do check if alpha is between lower and upper is to mesure angles modulo 360 from lower. This gives us positive values between 0 and 360.

We just have to check if (alpha - lower) modulo 360 is smaller than (upper - lower) modulo 360, as you can see on the illustrations:

alpha in the range:

alpha in the range

alpha out of the range:

enter image description here

def angle_in_range(alpha, lower, upper):
    return (alpha - lower) % 360 <= (upper - lower) % 360


tests = [(25, 20, 40), (15, 20, 40), (45, 20, 40), (10, 350, 20), (-5, 350, 20), (365, 350, 20), (330, 350, 20)]
for alpha, lower, upper in tests:
    print(f'{alpha} between {lower} and {upper}: {angle_in_range(alpha, lower, upper)}')

# 25 between 20 and 40: True
# 15 between 20 and 40: False
# 45 between 20 and 40: False
# 10 between 350 and 20: True
# -5 between 350 and 20: True
# 365 between 350 and 20: True
# 330 between 350 and 20: False
like image 172
Thierry Lathuille Avatar answered Oct 18 '25 05:10

Thierry Lathuille


First, make sure that all angles are modulo 360. Then, if the range appears backwards, reverse the condition.

So for example:

def in_range(lower, upper, angle):
    lower %= 360
    upper %= 360
    angle %= 360
    if lower > upper:
        return angle >= lower or angle <= upper
    return angle > lower and angle < upper
like image 28
Mad Physicist Avatar answered Oct 18 '25 05:10

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!