Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if number is inside circular interval

Let us suppose we have a number circle, that ranges from -180 to 180, looking something like this:

         180/-180
           ***
         *** ***
    90 ***     *** -90
         *** ***
           ***
            0

A section of the circle is always swept in a clockwise direction. How can you tell if a number is inside or outside of the interval swept?

In the following sample I/O, the first two numbers represent the interval and the third number is the number being checked. Output is true if the point is (inclusively) inside the interval, false otherwise.

2 4 6
False
2 4 4
True
90 -90 0
False
90 -90 -180
True
like image 662
Peter Olson Avatar asked Jul 07 '11 16:07

Peter Olson


2 Answers

  • Normalize your numbers from 0 to 359. Consider the arguments a, b and c (is c inside the sweep of a -> b). As pointed out by Chris Cunningham, you can also normalize to -180 to +179; see discussion below. The important part of normalization is to make sure only one number refers to each point on the circle.

  • If (a <= b) then return (c >= a && c <= b)

  • else you've swept across the 0 point and should return (c >= b || c <= a) (c >= a || c <= b)

like image 146
tomlogic Avatar answered Sep 24 '22 08:09

tomlogic


All the points x that are in [a,b] verifies :

if a%360<=b%360:

(x)%360<=b%360 and x%360>=a%360 if you process in the direct sens.

otherwise your intervall contains 0, and you can just verify. x in[a,b]

therefore:

def f(x,a,b):
    if a%360<=b%360:
        return ((x)%360<=b%360 and x%360>=a%360)
    else:
        return b>=x>=a

does what you need.

>>> f(0,90,-90)
False
>>> f(-180,90,-90)
True
>>> f(4,2,4)
True
>>> f(6,2,4)
False

I might inverse some things.. so you wil may be need to check it again.

like image 37
Ricky Bobby Avatar answered Sep 23 '22 08:09

Ricky Bobby