简体   繁体   中英

Struggling to find point of intersection using two lines in y = mx + b form

The method:

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

Method call:

int point[] = FindIntersectionPoint(new int[]{200, 100}, new int[]{300, 400}, new int[]{500, 50}, new int[]{200, 400});

I've checked and the m1, m2, b1, b2 variables are all calculated correctly and the formula for the xIntercept: (b2 - b1) / (m1 - m2) worked on paper but the program calculates -18.181818181818205 which is definitely not the answer.

Here is a visualization of whats going on: 在此处输入图片说明

Possible bug could be in this line:

double b1 = p0[1] - (m1 * p0[0]); //y axis intercept

You are saving operation on int to double , where the decimal digits will be always 0. You are sure, that this calculation is good?

Cast at least one of the ints to double before dividing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM