首页 > 解决方案 > 寻找方向角θ值

问题描述

我有两个角度(以度为单位,限制为0-359),我想在所需数量最小的方向上找到两个角度之间的方向差异。

例如:

  1. 0, 359将是-1(左1),而不是+359
  2. 180, 2将是-178(左178),而不是+182

我找到了一些代码,可以让我在没有方向的情况下找到差异。我应该如何修改它以定向工作?

180 - abs(abs(old - new) - 180)

标签: pythonmathangle

解决方案


我首先开始行人方式并比较了两种可能的旋转方式:

def nearest_signed(old, new):
    angles = ((new - old)%360, (new - old)%360 - 360)
    return min(angles, key=abs)

我们检查模 360 角,以及它在另一个方向上的补码。

它似乎工作:

>>> nearest_signed(0, 359)
-1
>>> nearest_signed(359, 0)
1
>>> nearest_signed(180, 2)
-178
>>> nearest_signed(2, 180)
178

现在,我想看看它是如何表现的,所以我绘制了每个角度组合的图:

import numpy as np
matplotlib.pyplot as plt                   

news,olds = np.ogrid[:360, :360]
rights = (news - olds) % 360
lefts = rights - 360
take_rights = abs(rights) < abs(lefts)
nearest_signed = np.where(take_rights, rights, lefts)

fig,ax = plt.subplots()
cf = ax.contourf(news.ravel(), olds.ravel(), nearest_signed, cmap='viridis', levels=np.linspace(-180, 180, 100), vmin=-180, vmax=180)
ax.set_xlabel('new angle')
ax.set_ylabel('old angle')
cb = plt.colorbar(cf, boundaries=(-180, 180))
plt.show()

漂亮的绘制结果

现在这很明显,一个简单的角度差模应该起作用。果然:

>>> np.array_equal((news - olds + 180) % 360 - 180, nearest_signed)
True

这意味着您正在寻找的公式是

(new - old + 180) % 360 - 180

在您的约定中给予或采取符号差异。如果你反过来计算旋转符号,只需切换两个角度:

(old - new + 180) % 360 - 180

推荐阅读