# 计算两条线之间的angular度而不必计算斜率？ （JAVA）

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

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

`atan2`函数减轻了处理`atan`的痛苦。

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

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

``` dx1 = x2-x1;
dy1 = y2-y1;
dx2 = x4-x3;
dy2 = y4-y3;

d = dx1 * dx2 + dy1 * dy2;  // 2个向量的点积
l2 =（dx1 * dx1 + dy1 * dy1）*（dx2 * dx2 + dy2 * dy2）//平方长度乘积

angular度= acos（d / sqrt（l2））;
```

2个向量的点积等于两个向量长度的angular度时间的余弦。 这计算点积，除以vector的长度，并使用反余弦函数来恢复angular度。

` `/** * Calculate angle between two lines with two given points * * @param A1 First point first line * @param A2 Second point first line * @param B1 First point second line * @param B2 Second point second line * @return Angle between two lines in degrees */ public static float angleBetween2Lines(PointF A1, PointF A2, PointF B1, PointF B2) { float angle1 = (float) Math.atan2(A2.y - A1.y, A1.x - A2.x); float angle2 = (float) Math.atan2(B2.y - B1.y, B1.x - B2.x); float calculatedAngle = (float) Math.toDegrees(angle1 - angle2); if (calculatedAngle < 0) calculatedAngle += 360; return calculatedAngle; }` `

` `tan a = (slope1 - slope2) / (1 - slope1 * slope2)` `

` `double angle = Math.atan((slope1 - slope2) / (1 + slope1 * slope2));` `

` ` double slope1 = (line1.getY1() - line1.getY2()) / (line1.getX1() - line1.getX2()); double slope2 = (line2.getY1() - line2.getY2()) / (line2.getX1() - line2.getX2());` `

` `double angle; try { angle = Math.atan((slope1 - slope2) / (1 - (slope1 * slope2))); catch (DivideByZeroException dbze) { //Do something about it! }` `

…或者你可以检查你的除数是否从零开始， 然后再尝试手术。

` `if ((1 - (slope1 * slope2))==0) { return /*something meaningful to avoid the div by zero*/ } else { double angle = Math.atan((slope1 - slope2) / (1 - (slope1 * slope2))); return angle; }` `