计算两条线之间的角度而不必计算斜率?(爪哇)

2022-09-01 07:04:55

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

如何计算这两条线之间形成的角度,而不必计算斜率?我目前遇到的问题是,有时我有水平线(沿x轴的线),并且以下公式失败(除以零异常):

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

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

这是我的代码片段:

// 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;
}

谢谢。


答案 1

该功能减轻了处理.atan2atan

它被声明为矩形坐标并将其转换为与极坐标的角度double atan2(double y, double x)(x,y)theta(r,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());
    return angle1-angle2;
}

答案 2

在这种情况下,点积可能更有用。在这里,您可以找到一个Java的几何包,它提供了一些有用的帮助程序。以下是他们用于确定两个3D点之间角度的计算。希望它能帮助你开始:

public static double computeAngle (double[] p0, double[] p1, double[] p2)
{
  double[] v0 = Geometry.createVector (p0, p1);
  double[] v1 = Geometry.createVector (p0, p2);

  double dotProduct = Geometry.computeDotProduct (v0, v1);

  double length1 = Geometry.length (v0);
  double length2 = Geometry.length (v1);

  double denominator = length1 * length2;

  double product = denominator != 0.0 ? dotProduct / denominator : 0.0;

  double angle = Math.acos (product);

  return angle;
}

祝你好运!