在Python中计算两个向量之间的角度 [英] Calculating angle between two vectors in python
问题描述
我正在尝试在python中计算两条线之间的角度. 我搜索了互联网,找到了如何做的方程式.但是我并不总是能得到准确的结果.当其他结果似乎正确时,其中一些结果显然是错误的. 我的代码如下:
I am trying to calculate the angle between two lines in python. I searched the internet and found the equation on how to do it. But I don't always get accurate result. Some of the results are clearly false when other seems correct. My code is given below:
def angle(pt1,pt2):
m1 = (pt1.getY() - pt1.getY())/1
m2 = (pt2.getY() - pt1.getY())/(pt2.getX()-pt1.getX())
tnAngle = (m1-m2)/(1+(m1*m2))
return math.atan(tnAngle)
def calculate(pt,ls):
i=2
for x in ls:
pt2 = point(x,i)
i=i+1
ang = angle(pt,pt2)*180/math.pi
ang = ang * (-1)
print ang
pt = point(3,1)
ls = [1,7,0,4,9,6,150]
calculate(pt,ls)
它产生的结果是:
45.0
0.0
45.0
-75.9637565321
0.0
-63.4349488229
0.0
问题在于,我不明白为什么第二个结果(第五个和最后一个结果)被归零,因为它们共享一个点,而另一个点却不重复,因为数组中的值不同.
The problem is that I don't understand why the second result, fifth and the last one are zeroed they intersect since they share a point and the other point in not duplicated since the value in the array is different.
推荐答案
看起来您正在使用Python2,如果两个参数都为int,则/
将执行整数除法.要获得Python3的行为,您可以将其放在文件顶部
It looks like you are using Python2, where /
will do an integer division if both arguments are int. To get the behaviour that Python3 has, you can put this at the top of the file
from __future__ import division
这篇关于在Python中计算两个向量之间的角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!