求 x 轴与单位圆上的向量之间的角度

[1,0]我有一个函数可以找到单位圆向量和单位圆上的向量之间的角度。


import numpy as np


def angle(a):

    b = [0,1]

    if a[1] >= 0:

        return round(np.degrees(np.arccos(np.dot(a, b)/ (np.linalg.norm(a) * np.linalg.norm(b)))), 2)

    else:

        return 180 + round(np.degrees(np.arccos(np.dot(a, b)/ (np.linalg.norm(a) * np.linalg.norm(b)))), 2)


print(angle(np.array([1,0])))

90.0


print(angle(np.array([-4,2])))

63.43 # This value should be 150


print(angle(np.array([-1,0])))

90.0 # This value should be 180


print(angle(np.array([0,-1])))

360.0 # This value should be 270

如何确定输入a始终是二维向量?

如何更改代码以使 x 轴下方的向量(即负 y 值)显示正确的值?


慕容森
浏览 39回答 3
3回答

慕标琳琳

你的 x 向量错了。它应该是b = [1,0]假设第一个坐标是 x 轴,第二个坐标是 y 轴。如果输入正确的 b 向量,所有计算都会按预期进行。

森栏

定义需要输入的函数的一种方法是将两者保留为单独的参数(这也修复了一些错误并简化了获取角度值的逻辑):def angle(x, y):&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; rad = np.arctan2(y, x)&nbsp; &nbsp; degrees = np.int(rad*180/np.pi)&nbsp; &nbsp; if degrees < 0:&nbsp; &nbsp; &nbsp; &nbsp; degrees = 360 + degrees&nbsp; &nbsp; return degrees顺便说一句,atan2输入顺序y, x很容易混淆。单独指定它们的一个优点是可以帮助避免这种情况。如果您想将输入保留为数组,类似这样的内容可以帮助您验证长度:def angle(a):&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if len(a) != 2:&nbsp; &nbsp; &nbsp; &nbsp; raise IndexError("vector a expected to be length 2")&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; x = a[0]&nbsp; &nbsp; y = a[1]&nbsp; &nbsp; rad = np.arctan2(y, x)&nbsp; &nbsp; degrees = np.int(rad*180/np.pi)&nbsp; &nbsp; if degrees < 0:&nbsp; &nbsp; &nbsp; &nbsp; degrees = 360 + degrees&nbsp; &nbsp; return degrees

偶然的你

我的坏处只是注意到它实际上是 numpy 数组,在这种情况下:if isinstance(x, np.ndarray) and x.shape[0] == 2来自评论:x.ndim == 2听起来更好。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python