xcoder xcoder - 2 months ago 13
Objective-C Question

Fastest way to calculate the distance between two CGPoints?

Distance between two points:

sqrt((x1-x2)^2 + (y1-y2)^2)


Is there a way to do this math faster in objective-C ?

EDIT: I think I need to clarify above. I wrote the formula above just to clarify what formula I am using to calculate the distance. ^ is not meant to represent xor - I just wanted to represent the mathematical formula without using any functions like pow or anything, so I meant to use ^ to "raise to the power off". I was wondering if anyone knows if using bitwise operators, or otherwise writing code in assembly would give an optimized version. I am using the formula in an iPhone / iPad application.

Answer

No, if you need the exact distance you cannot beat that formula.

Although to be clear ^ is not an operator for squaring a value, but a bit operator that does xor.

you will need something like

double dx = (x2-x1);
double dy = (y2-y1);
double dist = sqrt(dx*dx + dy*dy);

If you can live with just the square (which is useful when you just want to do something like sort by distance, you can use the much more efficient

double dx = (x2-x1);
double dy = (y2-y1);
double dist = dx*dx + dy*dy;

These will be at least as good as a solution pow. At worst, pow() will use the stack and be less efficient, but maybe your compiler turns it into x*x for this case.