我需要在Python中确定两个n维向量之间的角度。例如,输入可能是两个列表,如下所示:[1,2,3,4]
和[6,7,8,9]
。
注意:如果两个向量具有相同的方向(例如,(1, 0, 0)
,(1, 0, 0)
)或相反的方向(例如,(-1, 0, 0)
,(1, 0, 0)
),则这里的所有其他答案均会失败。
以下是一个可以正确处理这些情况的函数:
import numpy as np
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
>>> angle_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))
arccos
函数。示例代码:In [140]: np.arccos(np.dot(np.array([1,0,0]),np.array([-1,0,0]) ))
Out[140]: 3.1415926535897931In [141]: np.arccos(np.dot(np.array([1,0,0]),np.array([1,0,0]) ))
Out[141]: 0.0 - enenan
。由于浮点精度问题,dot()
函数将返回1.0000000000000002
,即使是在版本1.16.1中也是如此。 - userimport math
def dotproduct(v1, v2):
return sum((a*b) for a, b in zip(v1, v2))
def length(v):
return math.sqrt(dotproduct(v, v))
def angle(v1, v2):
return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2)))
注意:当向量具有相同或相反方向时,此方法将失败。 正确的实现在这里:https://dev59.com/g3E85IYBdhLWcg3wVR-g#13849249
math.sqrt(x)
等价于x**0.5
,math.pow(x,y)
等价于x**y
,我很惊讶它们在Python 2.x到3.0的过渡期间幸存了下来。在实践中,我通常将这些数值操作作为计算密集型进程的一部分进行处理,解释器对'**'直接转化为字节码BINARY_POWER的支持,相对于查找'math',访问其属性'sqrt',然后是痛苦缓慢的字节码CALL_FUNCTION,可以在没有编码或可读性成本的情况下显着提高速度。 - PaulMcGangle((1., 1., 1.), (1., 1., 1.))
),则此方法将失败。请参见我的答案,其中包含稍微更正的版本。 - David Wolever使用numpy(强烈推荐)可以这样做:
from numpy import (array, dot, arccos, clip)
from numpy.linalg import norm
u = array([1.,2,3,4])
v = ...
c = dot(u,v)/norm(u)/norm(v) # -> cosine of the angle
angle = arccos(clip(c, -1, 1)) # if you really want the angle
nan
)。请参考我的答案获取更正确的版本。 - David Woleverangle = arccos(clip(c, -1, 1))
以避免舍入问题。这解决了@DavidWolever的问题。 - Tim Tisdallclip
添加到 numpy 导入列表中。 - Liam Deacon另一种可能性是仅使用numpy
,它会给出内角。
import numpy as np
p0 = [3.5, 6.7]
p1 = [7.9, 8.4]
p2 = [10.8, 4.8]
'''
compute angle (in degrees) for p0p1p2 corner
Inputs:
p0,p1,p2 - points in the form of [x,y]
'''
v0 = np.array(p0) - np.array(p1)
v1 = np.array(p2) - np.array(p1)
angle = np.math.atan2(np.linalg.det([v0,v1]),np.dot(v0,v1))
print np.degrees(angle)
这里是输出结果:
In [2]: p0, p1, p2 = [3.5, 6.7], [7.9, 8.4], [10.8, 4.8]
In [3]: v0 = np.array(p0) - np.array(p1)
In [4]: v1 = np.array(p2) - np.array(p1)
In [5]: v0
Out[5]: array([-4.4, -1.7])
In [6]: v1
Out[6]: array([ 2.9, -3.6])
In [7]: angle = np.math.atan2(np.linalg.det([v0,v1]),np.dot(v0,v1))
In [8]: angle
Out[8]: 1.8802197318858924
In [9]: np.degrees(angle)
Out[9]: 107.72865519428085
寻找两个向量间夹角的简便方法(适用于n维向量),
Python代码:
import numpy as np
vector1 = [1,0,0]
vector2 = [0,1,0]
unit_vector1 = vector1 / np.linalg.norm(vector1)
unit_vector2 = vector2 / np.linalg.norm(vector2)
dot_product = np.dot(unit_vector1, unit_vector2)
angle = np.arccos(dot_product) #angle in radian
如果你正在处理 3D 向量,你可以使用工具库 vg 来简洁地完成。它是建立在 numpy 上的轻量级扩展。
import numpy as np
import vg
vec1 = np.array([1, 2, 3])
vec2 = np.array([7, 8, 9])
vg.angle(vec1, vec2)
vg.angle(vec1, vec2, look=vg.basis.z)
或者通过投影计算有符号角度:
vg.signed_angle(vec1, vec2, look=vg.basis.z)
我在上一家创业公司创建了这个库,它的应用场景包括:将NumPy中冗长或难以理解的简单概念变得更加清晰易懂。
def unit_vector(vector):
""" Returns the unit vector of the vector"""
return vector / np.linalg.norm(vector)
def angle(vector1, vector2):
""" Returns the angle in radians between given vectors"""
v1_u = unit_vector(vector1)
v2_u = unit_vector(vector2)
minor = np.linalg.det(
np.stack((v1_u[-2:], v2_u[-2:]))
)
if minor == 0:
raise NotImplementedError('Too odd vectors =(')
return np.sign(minor) * np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
虽然存在 NotImplementedError
,但对于我的情况来说它已经很好用了。这种行为可以通过编写更多的代码来修复(因为手性是针对任何给定的一对确定的),但我并不想写那么多。
arccos(dot(u,v)/(norm(u)* norm(v)))
,如其他答案所述)在几种极端情况下存在数值不稳定性。以下代码适用于n维和所有极端情况(它不检查长度为零的向量,但可以像其他答案中所示那样轻松添加)。请参见下面的注释。from numpy import arctan, pi, signbit
from numpy.linalg import norm
def angle_btw(v1, v2):
u1 = v1 / norm(v1)
u2 = v2 / norm(v2)
y = u1 - u2
x = u1 + u2
a0 = 2 * arctan(norm(y) / norm(x))
if (not signbit(a0)) or signbit(pi - a0):
return a0
elif signbit(a0):
return 0.0
else:
return pi
对于那些可能因为SEO问题而到达此处,想要在Python中计算两条几何线段之间的角度,例如(x0, y0), (x1, y1)
,下面是一个最小的解决方案(使用了shapely
模块,但可以轻松修改为不使用):
Original Answer翻译成"最初的回答"
from shapely.geometry import LineString
import numpy as np
ninety_degrees_rad = 90.0 * np.pi / 180.0
def angle_between(line1, line2):
coords_1 = line1.coords
coords_2 = line2.coords
line1_vertical = (coords_1[1][0] - coords_1[0][0]) == 0.0
line2_vertical = (coords_2[1][0] - coords_2[0][0]) == 0.0
# Vertical lines have undefined slope, but we know their angle in rads is = 90° * π/180
if line1_vertical and line2_vertical:
# Perpendicular vertical lines
return 0.0
if line1_vertical or line2_vertical:
# 90° - angle of non-vertical line
non_vertical_line = line2 if line1_vertical else line1
return abs((90.0 * np.pi / 180.0) - np.arctan(slope(non_vertical_line)))
m1 = slope(line1)
m2 = slope(line2)
return np.arctan((m1 - m2)/(1 + m1*m2))
def slope(line):
# Assignments made purely for readability. One could opt to just one-line return them
x0 = line.coords[0][0]
y0 = line.coords[0][1]
x1 = line.coords[1][0]
y1 = line.coords[1][1]
return (y1 - y0) / (x1 - x0)
使用方法将是
>>> line1 = LineString([(0, 0), (0, 1)]) # vertical
>>> line2 = LineString([(0, 0), (1, 0)]) # horizontal
>>> angle_between(line1, line2)
1.5707963267948966
>>> np.degrees(angle_between(line1, line2))
90.0
在 Sgt Pepper 的优秀回答的基础上,增加了对齐向量的支持,并使用 Numba 实现了超过 2 倍的加速。
@njit(cache=True, nogil=True)
def angle(vector1, vector2):
""" Returns the angle in radians between given vectors"""
v1_u = unit_vector(vector1)
v2_u = unit_vector(vector2)
minor = np.linalg.det(
np.stack((v1_u[-2:], v2_u[-2:]))
)
if minor == 0:
sign = 1
else:
sign = -np.sign(minor)
dot_p = np.dot(v1_u, v2_u)
dot_p = min(max(dot_p, -1.0), 1.0)
return sign * np.arccos(dot_p)
@njit(cache=True, nogil=True)
def unit_vector(vector):
""" Returns the unit vector of the vector. """
return vector / np.linalg.norm(vector)
def test_angle():
def npf(x):
return np.array(x, dtype=float)
assert np.isclose(angle(npf((1, 1)), npf((1, 0))), pi / 4)
assert np.isclose(angle(npf((1, 0)), npf((1, 1))), -pi / 4)
assert np.isclose(angle(npf((0, 1)), npf((1, 0))), pi / 2)
assert np.isclose(angle(npf((1, 0)), npf((0, 1))), -pi / 2)
assert np.isclose(angle(npf((1, 0)), npf((1, 0))), 0)
assert np.isclose(angle(npf((1, 0)), npf((-1, 0))), pi)
%%timeit
没有使用Numba的结果
使用Numba的结果