计算两条线之间的角度而不必计算斜率? (JAVA) [英] Calculating the angle between two lines without having to calculate the slope? (Java)

查看:1071
本文介绍了计算两条线之间的角度而不必计算斜率? (JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两条线:L1和L2。我想计算两条线之间的角度。 L1具有以下几点: {(x1,y1),(x2,y2)} ,y4)} 。



如何计算这两条线之间形成的角度,而无需计算斜率?我现在遇到的问题是,有时我会有水平线(沿着x轴的线),下面的公式失败(除以零例外):

  arctan((m1  -  m2)/(1-(m1 * m2)))

其中 m1 m2 分别是第1行和第2行的斜率。是否有公式/算法可以计算两条线之间的角度而不会得到零除异常?任何帮助将不胜感激。



这是我的代码片段:

  //计算两行之间形成的角度
public static double angleBetween2Lines(Line2D line1,Line2D line2)
{
double slope1 = line1.getY1() - line1.getY2()/ line1.getX1() - line1.getX2();
double slope2 = line2.getY1() - line2.getY2()/ line2.getX1() - line2.getX2();
double angle = Math.atan((slope1 - slope2)/(1-(slope1 * slope2)));
回报角度;
}

谢谢。 b $ b

atan2 函数缓解了处理 atan 的痛苦。



它被声明为 double atan2(double y,double x)并转换直角坐标( x,y)与极坐标(r,theta)的角度 theta

所以我会将你的代码重写为

  public static double angleBetween2Lines(Line2D line1,Line2D line2)
{
double angle1 = Math.atan2(line1.getY1() - line1.getY2(),
line1.getX1() - line1.getX2( ));
double angle2 = Math.atan2(line2.getY1() - line2.getY2(),
line2.getX1() - line2.getX2());
返回angle1-angle2;
}


I have two Lines: L1 and L2. I want to calculate the angle between the two lines. L1 has points: {(x1, y1), (x2, y2)} and L2 has points: {(x3, y3), (x4, y4)}.

How can I calculate the angle formed between these two lines, without having to calculate the slopes? The problem I am currently having is that sometimes I have horizontal lines (lines along the x-axis) and the following formula fails (divide by zero exception):

arctan((m1 - m2) / (1 - (m1 * m2)))

where m1 and m2 are the slopes of line 1 and line 2 respectively. Is there a formula/algorithm that can calculate the angles between the two lines without ever getting divide-by-zero exceptions? Any help would be highly appreciated.

This is my code snippet:

// Calculates the angle formed between two lines
public static double angleBetween2Lines(Line2D line1, Line2D line2)
{
    double slope1 = line1.getY1() - line1.getY2() / line1.getX1() - line1.getX2();
    double slope2 = line2.getY1() - line2.getY2() / line2.getX1() - line2.getX2();
    double angle = Math.atan((slope1 - slope2) / (1 - (slope1 * slope2)));
    return angle;
}

Thanks.

解决方案

The atan2 function eases the pain of dealing with atan.

It is declared as double atan2(double y, double x) and converts rectangular coordinates (x,y) to the angle theta from the polar coordinates (r,theta)

So I'd rewrite your code as

public static double angleBetween2Lines(Line2D line1, Line2D line2)
{
    double angle1 = Math.atan2(line1.getY1() - line1.getY2(),
                               line1.getX1() - line1.getX2());
    double angle2 = Math.atan2(line2.getY1() - line2.getY2(),
                               line2.getX1() - line2.getX2());
    return angle1-angle2;
}

这篇关于计算两条线之间的角度而不必计算斜率? (JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆