可以把计算两条直线的角度转换成计算两个向量的角度问题,这样可以用numpy的点乘(np.dot())很好地解决,可以很容易扩展维度(从平面扩展到空间或者更高维度)
def unit_vector(vector):
""" Returns the unit vector of the vector. """
return vector / np.linalg.norm(vector)
def angle_between(v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
angle_between((1, 0, 0), (1, 0, 0))
0.0
ngle_between((1, 0, 0), (-1, 0, 0))
3.141592653589793
"""
v1_u = unit_vector(v1)
v2_u = unit_vector(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
# 假设计算直线p11p12和直线p21p22的夹角
p11 = [1, 2, 3]
p12 = [2, 3, 4]
p21 = [3, 4, 5]
p22 = [4, 5, 6]
v1 = np.array(np.array(p11)-np.array(p12))
v2 = np.array(np.array(p21)-np.array(p22))
angle12 = angle_between(v1, v2)
代码参考https://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python