Calculating which two points are the closest together given a series of points.

184 Views Asked by At

I'm in a position where I need to calculate the distance between two points to determine which is the closest point. Now, the proper formula to do this is:

$$distance = \sqrt{(x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2}$$

That's all well and good, but it's rather slow to calculate. I don't need to know the distance, just that the calculated distance is the shortest. So, thinking about how to do this, if I throw away the powering and square root, would I be able to determine which distance is the shortest by comparing the results, even though it would most certainly not give an accurate distance?

1

There are 1 best solutions below

2
On BEST ANSWER

You can remove the square root -- just compare squared distances, rather than actual distances.

The multiplications will take very little time compared to the square root, but you can avoid some of those, too.

Suppose the current minimum distance is $d$, and suppose we're checking the point $P_i = (x_i, y_i, z_i)$ to see if it gives us a smaller distance to the base point $P_0 = (x_0, y_0, z_0)$. If $|x_i-x_0|$ is larger than $d$, then we know immediately that the distance from $P_i$ to $P_0$ is greater than $d$, so there's no sense in doing any further calculations. You can check $|y_i-y_0|$ and $|z_i-z_0|$ similarly.