简体   繁体   English

计算两个坐标之间的角度? Python

[英]Calculate angle between two coordinates? Python

Say you have two coordinates within a range of 0.0 till 1.0.假设您在 0.0 到 1.0 的范围内有两个坐标。 A: (0.12, 0.75) B: (0.43, 0.97) And you want to walk from point A to point B. How would you calculate the angle in python.Where north is 0 and south is 180. A: (0.12, 0.75) B: (0.43, 0.97) 你想从 A 点走到 B 点。你将如何在 python 中计算角度。北为 0,南为 180。

if you want to get it from North then here you go:如果你想从北方得到它,那么你去:

def get_angle(x1,y1,x2,y2):
    return math.degrees(math.atan2(y2-y1, x2-x1))

This works because这有效,因为

tan(x) = Opposite/Adjacent;
Opposite/Adjacent = (x2-x1)/(y2-y1);
x=atan(x2-x1, y2-y1)

With atan being the inverse of tan . atantan的倒数。 And to not just get the orientation, but true direction, we use the atan2 function instead, as that can get use angels from -pi (-180) to +pi (180), whereas atan can only yield values between -pi/2 (-90) and pi/2 (90).为了不只是获得方向,而是真正的方向,我们使用atan2函数,因为它可以获得从 -pi (-180) 到 +pi (180) 的使用角度,而atan只能产生 -pi/2 之间的值(-90) 和 pi/2 (90)。

One gotcha: the argument order for atan2 is the y difference first , so it's atan2(dy, dx) , not atan2(dx, dy) .一个问题: atan2的参数顺序是 y 差异first ,所以它是atan2(dy, dx)而不是atan2(dx, dy)

I would calculate the diference in x and the diference in y and use the function math.atan2(y/x) from the math module.我将计算 x 的差异和 y 的差异,并使用math模块中的函数math.atan2(y/x) Then it's just a matter of converting from radians to degrees and add 90º.然后只需将弧度转换为度数并加上 90º。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM