Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python code to calculate angle between three point using their 3D coordinates

Tags:

python

math

numpy

I have write down a code to calculate angle between three points using their 3D coordinates.

import  numpy as np

a = np.array([32.49, -39.96,-3.86])

b = np.array([31.39, -39.28, -4.66])

c = np.array([31.14, -38.09,-4.49])

f = a-b # normalization of vectors
e = b-c # normalization of vectors

angle = dot(f, e) # calculates dot product 
print degrees(cos(angle))  # calculated angle in radians to degree 

output of the code:

degree 33.4118214995

but when i used one of the software to calculate the same it gives output bit different 120 degree. please help

reference i have used to write the program:

(How to calculate bond angle in protein db file?)

like image 714
jax Avatar asked Feb 03 '16 11:02

jax


People also ask

How do you find the angle of a 3D space?

To calculate the angle between two vectors in a 3D space: Find the dot product of the vectors. Divide the dot product by the magnitude of the first vector. Divide the resultant by the magnitude of the second vector.


2 Answers

Your original code is pretty close. Adomas.m's answer is not very idiomatic numpy:

import numpy as np

a = np.array([32.49, -39.96,-3.86])
b = np.array([31.39, -39.28, -4.66])
c = np.array([31.14, -38.09,-4.49])

ba = a - b
bc = c - b

cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
angle = np.arccos(cosine_angle)

print np.degrees(angle)
like image 164
Eric Avatar answered Sep 20 '22 06:09

Eric


I guess numpy is quite enough:

    from numpy import *
    from numpy.linalg import norm
    a = array([32.49, -39.96,-3.86])
    b = array([31.39, -39.28, -4.66])
    c = array([31.14, -38.09,-4.49])
    f = b-a 
    e = b-c 
    abVec = norm(f)
    bcVec = norm(e)
    abNorm = f / abVec;
    bcNorm = e / bcVec;
    res = abNorm[0] * bcNorm[0] + abNorm[1] * bcNorm[1] + abNorm[2] * bcNorm[2];
    angle = arccos(res)*180.0/ pi
    print angle

also the res can be calculated with dot:

    res = abNorm[0] * bcNorm[0] + abNorm[1] * bcNorm[1] + abNorm[2] * bcNorm[2];
    res = dot(abNorm, bcNorm)
like image 36
adomas.m Avatar answered Sep 20 '22 06:09

adomas.m