Efficient way of finding distance between two 3D points

后端 未结 11 1057
借酒劲吻你
借酒劲吻你 2021-02-01 06:42

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,

相关标签:
11条回答
  • 2021-02-01 07:09

    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)

    0 讨论(0)
  • 2021-02-01 07:09

    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

    0 讨论(0)
  • 2021-02-01 07:14

    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.

    0 讨论(0)
  • 2021-02-01 07:14

    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.

    0 讨论(0)
  • 2021-02-01 07:21

    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.

    0 讨论(0)
  • 2021-02-01 07:21

    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.

    0 讨论(0)
提交回复
热议问题