方法:
public static int[] FindIntersectionPoint(int[] p0, int[] p1, int[] p2, int[] p3) {
//line 1 equation
double m1 = (double) (Math.abs(p0[1] - p1[1])) / (double) (Math.abs(p0[0] - p1[0])); //slope
double b1 = p0[1] - (m1 * p0[0]); //y axis intercept
DC.drawLine(p0[0], p0[1], p1[0], p1[1]);
//line 2 equation
double m2 = (double) (Math.abs(p2[1] - p3[1])) / (double) (Math.abs(p2[0] - p3[0])); //slope
double b2 = p2[1] - (m2 * p2[0]); //y axis intercept
DC.drawLine(p2[0], p2[1], p3[0], p3[1]);
//Intersection points
double intersectX = (double)(b2 - b1) / (double)(m1 - m2);
double intersectY = 0;
System.out.println(intersectX); //is -18.181818181818205 which is way off
return new int[] {(int)intersectX, (int)intersectY};
}
方法调用:
int point[] = FindIntersectionPoint(new int[]{200, 100}, new int[]{300, 400}, new int[]{500, 50}, new int[]{200, 400});
我已经检查过,m1、m2、b1、b2 变量均已正确计算,并且 xIntercept 的公式:(b2 - b1)/(m1 - m2) 在纸上有效,但程序计算出 -18.181818181818205,这绝对不是答案。
最佳答案
可能的错误可能在这一行:
double b1 = p0[1] - (m1 * p0[0]); //y axis intercept
您正在将 int
上的操作保存为 double
,其中小数位始终为 0。您确定此计算结果正确吗?
在除法之前,将至少一个 int
转换为 double
。
关于java - 努力使用 y = mx + b 形式的两条线找到交点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34803994/