Java find intersection of two lines
In Java, I have a class Line
that has two variables: m
and b
, so the string follows the formula mx + b
. I have two such lines. How can I find the coordinates x
and y
intersections of 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;
}
}
source to share
Let's assume you have these 2 functions:
y = m1*x + b1
y = m2*x + b2
To find the intersection point x-axis
, 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 function expressions and replace x
with its value (b2-b1) / (m1-m2)
.
So:
y = m1 * [(b2-b1) / (m1-m2)] + b1
Do you (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);
}
source to share
What I got. Couldn't find any exceptions that don't work:
public static Point calculateInterceptionPoint(Point s1, Point d1, Point s2, Point d2) {
double sNumerator = s1.y * d1.x + s2.x * d1.y - s1.x * d1.y - s2.y * d1.x;
double sDenominator = d2.y * d1.x - d2.x * d1.y;
// parallel ... 0 or infinite points, or one of the vectors is 0|0
if (sDenominator == 0) {
return null;
}
double s = sNumerator / sDenominator;
double t;
if (d1.x != 0) {
t = (s2.x + s * d2.x - s1.x) / d1.x;
} else {
t = (s2.y + s * d2.y - s1.y) / d1.y;
}
Point i1 = new Point(s1.x + t * d1.x, s1.y + t * d1.y);
return i1;
}
public static void main(String[] args) {
System.out.println(calculateInterceptionPoint(new Point(3, 5), new Point(0, 2), new Point(1, 2), new Point(4, 0)));
System.out.println(calculateInterceptionPoint(new Point(3, 5), new Point(0, 2), new Point(1, 2), new Point(0, 2)));
System.out.println(calculateInterceptionPoint(new Point(0, 0), new Point(0, 2), new Point(0, 0), new Point(2, 0)));
System.out.println(calculateInterceptionPoint(new Point(0, 0), new Point(0, 2), new Point(0, 0), new Point(0, 2)));
System.out.println(calculateInterceptionPoint(new Point(0, 0), new Point(0, 0), new Point(0, 0), new Point(0, 0)));
}
source to share