Calculate the difference between two compass headings Python
Question:
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
Answers:
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
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)
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
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
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)