python-3.x - 如何在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)
解决方案
矢量几何提供了(至少)两个有用的公式来找到两个矢量之间的角度:
- 点积公式
可以使用哪里a · b
计算
- 和叉积公式:
在哪里
由于我们的向量是二维的,我们可以取a3
和b3
(z 轴方向的分量)等于 0。这进一步简化了公式:
|a x b| = |a1 * b2 - a2 * b1| = |a| * |b| * sin(ϴ)
s 是这ϴ
两个公式,然而,有不同的解释。使用点积,角度是两个向量之间的夹角——因此总是一个介于 0 和 pi 之间的值。
使用叉积,角度从到 到逆时针方向测量。由于您正在寻找以顺时针方向测量的角度,因此您只需反转使用叉积公式获得的角度的符号。a
b
在 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) 度。vector1
vector2
angle
vector1
vector2
推荐阅读
- c# - 使用别名简化 LINQ 子查询
- google-apps-script - 如何使 onEdit(e) 在受保护的工作表上运行?Google Apps 脚本
- c# - 如何通过无头浏览器将页面顶部渲染为 png?
- python - python读写与shutil复制
- python-3.x - Django 如何动态改变布尔值?
- r - 从R中的复杂标题中提取年份
- embedded-linux - yocto 在自定义发行版中添加包 /packages-groups
- python - 如果随机写入,我该如何安排这个 3D 数组数据
- mongodb - 一对一填充猫鼬不工作
- javascript - 我可以动态调用导入的文件名吗?