tha*_*ees 4 computational-geometry python-3.x
我想在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)
Run Code Online (Sandbox Code Playgroud)
向量几何提供(至少)两个有用的公式来计算两个向量之间的角度:
在哪里a · b可以使用计算
在哪里
由于我们的向量是二维的,我们可以取a3和b3(z 轴方向的分量)等于 0。这进一步简化了公式:
|a x b| = |a1 * b2 - a2 * b1| = |a| * |b| * sin(?)
Run Code Online (Sandbox Code Playgroud)
该?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]))
Run Code Online (Sandbox Code Playgroud)
印刷
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
Run Code Online (Sandbox Code Playgroud)
以上,t是从角vector1到vector2在范围(0,360)度的反时针方向测量的。angle是从vector1到vector2顺时针方向测量的角度,范围为 (-90, 90) 度。
| 归档时间: |
|
| 查看次数: |
5029 次 |
| 最近记录: |