首页 > 解决方案 > 如何在python中找到两个向量之间的顺时针角度?

问题描述

我想在python中找到两个向量之间的顺时针角度,角度应该在(-90,90)的范围内

计算角度的方程式/代码是什么?

class Vect:
  def __init__(self, a, b):
    self.a = a
    self.b = b

  def findClockwiseAngle(self, other):
    ## how to compute ??
    pass


vector1 = Vect(a1,b1)  ## a1*i + b1*j
vector2 = Vect(a2,b2)  ## a2*i + b2*j
angle = vect1.findClockwiseAngle(vect2)

标签: python-3.xcomputational-geometry

解决方案


矢量几何提供了(至少)两个有用的公式来找到两个矢量之间的角度:

可以使用哪里a · b计算

在哪里

由于我们的向量是二维的,我们可以取a3b3(z 轴方向的分量)等于 0。这进一步简化了公式:

|a x b| = |a1 * b2 - a2 * b1| = |a| * |b| * sin(ϴ)

s 是这ϴ两个公式,然而,有不同的解释。使用点积,角度是两个向量之间的夹角——因此总是一个介于 0 和 pi 之间的值。

使用叉积,角度从到 到逆时针方向测量。由于您正在寻找以顺时针方向测量的角度,因此您只需反转使用叉积公式获得的角度的符号。ab

在 Python 中,math.asin返回 [-pi/2, pi/2] 范围内的值,而math.acos返回 [0, pi] 范围内的值。由于您需要 [-pi/2, pi/2] 范围内的角度(以弧度为单位),因此叉积公式似乎是更有希望的候选者:

import math

class Vect:

   def __init__(self, a, b):
        self.a = a
        self.b = b

   def findClockwiseAngle(self, other):
       # using cross-product formula
       return -math.degrees(math.asin((self.a * other.b - self.b * other.a)/(self.length()*other.length())))
       # the dot-product formula, left here just for comparison (does not return angles in the desired range)
       # return math.degrees(math.acos((self.a * other.a + self.b * other.b)/(self.length()*other.length())))

   def length(self):
       return math.sqrt(self.a**2 + self.b**2)

vector1 = Vect(2,0) 

N = 12
theta = [i * 2 * math.pi / N for i in range(N)]
result = []
for t in theta:
    vector2 = Vect(math.cos(t), math.sin(t))  ## a2*i + b2*j
    angle = vector1.findClockwiseAngle(vector2)
    result.append((math.degrees(t), angle))

print('{:>10}{:>10}'.format('t', 'angle'))    
print('\n'.join(['{:>10.2f}{:>10.2f}'.format(*pair) for pair in result]))

印刷

     t     angle
  0.00     -0.00
 30.00    -30.00
 60.00    -60.00
 90.00    -90.00
120.00    -60.00
150.00    -30.00
180.00     -0.00
210.00     30.00
240.00     60.00
270.00     90.00
300.00     60.00
330.00     30.00

以上,是在 (0, 360) 度范围内以逆时针方向测量t的角度 from 。是从到顺时针方向测量的角度,范围为 (-90, 90) 度。vector1vector2anglevector1vector2


推荐阅读