# Distance Formula Implecations: Urgent!

Printable View

• 03-18-2004
KneeLess
Distance Formula Implecations: Urgent!
Hello. As we all know, the distance formula is sqrt(sq(x2-x1) + sq(y2 - y1)). sq = square. Now, for some reason, this isn't at all working. Here is my code:

Code:

```float distance(float x2, float y2) {   float distance = 0;   static float x1 = 7, y1 = 2;   distance = sq(x2 - x1) + sq(y2 - y1);   distance = 4 * sq(distance) + 0.5;   x1 = x2;   y1 = y2;   return distance; }```
Now I don't have the math.h libraries available (working with a special embedded system, using a special compiler) therefore I have no sqrt() availible, so i just squared it a second time. Assume all numbers are correct, because they are. But when I do something like: sqrt(sq(6-7) + sq(1-2)) which in my calculator comes out to 1.41421... but in my program comes out to -46.500000. Also I'm using printf("%f\n", distance) to print. I just don't understance what's wrong, any help would be much appreciated.
• 03-18-2004
XSquared
...and what's your sq( ) function?
• 03-18-2004
KneeLess
Nevermind, fixed. Don't you hate that? Worked on it for 6 hours only to fix it in three minutes. :rolleyes:
• 03-18-2004
major_blagger
How did you fix it?
• 03-19-2004
VirtualAce
You can use a power series to estimate distance or if you know the angle you are looking you can find the distance by

Code:

```if (distx>disty) {   totaldist=distx/cos(angle); } else totaldist=disty/sin(angle);```
• 03-20-2004
joed
distance
A little off the subject, but here's a neat way to approximate integer distance, if you don't care about precision. Saw this somewhere and simplified the shifting for my needs:

Code:

```int fastdist(int x1, int y1, int x2, int y2) {   int dx = abs(x2 - x1);   int dy = abs(y2 - y1);   if(dy > dx) {        // XOR swap function     dx ^= dy;     dy ^= dx;     dx ^= dy;   }   return ((dx << 4) + (dx << 2) +           (dy << 4) - (dy << 3)) >> 4; }```
Making the shifting more complex adds precision, without costing too much, but this was precise enough for the short pixel distances I was measuring. Haven't tried converting to fixed-point.

-Joe
• 03-20-2004
VirtualAce
Yes you can approximate distance via a power series, but it has an error of like 3 or 4 percent.