Search code examples
javamathgeometrylinepoint

Java find intersection of two lines


In Java, I have a class Line that has two variables : m and b, such that the line follows the formula mx + b. I have two such lines. How am I to find the x and y coordinates of the intersection of the two lines? (Assuming the slopes are different)

Here is class Line:

import java.awt.Graphics;
import java.awt.Point;

public final class Line {
    public final double m, b;

    public Line(double m, double b) {
        this.m = m;
        this.b = b;
    }

    public Point intersect(Line line) {
        double x = (this.b - line.b) / (this.m - line.m);
        double y = this.m * x + this.b;
        return new Point((int) x, (int) y);
    }

    public void paint(Graphics g, int startx, int endx, int width, int height) {
        startx -= width / 2;
        endx -= width / 2;
        int starty = this.get(startx);
        int endy = this.get(endx);
        Point points = Format.format(new Point(startx, starty), width, height);
        Point pointe = Format.format(new Point(endx, endy), width, height);
        g.drawLine(points.x, points.y, pointe.x, pointe.y);
    }

    public int get(int x) {
        return (int) (this.m * x + this.b);
    }

    public double get(double x) {
        return this.m * x + this.b;
    }
}

Solution

  • Lets assume you have these 2 functions:

    y = m1*x + b1    
    y = m2*x + b2
    

    To find the intersection point of the x-axis we do:

    m1*x+b1 = m2*x+b2    
    m1*x-m2*x = b2 - b2    
    x(m1-m2) = (b2-b1)    
    x = (b2-b1) / (m1-m2)
    

    To find y, you use of the function expressions and replace x for its value (b2-b1) / (m1-m2).

    So:

    y = m1 * [(b2-b1) / (m1-m2)] + b1
    

    You have (this.b - line.b), change to (line.b - this.b).

    public Point intersect(Line line) {
        double x = (line.b - this.b) / (this.m - line.m);
        double y = this.m * x + this.b;
    
        return new Point((int) x, (int) y);
    }