Go Down

### Topic: Calculate the minimum angular movement between two compass points? (Read 594 times)previous topic - next topic

#### warren631

##### Nov 09, 2012, 06:09 am
Does anyone have a handy dandy function to do this (returns results from -180 to +180)?
For example:
move from 90 to 180 = 90 (easy)
move from 180 to 90 = -90 (easy)
move from 45 to 359 = -46 (not so easy)
move from 315 to 90 = 135 (not so easy)
(Clockwise move is positive, anti-clock is negative).

#### WizenedEE

#1
##### Nov 09, 2012, 06:18 am
function:
Code: [Select]
`int angDist(int p1, int p2) {  int rawdist = p2 - p1;  while (rawdist <  -180) rawdist += 360;  while (rawdist >= +180) rawdist -= 360;  return rawdist;}`
and test code:
Code: [Select]
`#include <iostream>using namespace std;int angDist(int p1, int p2) {  int rawdist = p2 - p1;  while (rawdist <  -180) rawdist += 360;  while (rawdist >= +180) rawdist -= 360;  return rawdist;}#define printfunc(x,y) cout << "x: " << x << "y: " << y << "angDist(x, y): " << angDist(x, y) << endlint main() {    printfunc(90, 180);    printfunc(180, 90);    printfunc(45, 359);    printfunc(315,90);}`

prints out results you gave

#### warren631

#2
##### Nov 09, 2012, 04:15 pm
Thanks WizenedEE.  I also found these on the internet which might be of use to others looking for such a function:
Code: [Select]
`int angle_difference(int target, int head){  return ((((target - head) % 360) + 540) % 360) - 180;}int angleDifference(int target, int head){  return abs((target + 180 -  head) % 360 - 180);}`

Go Up