python - 寻找方向角θ值
问题描述
我有两个角度(以度为单位,限制为0-359
),我想在所需数量最小的方向上找到两个角度之间的方向差异。
例如:
0, 359
将是-1
(左1
),而不是+359
180, 2
将是-178
(左178
),而不是+182
我找到了一些代码,可以让我在没有方向的情况下找到差异。我应该如何修改它以定向工作?
180 - abs(abs(old - new) - 180)
解决方案
我首先开始行人方式并比较了两种可能的旋转方式:
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
推荐阅读
- javascript - 关闭弹出窗口后如何仅在父页面中刷新特定下拉列表
- dart - 如何在 Flutter 中测试/调试摇树?
- json - @RequestParam 从邮递员的表单数据中传递 Spring Boot 中的 pojo 字段
- c# - 使用 C# 访问 Google 电子表格(无 API)
- git - 如何减少 git grep 的输出
- r - 如何使用带条件的 rowSums 返回二进制值?
- .htaccess - htaccess 重定向无序链接
- python - 将列表中的元素相乘的Python问题
- powershell - 在 Azure DevOps 发布管道中从 PowerShell 执行 SQLCMD.exe
- tensorflow - 无法在 Google Cloud ML 中进行训练