• Create Account

## simple 8 way direction finding algorithm?

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

10 replies to this topic

### #1xinfinite33  Members

204
Like
0Likes
Like

Posted 30 November 2012 - 11:15 AM

hi guys. Well the problem I'm having is that I have been trying to create a simple function that takes in 2 points and determines the direction from one point to another then displays the direction as N,NE,E,SE,S,SW,W,NW Like a compass. I found a very simple way to do this for 4 directions by subtracting point 2's coordinates from point 1's coordinates. then I get the absolute value of the x distance and the y distance and determine which axis's distance is greater. if the Y distance is greater, then point2 is either North(negative) or South(positive) of point1, and If the X distance is greater, then point2 is either East(positive) or West(negative) of point1. This method is very fast, But as you see this only provides 4 directions. Is there a simple trick similar to this one that yields 8 directions instead of 4? I know I could just go the angular route and divide 360 by 8, then find the angle of point A to point B and see which range it lies in, but i'm trying to find a simpler solution that doesn't use division or other expensive operations, just for the sake of tiny optimizations lol. Any ideas?

### #2SiCrane  Moderators

11523
Like
3Likes
Like

Posted 30 November 2012 - 11:22 AM

Get a normalized vector for each direction and then take the dot product of each direction against the vector of one point to the other. The one with the largest positive dot product will be the closest direction.

### #3xinfinite33  Members

204
Like
0Likes
Like

Posted 30 November 2012 - 12:48 PM

Thanks SiCrane. thats a really nice way to do it, even tho you have to use division and square root to normalize a vector, but its much cleaner than the way I was doing it. thanks alot!

### #4SiCrane  Moderators

11523
Like
0Likes
Like

Posted 30 November 2012 - 12:52 PM

If you only care about the eight directions, then you can precalculate the normals so you won't have to deal with the cost every time you find the heading.

### #5ifthen  Members

820
Like
0Likes
Like

Posted 30 November 2012 - 01:07 PM

I agree with SiCrane – that would probably be the simplest way to do it (if you got vector classes lying handy, if not, code a one!).

But if you (and future readers of this thread) need an angle like the one on a compass (I have instantly remembered Silent Hunter when reading this thread), there exists a function atan2(y, x) in most of non-obscure programming languages, which (if given parameters in the expected order) returns an angle in normal mathematical notation (the "fixed" ray of the angle is pointing from (0;0) to right (1;0), goes into plus numbers counterclockwise and in radians).
If you wanted to get an angle as they are on a compass (0 points north, 90 east), you would need to do something like (NOT TESTED, use at own risk and test first)
[source lang="cpp"]/* if observer is at (0;1) and dest (0;5), the diff would be (0;4), which points north - correct */vertex diff = destination - observer; /* we switch the Y sign and the arguments to get the angle from (0;1) NORTH, not (1;0) WEST; switching X sign flips the direction clockwiseangle is now in interval (-pi;pi>*/double angle = atan2(-diff.x, -diff.y);/* convert to degrees; angle is now in interval (-180;180> */angle = angle * 180. / M_PI/* convert the angle to interval <0;360)*/if (angle < 0) /* since the angle is now below zero, adding it to 360 will simply subtract the positive angle */ angle = 360 + angle;[/source]
Also, you really shouldn't worry about performance of most things you code. Suppose that your CPU has a frequency of 3 GHz. That means it can do 3,000,000,000 operations per second. A code to calculate this could take 50-200 operations (I take the numbers out of my hat – just for demonstration). So you would have to compute thirty millions of angles per second for you FPS to drop to 10. That doesn't happen often with angles, but e.g. with model vertices, it certainly is be possible to slow down like this. The point is, don't do premature optimization. Optimize when needed.

### #6Álvaro  Members

20253
Like
2Likes
Like

Posted 30 November 2012 - 01:41 PM

This problem is a good excuse to have some fun with obfuscation:

enum Direction8 {N,NE,E,SE,S,SW,W,NW};

Direction8 direction8(double x, double y) {
static double const Cosine = std::cos(0.5*std::atan(1.0)), Sine = std::sin(0.5*std::atan(1.0));

double rx = x*Cosine - y*Sine;
double ry = x*Sine + y*Cosine;

int i = 7 - (std::abs(rx) > std::abs(ry));
if (ry < 0.0) i = 11-i;
if (rx < 0.0) i = 7-i;

return Direction8(i);
}


### #7xinfinite33  Members

204
Like
0Likes
Like

Posted 30 November 2012 - 01:54 PM

thanks for the replies guys!
@SiCrane thanks for the suggestion about precalculated normals. I'm surprised I didn't think about that sooner.

@ifthen thanks for your reply, as well as the advice about premature optimization. and yes I coded my own simple vector class "which wasn't as hard to do as I thought lol".
this is my first time seeing the method you suggested before. I'll benchmark test it a few times and keep it for future reference! thanks

@Álvaro Thanks for the code! That's a very elegant way to handle it lol. and since Sine and Cosine can be precalculated that makes it even more useful.

and again thanks a lot guys!

Edited by xinfinite33, 30 November 2012 - 02:02 PM.

### #8fastcall22  Moderators

9738
Like
1Likes
Like

Posted 30 November 2012 - 02:16 PM

... but i'm trying to find a simpler solution that doesn't use division or other expensive operations, just for the sake of tiny optimizations lol

ಠ__ಠ

Mathematical operations and floating point operations haven't been a bottle-neck concerns in decades (in the general case, that is). The biggest performance killers now-a-days are cache mismanagement and branch mispredictions. In other words, algorithm-level optimizations will perform better than hardware-level optimizations of poor-performing algorithms. Avoid micro-optimizations unless you have proof from a profiler that a specific area of the code can benefit from such optimizations.

Anyways, there isn't anything inherently wrong with an angle-based approach. Though, you could use a branch-less version, and it might perform faster than a version with branching or a vector-and-dot-product approach:
const char* cardinal_direction(float ang) {
// Assuming sane negative numbers, +y is up, 4-byte alignment
static const char* label[8][4] = {"E", "NE", "N", "NW", "W", "SW", "S", "SE"};
return label[(int)(fmodf((ang+17*pi/8),2*pi)*4/pi)];
}
const char* cardinal_direction(float dy,float dx) {
return cardinal_direction(atan2(dy,dx));
}

(Though unreadable and perhaps unmaintainable, this was a fun exercise.)

Though, such optimizations are moot, unless you are calculating millions of cardinal_directions per second...
zlib: eJzVVLsSAiEQ6/1qCwoK i7PxA/2S2zMOZljYB1TO ZG7OhUtiduH9egZQCJH9 KcJyo4Wq9t0/RXkKmjx+ cgU4FIMWHhKCU+o/Nx2R LEPgQWLtnfcErbiEl0u4 0UrMghhZewgYcptoEF42 YMj+Z1kg+bVvqxhyo17h nUf+h4b2W4bR4XO01TJ7 qFNzA7jjbxyL71Avh6Tv odnFk4hnxxAf4w6496Kd OgH7/RxC

### #9xinfinite33  Members

204
Like
0Likes
Like

Posted 30 November 2012 - 02:46 PM

loool I know it Isn't that much of a difference when it comes to optimizing since we can do millions of operations a second. I cant remember where but I read somewhere that division was the slowest operation out of all the others, excluding the case where your'e multiplying numbers less than one, then division is faster. I apologize for my novice assumption as I am still fairly new to programming .

Edited by xinfinite33, 30 November 2012 - 02:47 PM.

### #10Álvaro  Members

20253
Like
0Likes
Like

Posted 30 November 2012 - 03:10 PM

loool I know it Isn't that much of a difference when it comes to optimizing since we can do millions of operations a second. I cant remember where but I read somewhere that division was the slowest operation out of all the others, excluding the case where your'e multiplying numbers less than one, then division is faster. I apologize for my novice assumption as I am still fairly new to programming .

You should try to forget all of that, since it's mostly wrong. The only way you have to know for sure what is faster is to try it both ways inside of your program and measure.

There are some rules of thumb that can guide you, but what is faster than what changes over time, so you should always measure, instead of assuming your heuristics are correct.

### #11ifthen  Members

820
Like
0Likes
Like

Posted 30 November 2012 - 04:57 PM

Remember that in programming, correctness comes first, readability afterwards and speed the last.

Once you write down a slow but correct algorithm in your function, you can always rewrite it for speed later. If you write a speedy one, yet it fails to handle corner cases, it is useless (and you will spend days trying to find the bug). C(++/other low level languages) is very tricky for beginners: they think that because it is advertised for speed, they have to write fast code with it – otherwise, why would they even bother not using Java?

That is a wrong approach. Code is not "slow" in general, only small segments are (copying large arrays, nested loop on one array...). C can, unlike high-level languages, sometimes speed up bottlenecks that cannot be solved by better algorithm. The other 99% of code are performance-wise unremarkable.

When a lumberjack gets a chainsaw instead of saw, he doesn't swing it so he can chop a tree even faster. He would just cut off his leg.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.