我意识到这可能是有史以来最菜鸟的问题,但我的思绪完全卡住了。
我有两个角,代表两个单位的罗盘方向,比方说
单位 1:90.0
单元 2:45.0
如果它们相差超过 20 度,unit2 需要采用 unit1 的方向,+/-20 度,这样
unit1:90.0
unit2:70.0
我可以使用
计算出这两个(已签名)之间的度数差异angle = 180 - abs(abs(unit1 - unit2) - 180)
但我需要知道是调整 +20 还是 -20。
例如,对于这个集合:
单位 1:270
unit2:350
unit2需要变成290(unit1加20度)
我很确定可能有一个 python 函数可以为我做这件事,但我完全被困住了,不记得我 20 年前学过的任何数学。
我完全希望有人能取笑我,但无论如何我都会很感激。
请您参考如下方法:
我明白你为什么坚持这一点。另一个解决方案并没有真正解决 unit1 处于 30 度和 unit2 处于 340 度的情况,它会从 360 度旋转到 0 度。代码可以进行一些清理,但我希望这能有所帮助。
import math
# calculate and return the distance unit2
# needs to move to reach unit1
def get_distance(unit1, unit2):
phi = abs(unit2-unit1) % 360
sign = 1
# used to calculate sign
if not ((unit1-unit2 >= 0 and unit1-unit2 <= 180) or (
unit1-unit2 <= -180 and unit1-unit2 >= -360)):
sign = -1
if phi > 180:
result = 360-phi
else:
result = phi
return result*sign
# distance unit2 needs to move to reach unit1
print get_distance(90,45) # output 45
print get_distance(270, 350) # output -80
print get_distance(350, 30) # output -40 (unit2 moves -40 degrees)
print get_distance(30, 350) # output 40
unit1 = 30
unit2 = 350
# then calculate distance to move by taking 20 from distance
distance_to_move = (get_distance(unit1, unit2) - 20)
print (unit2 + distance_to_move)%360 # new position 10
正如 Tadhg 所指出的,我对它进行了一些改动,使其可以工作超过 360 度。 . 20 度的方差也没有那么硬编码。
import math
# calculate and return the distance unit2
# needs to move to reach unit1
def get_distance(unit1, unit2):
phi = (unit2-unit1) % 360
sign = -1
# used to calculate sign
if not ((phi >= 0 and phi <= 180) or (
phi <= -180 and phi >= -360)):
sign = 1
if phi > 180:
result = 360-phi
else:
result = phi
return (result*sign), sign
def get_sign(unit1, unit2):
phi = (unit2-unit1) % 360
sign = 1
if ((phi >= 0 and phi <= 180) or (
phi <= -180 and phi >= -360)):
sign = -1
return sign
def new_position(unit1, unit2, variance = 20):
distance_to_move, sign = get_distance(unit1, unit2)
variance*=sign
# %360 to keep it within the circle
return (unit2+distance_to_move-variance)%360
# distance unit2 needs to move to reach unit1
assert (get_distance(90,45) == (45, 1))
assert (get_distance(270, 350) == (-80, -1))
assert (get_distance(350, 30) == (-40, -1))
assert (get_distance(30, 350) == (40, 1))
assert (get_distance(50, 360*4) == (50, 1))
assert (get_distance(360*4, 50) == (-50, -1))
print "----------"
assert (new_position(90,45) == 70)
assert (new_position(270, 350) == 290)
assert (new_position(350, 30) == 10)
assert (new_position(30, 350) == 10)
assert (new_position(50, 360*4) == 30)
assert (new_position(360*4, 50) == 20)
