查找一个角度与另一个角度是否在 X 度范围内
我需要一种算法来确定一个角度与另一个角度的夹角是否在一定范围内。
我的第一个想法是 (ax < b) && (a+x > b)
,但当它必须处理从 -179 到 180 的角度时,它会失败。
在上图中,角度必须位于负边和正边之间的区域(绿色)。如何确定角度(红线)是否落在该区域内?
I need an algorithm to figure out if one angle is within a certain amount of degrees from another angle.
My first thought was (a-x < b) && (a+x > b)
, but it fails when it has to work with angles that wrap around from -179 to 180.
In the diagram above, the region (green) that the angle must be between wraps between the negative and positive sides. How can I determine whether the angle (the red line) falls inside this region?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试这个公式:
或者,在 PHP 中:
try this formula:
Or, in PHP:
正如马塞尔正确指出的那样,负数取模可能存在问题。另外,355度和5度有什么区别?计算结果可能为 350 度,但人们期望的可能是 10 度。我们做出以下假设:
0 <= diff <= 180
;2*PI
;-360 < x < 360
其中 x 是输入角度,输入:角度 a 和 b。所以算法很简单:
0 <= x
360;
第一步,要将角度转换为所需的范围,有两种可能性:
x >= 0
:Normal = x % 360x < 0
: 正常 = (-x / 360 + 1) * 360 + x第二个旨在消除负模运算解释差异上的任何歧义。举一个 x = -400 的例子:
那么
对于输入 10 和 -400,法向角度是 10 和 320。
现在我们计算它们之间的最短角度。作为健全性检查,这两个角度的总和必须为 360。在本例中,可能性为 50 和 310(画出来,您就会看到这一点)。要解决这些问题:
对于我们的示例:
您将注意到
normal1 + normal2 = 360
(如果您愿意,您甚至可以证明情况就是如此)。最后:
在我们的例子中是 50。
As Marcel rightly points out, modulo on negative numbers is potentially problematic. Also, what is the difference between 355 and 5 degrees? It might be worked out to be 350 degrees but 10 degrees is probably what people are expecting. We make the following assumptions:
0 <= diff <= 180
;2*PI
;-360 < x < 360
where x is an input angle andInputs: angles a and b. So the algorithm is simply:
0 <= x < 360
;For the first step, to convert the angle to the desired range, there are two possibilities:
x >= 0
: normal = x % 360x < 0
: normal = (-x / 360 + 1) * 360 + xThe second is designed to remove any ambiguity on the difference in interpretation of negative modulus operations. So to give a worked example for x = -400:
then
so for inputs 10 and -400 the normal angles are 10 and 320.
Now we calculate the shortest angle between them. As a sanity check, the sum of those two angles must be 360. In this case the possibilities are 50 and 310 (draw it and you'll see this). To work these out:
So for our example:
You'll note
normal1 + normal2 = 360
(and you can even prove this will be the case if you like).Lastly:
or 50 in our case.
您还可以使用点积:
You can also use a dot product:
对于半径为 1 的情况,直线端点之间的距离为 2sin((ab/2)。因此丢弃 2,因为您只对比较感兴趣,并将 sin(x/2) 与 sin((ab)/ 2). 三角函数负责所有的包装。
For a radius of 1, the distance between the line endpoints is 2sin((a-b/2). So throw away the 2 since you are only interested in a comparison, and compare sin(x/2) with sin((a-b)/2). The trig functions take care of all the wrapping.
C++实现:
c++ implementation: