直线交点 java,Java找到两条线的交点

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;

}

}

解决方案

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值