Test if number is inside circular interval

余生长醉 提交于 2021-02-19 01:15:53

问题


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

回答1:


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




回答2:


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.




回答3:


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)


来源:https://stackoverflow.com/questions/6613718/test-if-number-is-inside-circular-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!