使用3D坐标计算三点之间角度的python代码

时间:2016-02-03 11:58:36

标签: python math 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])

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 

输出代码:

degree 33.4118214995

但是当我使用其中一个软件来计算它时,它会使输出位不同120度。请帮忙

我已经习惯编写程序:

How to calculate bond angle in protein db file?

3 个答案:

答案 0 :(得分:12)

您的原始代码非常接近。 Adomas.m的答案不是非常惯用的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)

答案 1 :(得分:1)

我觉得numpy足够了:

    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

也可以用点计算res:

    res = abNorm[0] * bcNorm[0] + abNorm[1] * bcNorm[1] + abNorm[2] * bcNorm[2];
    res = dot(abNorm, bcNorm)

答案 2 :(得分:0)

或者,您也可以使用它,使用数学库。

 import math
 
def getAngle(a, b, c):
    ang = math.degrees(math.atan2(c[1]-b[1], c[0]-b[0]) - math.atan2(a[1]-b[1], a[0]-b[0]))
    return ang + 360 if ang < 0 else ang
 
print(getAngle((5, 0), (0, 0), (0, 5)))

信用:https://manivannan-ai.medium.com/find-the-angle-between-three-points-from-2d-using-python-348c513e2cd