开发者

Get angles in the range -180 to +180

Before I start thanking everybody.

Through my application s/w I will read syncro values which will be in angles. When I run Python script, the values are collected in particular variables.

Suppose the range is -180 to 180.

And I got angle as -180. According to the requirement it should be +/-1 deg window;ie; between 179 and -179.

How I will check whether its falling in that range ?

angle = -180
tolerance = 1 (in degree)
if(180-1) <= -180 <= (-180+1):
       # statements



angle1 = -179
tolerance = 1
if(-170-1)<= -179 <= (-179+1):
      # statements



angle2 = 179
tolerance = 1
if(179-1) <= 179 <= (179+1):
         # statements

will this work for all angle combinations ? wha开发者_运维百科t you think ?


if -180 < x < 180:
    #do something

This includes -179 and 179 in the range, but not -180 and 180.


If I understand you correctly, you have some angles that you want to make sure that they are close to a target angle, given a specific tolerance defining the closeness. I think this is what you need:

def restrict_angle(angle):
    "make sure any angle falls in the [0..360) range"
    return angle % 360

def is_angle_almost(angle, target_angle, tolerance):

    tolerance= abs(tolerance) # same meaning, easier logic

    angle= restrict_angle(angle)
    upper_limit= restrict_angle(target_angle + tolerance)
    lower_limit= restrict_angle(target_angle - tolerance)

    if upper_limit < lower_limit: # when target_angle close to -180
        upper_limit+= 360

    return (lower_limit <= angle <= upper_limit
        or lower_limit <= angle + 360 <= upper_limit)

if __name__ == "__main__":
    for test in (
        ( (90, 92, 3), True),
        ( (90, 92, -3), True),
        ( (90, 92, -1), False),
        ( (180, 181, 1), True),
        ( (180, 182, 1), False),
        ( (179, -180, 1), True),
        ( (-175, 180, 6), True),
        ( (-175, 180, 4), False),
        ( (4, 0, 5), True),
    ):
        if is_angle_almost(*test[0]) != test[1]:
            print ("fails for " + str(test[0]))
            break
    else:
        print "all tests successful"

The function you will use is is_angle_almost.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜