主题: Python使用指南针传感器输入:卡住计算
我拿着一个名为“开始”的指南针读数,旋转360度,读数为“结束”。我想知道开始和结束之间的增量。不是转了多少度,而是终点和起点有多大的不同。
degrees_start = 0
degrees_end = 359
#degrees_diff = degrees_end - degrees_start
degrees_diff = (degrees_start-degrees_end) % 360
print(degrees_diff)
'''
test set
degrees_start, degrees_end, deg_diff(expected), deg_diff(observed)
10, 20, +10, +10
20, 10, -10, -10
350, 10, +20, -340
10, 350, -20, +340
0, 359, -1, +359
359, 0, +1, -359
'''算法非常简单: end - start =delta.
但是我被困在359和1的边界上。例如,开始10,结束350。我尝试过很多算术组合,但都没有想出一个总是正确的公式。
有什么建议吗?谢谢。
下面是一些答案的测试:
# test 10,350 -> correct answer -> -20 i.e. 20 deg short of full circle
#degrees_diff = degrees_end - degrees_start # test 10,350 -> 340
#degrees_diff = (degrees_start-degrees_end) % 360 # test 10,350 -> 20
#degrees_diff = (degrees_end - degrees_start) % 360 # test 10,350 -> 340发布于 2020-12-12 06:13:20
必须使用模运算符(Python中的%)。算法变成了delta = (end - start) % 360。
在Python中,保证结果在半开区间[0,360]内。如果你喜欢[-180,180),你可以使用:
delta = ((180 + end - start) / 360) - 180发布于 2020-12-12 07:55:56
答案取决于旋转的方向。如果你总是想要结束和开始之间的最短角度,那么你必须计算两个方向并进行比较。
此外,有两种方式来考虑方向:(1)时钟或指南针角度上的秒针的方向,其中零落在+y轴上,90度落在+x轴上。增加的角度是逆时针方向(2)传统的数学定义是0度落在+x轴上,增加到+90度是+y轴,依此类推。
我将使用第一个定义/约定。
degrees_start = 10
degrees_end = 350
# conventions: clockwise (cw) rotation angles are always increasing
# until you cross from 359 to 0. also, delta angles for cw are always positive
if degrees_end > degrees_start:
# simple calculation for cw, we didn't cross 0
delta_cw = degrees_end - degrees_start
# fancier calculation for ccw. we crossed zero
delta_ccw = -(degrees_start + (360 - degrees_end))
else:
# fancy calculation for cw
delta_cw = degrees_end + (360 - degrees_start)
# easy calculation for ccw
delta_cw = degrees_end - degrees_start
print('delta_cw: +', delta_cw)
print('delta_ccw: ', delta_ccw)
if delta_cw < abs(delta_ccw):
print('shortest move: +', delta_cw)
else:
print('shortest move: ', delta_ccw)它给出输出:
delta_cw: + 340
delta_ccw: -20
shortest move: -20发布于 2020-12-19 05:49:58
我想这可能就是你要找的。
def degrees_diff(start, end):
if (start + end) >= 360:
ccw = -((start-end) % 360)
return print('CCW is', ccw, 'CW is', (ccw + 360))
else:
cw = -(start - end) % 360
return print('CW is', cw, 'CCW is', (cw - 360))
degrees_diff(350,10)这将为您提供:
CCW is -20 CW is 340https://stackoverflow.com/questions/65259241
复制相似问题