我意识到这可能是有史以来最菜鸟的问题,但我的思绪完全卡住了。
我有两个角度,代表两个单位的罗盘方向,可以说
单位1:90.0
单位2:45.0
如果它们相差超过 20 度,则unit2需要采用unit1的方向,+/-20度,这样
单位1:90.0
单位2:70.0
我可以使用以下方法计算出这两个(有符号)之间的度数差异
angle = 180 - abs(abs(unit1 - unit2) - 180)
Run Code Online (Sandbox Code Playgroud)
但我需要知道是调整+20还是-20。
例如,对于这个集合:
单位1:270
单位2:350
单位 2 需要变为 290(向单位 1 添加 20 度)
我很确定可能有一个 python 函数可以为我完成此操作,但我完全陷入困境,记不起 20 年前学过的任何数学知识。
我完全希望有人能愚弄我,但无论如何我都会很感激。
小智 5
我明白你为什么陷入困境。另一个解决方案并没有真正解决像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
Run Code Online (Sandbox Code Playgroud)
正如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)
Run Code Online (Sandbox Code Playgroud)