1

I have to test whether the difference in degrees between a compass reading and a set point is within x amount.

This post describes what I'm after, it's just in C# and I can't interpret how the solution would work.

E.g...

Compass Reading  Set Point  Difference (absolute)
360              1          1
50               60         10
1                360        1
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
Caspar B
  • 499
  • 1
  • 6
  • 19
  • I'd encourage you to try and translate the C# solution to Python yourself, and ask concrete question if and when you get stuck, posting the code you have so far. Right now the question reads as a "please code this up for me", which generally isn't a good fit for this site. – NPE Aug 13 '17 at 11:13

2 Answers2

2

this is translated code to python:

def getHeadingError(init, final):
    if init > 360 or init < 0 or final > 360 or final < 0:
        raise Exception("out of range")
    diff = final - init
    absDiff = abs(diff)

    if absDiff == 180:
        return absDiff
    elif absDiff < 180:
        return diff
    elif final > init:
        return absDiff - 360
    else:
        return 360 - absDiff

print("init -- final -- error")
print("360 -- 1 -- {}".format(getHeadingError(360, 1)))
print("50 -- 60 -- {}".format(getHeadingError(50, 60)))
print("1 -- 360 -- {}".format(getHeadingError(1, 360)))

i hope this can help you

Hadi Farhadi
  • 1,773
  • 2
  • 16
  • 33
0

The accepted answer works, but if you want a single return, the following will get the job done, too:

def get_compass_diff(current, target):
    diff = (current - 360) if current > 180 else current
    target = target - diff
    return target if target < 180 else target - 360

(and then if you need abs, just use abs where appropriate rather than baking it into your compass heading diff function)

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153