为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕容森 2024-01-15 17:12:52
[1,0]我有一个函数可以找到单位圆向量和单位圆上的向量之间的角度。import numpy as npdef 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.0print(angle(np.array([-4,2])))63.43 # This value should be 150print(angle(np.array([-1,0])))90.0 # This value should be 180print(angle(np.array([0,-1])))360.0 # This value should be 270如何确定输入a始终是二维向量?如何更改代码以使 x 轴下方的向量(即负 y 值)显示正确的值?
查看完整描述

3 回答

?
慕标琳琳

TA贡献1830条经验 获得超9个赞

你的 x 向量错了。它应该是

b = [1,0]

假设第一个坐标是 x 轴,第二个坐标是 y 轴。如果输入正确的 b 向量,所有计算都会按预期进行。


查看完整回答
反对 回复 2024-01-15
?
森栏

TA贡献1810条经验 获得超5个赞

定义需要输入的函数的一种方法是将两者保留为单独的参数(这也修复了一些错误并简化了获取角度值的逻辑):


def angle(x, y):

    

    rad = np.arctan2(y, x)

    degrees = np.int(rad*180/np.pi)

    if degrees < 0:

        degrees = 360 + degrees

    return degrees

顺便说一句,atan2输入顺序y, x很容易混淆。单独指定它们的一个优点是可以帮助避免这种情况。如果您想将输入保留为数组,类似这样的内容可以帮助您验证长度:


def angle(a):

    

    if len(a) != 2:

        raise IndexError("vector a expected to be length 2")        

    x = a[0]

    y = a[1]

    rad = np.arctan2(y, x)

    degrees = np.int(rad*180/np.pi)

    if degrees < 0:

        degrees = 360 + degrees

    return degrees


查看完整回答
反对 回复 2024-01-15
?
偶然的你

TA贡献1841条经验 获得超3个赞

我的坏处只是注意到它实际上是 numpy 数组,在这种情况下:if isinstance(x, np.ndarray) and x.shape[0] == 2

来自评论:x.ndim == 2听起来更好。


查看完整回答
反对 回复 2024-01-15
  • 3 回答
  • 0 关注
  • 36 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信