Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to calculate the angle between three 3D points.
The results are not what I expect.
Can anyone please tell me where the code may be incorrect and how to fix it?

# points are A, B, C each with 3 coordinates (x, y, z) # stored as array elements [0],[1],[2] # value desired is cos(theta) between AB and BC that # should range 0 to 1, where 1 is a straight line A to C # Calculate by cos(theta) = AB*BC (dot product) @AB = ($B[0]-$A[0], $B[1]-$A[1], $B[2]-$A[2]); @BC = ($C[0]-$B[0], $C[1]-$B[1], $C[2]-$B[2]); $lengthAB = sqrt((($AB[0])**2)+(($AB[1])**2)+(($AB[2])**2); $lengthBC = sqrt((($BC[0])**2)+(($BC[1])**2)+(($BC[2])**2); @unitvectorAB=($AB[0]/$lengthAB, $AB[1]/$lengthAB, $AB[2]/$lengthAB); @unitvectorBC=($BC[0]/$lengthBC, $BC[1]/$lengthBC, $BC[2]/$lengthBC); $costheta = ($unitvectorAB[0]*$unitvectorBC[0])+($unitvectorAB[1]*$uni +tvectorBC[1])+($unitvectorAB[2]*$unitvectorBC[2]);
Thank you!

Replies are listed 'Best First'.
Re: Calculate Angle Between Three 3D Points
by dws (Chancellor) on Aug 20, 2003 at 18:41 UTC
    I'm trying to calculate the angle between three 3D points. The results are not what I expect.

    It looks like you're on the right track: prior to normalizing the vectors, translate the vectors such that B is at (0,0,0). But your translation looks wrong. Think @BA instead of @AB, walk through your math again, and see if you can spot the problem.

      THANK YOU! It works when I reverse @AB into @BA.
      The expected answers for cos(theta) from dot product are now
      -1 to 0, and that is fine with me. Thanks again!
Re: Calculate Angle Between Three 3D Points
by Zeroth (Beadle) on Aug 20, 2003 at 18:21 UTC
      Thanks for the advice (and the rapid response!)
      However, I cannot get Math::VectorReal to work with my Perl.
      It gives the error message: Can't locate Math/VectorReal.pm in @INC

      I think it would be easier for now to fix the code written
      above, so does anyone see a mistake and know how to fix it?

        That's because you have to install it from CPAN. It's not a module that comes standard with Perl. Click on the link: Math::VectorReal and download it.

        ------
        We are the carpenters and bricklayers of the Information Age.

        The idea is a little like C++ templates, except not quite so brain-meltingly complicated. -- TheDamian, Exegesis 6

        Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.