在编程语言(Python, c#等),我需要确定如何计算一条线和水平轴之间的角度?
我认为图片最能描述我想要的东西:
已知(P1x,P1y)和(P2x,P2y)计算这个角的最佳方法是什么?原点在上左叶,只使用正象限。
在编程语言(Python, c#等),我需要确定如何计算一条线和水平轴之间的角度?
我认为图片最能描述我想要的东西:
已知(P1x,P1y)和(P2x,P2y)计算这个角的最佳方法是什么?原点在上左叶,只使用正象限。
当前回答
matlab函数:
function [lineAngle] = getLineAngle(x1, y1, x2, y2)
deltaY = y2 - y1;
deltaX = x2 - x1;
lineAngle = rad2deg(atan2(deltaY, deltaX));
if deltaY < 0
lineAngle = lineAngle + 360;
end
end
其他回答
deltaY = Math.Abs(P2.y - P1.y);
deltaX = Math.Abs(P2.x - P1.x);
angleInDegrees = Math.atan2(deltaY, deltaX) * 180 / PI
if(p2.y > p1.y) // Second point is lower than first, angle goes down (180-360)
{
if(p2.x < p1.x)//Second point is to the left of first (180-270)
angleInDegrees += 180;
else //(270-360)
angleInDegrees += 270;
}
else if (p2.x < p1.x) //Second point is top left of first (90-180)
angleInDegrees += 90;
matlab函数:
function [lineAngle] = getLineAngle(x1, y1, x2, y2)
deltaY = y2 - y1;
deltaX = x2 - x1;
lineAngle = rad2deg(atan2(deltaY, deltaX));
if deltaY < 0
lineAngle = lineAngle + 360;
end
end
考虑到这个确切的问题,将我们置于一个“特殊”坐标系中,其中正轴意味着向下移动(如屏幕或界面视图),你需要调整这个函数,并负Y坐标:
Swift 2.0中的示例
func angle_between_two_points(pa:CGPoint,pb:CGPoint)->Double{
let deltaY:Double = (Double(-pb.y) - Double(-pa.y))
let deltaX:Double = (Double(pb.x) - Double(pa.x))
var a = atan2(deltaY,deltaX)
while a < 0.0 {
a = a + M_PI*2
}
return a
}
这个函数给出了问题的正确答案。答案是以弧度为单位,所以用角度来表示角度的用法是:
let p1 = CGPoint(x: 1.5, y: 2) //estimated coords of p1 in question
let p2 = CGPoint(x: 2, y : 3) //estimated coords of p2 in question
print(angle_between_two_points(p1, pb: p2) / (M_PI/180))
//returns 296.56
根据参考“彼得O”..这是java版本
private static final float angleBetweenPoints(PointF a, PointF b) {
float deltaY = b.y - a.y;
float deltaX = b.x - a.x;
return (float) (Math.atan2(deltaY, deltaX)); }
我已经在Python中找到了一个很好的解决方案!
from math import atan2,degrees
def GetAngleOfLineBetweenTwoPoints(p1, p2):
return degrees(atan2(p2 - p1, 1))
print GetAngleOfLineBetweenTwoPoints(1,3)