迭代到圆上的特定角度
Iterating toward a specific angle on a circle
我正在建造一个带有车载指南针的机器人车辆。从车辆的当前方向开始,我想使用指南针将它向任一方向旋转 90 度。
我假设最好的方法是在 "while" 循环中以增量方式旋转车辆,并在每次旋转增量后测试它是否移动了 90 度。
然而,虽然处理两个正点之间的转换很简单,但处理涉及从 0 到 360 的转换就变得具有挑战性。
换句话说,这段左旋代码失败的原因很明显:
let startingPoint = 30 // in degrees
let endPoint = startingPoint - 90
while currentPoint > endPoint {
rotateLeft()
}
是否有一个方程式可以在跨越 360/0 边界时进行这种比较?
您可以检查差异,而不是绝对值。
要确定差异是否超出 90 度范围,您可以使用计算任意角度的公式,包括通过 0 的过渡(不要忘记角度应以弧度为单位)
if Cos(startingangle - currentangle) <=0 then
absolute difference is equal or more than Pi/2 (90 degrees)
此处粗箭头显示(忽略轴标签或将其除以 4)Cos
零起始角与 +-30
度角的差异(适用于任何起始角)
Python 演示:
import math
def AngleInRange(value, central, arange):
value = math.radians(value)
central = math.radians(central)
arange = math.radians(arange)
return (math.cos(value - central) >= math.cos(arange))
for a in range (100, 220, 15): #through 180
print(a, AngleInRange(a, 150, 45))
for a in range (-40, 40, 10): #through 0
print(a, AngleInRange(a, -10, 20))
100 False
115 True
130 True
145 True
160 True
175 True
190 True
205 False
-40 False
-30 True
-20 True
-10 True
0 True
10 True
20 False
30 False
我正在建造一个带有车载指南针的机器人车辆。从车辆的当前方向开始,我想使用指南针将它向任一方向旋转 90 度。
我假设最好的方法是在 "while" 循环中以增量方式旋转车辆,并在每次旋转增量后测试它是否移动了 90 度。
然而,虽然处理两个正点之间的转换很简单,但处理涉及从 0 到 360 的转换就变得具有挑战性。
换句话说,这段左旋代码失败的原因很明显:
let startingPoint = 30 // in degrees
let endPoint = startingPoint - 90
while currentPoint > endPoint {
rotateLeft()
}
是否有一个方程式可以在跨越 360/0 边界时进行这种比较?
您可以检查差异,而不是绝对值。
要确定差异是否超出 90 度范围,您可以使用计算任意角度的公式,包括通过 0 的过渡(不要忘记角度应以弧度为单位)
if Cos(startingangle - currentangle) <=0 then
absolute difference is equal or more than Pi/2 (90 degrees)
此处粗箭头显示(忽略轴标签或将其除以 4)Cos
零起始角与 +-30
度角的差异(适用于任何起始角)
Python 演示:
import math
def AngleInRange(value, central, arange):
value = math.radians(value)
central = math.radians(central)
arange = math.radians(arange)
return (math.cos(value - central) >= math.cos(arange))
for a in range (100, 220, 15): #through 180
print(a, AngleInRange(a, 150, 45))
for a in range (-40, 40, 10): #through 0
print(a, AngleInRange(a, -10, 20))
100 False
115 True
130 True
145 True
160 True
175 True
190 True
205 False
-40 False
-30 True
-20 True
-10 True
0 True
10 True
20 False
30 False