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,
Do you need the actual distance? You could use the distance squared to determine if they are the same, and for many other purposes. (saves on the sqrt operation)
You may try to use SSE extensions. For example, you can init two vectors A(x1,y1,z1) and B(x2,y2,z2):
_m128 A = _mm_set_ps(x1, y1, z1, 0.0f)
_m128 B = _mm_set_ps(x2, y2, z2, 0.0f)
Then compute diff using _mm_sub_ps:
__m128 Diff = _mm_sub_ps(A, B)
Next compute sqr of diff:
__m128 Sqr = __mm_mul_ps(Diff, Diff)
And finally:
__m128 Sum = add_horizontal(Sqr)
__m128 Res = _mm_sqrt_ss(Sum)
Res[0] will be filled with your answer.
P.S. add_horizontal is a place for optimization
Note that when using sqrt(dx*dx+dy*dy+dz*dz)
the sum of squares might overflow. hypot(dx, dy)
computes a distance directly without any chance of overflow. I'm not sure of the speediest 3d equivalent, but hypot(dx, hypot(dy, dz))
does the job and won't overflow either.
There are faster ways to get an approximate distance but nothing built into the standard libraries. Take a look at this article on FlipCode that covers the method for fast 2D distances. It essentially collapsed the sqrt function into a compound linear function that can be quickly calculated but isn't 100% accurate. However, on modern machines these days fpmath is fairly fast so don't optimize too early, you might find that you're fine taking your simple approach.
The GNU Scientific Library defines gsl_hypot3
that computes exactly the distance you want in the first part of your question. Kind of overkill compiling the whole thing just for that, given Darius' suggestion, but maybe there's other stuff there you want.
As far as Question 1 goes, the performance penalty is the calculation of the square root itself. The formula for calculating the distance using the square root of paired coordinate differences is what it is.
I would highly recommend to read this A-M-A-Z-I-N-G square root implementation by John Carmack of ID software he used in his engine in Quake III. It is simply MAGICAL.