I am writing a code in C++ and want to compute distance between two points. Question 1:
I have two points P(x1, y1, z1) and Q(x2, y2, z2) , where x,
No, there is no more efficient way to calc the dist. Any treatment with special cases p.x==q.x etc. will be slower on average.
Yes, the fastest way to see if p and q are the same points is just comparing x, y, z. Since they are float, you should not check == but allow for some finite, small difference which you define.
No there is no better way.
The implementation of square_root
might be optimised.
If you are comparing two distances and want to know the longer, but do not care about what the actual distance is, then you can simply ingore the square-rooting step completely and manipulate your distances still squared. This would be applicable to comparing two pairs of points to determine if they are the same distance apart, for example.
You might find this article interesting:
http://www.codemaestro.com/reviews/9
It describes how the square root was calculated in the Quake 3 engine, claiming that on some CPU's it ran 4 times as fast as the sqrt() function. Not sure whether it'll give you a performance boost in C++ nowadays - but still an interesting read
Q2 answer: x1 = x2 and y1 = y2 and z1 = z2 if the points are the same.
Taking in consideration that you store points as float/double you might need to do the comparison with some epsilon.
Is there a better way if I just want to determine if P and Q are in fact the same points?
Then just compare the coordinates directly!
bool areEqual(const Point& p1, const Point& p2) {
return fabs(p1.x - p2.x) < EPSILON &&
fabs(p1.y - p2.y) < EPSILON &&
fabs(p1.z - p2.z) < EPSILON;
}