开发者

Test if number is inside circular interval

开发者 https://www.devze.com 2023-03-18 13:12 出处:网络
Let us suppose we have a number 开发者_StackOverflowcircle, that ranges from -180 to 180, looking something like this:

Let us suppose we have a number 开发者_StackOverflowcircle, 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


  • 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)


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.


You have start and end as endpoints of the intervall.

range = 360
if start > end:
    if number > start:
        end += range
    else:
        start -= range
inside = (number >= start) and (number <= end)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号