2015-07-19 76 views
3

在Java中,我有一个类Line,它有两个变量:mb,使得该行遵循公式mx + b。我有两条这样的路线。我如何找到两条线的交点坐标为xy? (假设斜率不同)Java查找两条线的交点

这里是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; 
    } 
} 
+1

你已经得到了代码:它不工作?另外,如果您试图解决这些问题,请考虑用2 y = mx + b行的笔和纸做什么。等于并求解x为x定义一个通用解,然后使用任一线方程求解y。将公式转换为代码 –

+0

您是否无法计算出公式?这是[math.se]。或者,您是否难以将您已知的公式转换为代码?这不应该太难,而且已经完成了。 – Teepeemm

回答

7

让我们假设你有这两个功能:

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

要找到x-axis的交汇点上,我们做的事:

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

要找到y,可以使用函数exp并将x替换为其值(b2-b1)/(m1-m2)

所以:

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

你有(this.b - line.b),改变(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); 
} 
+0

完美!我认为这只是一个小错误,因为我的数字很小。非常感谢! – HyperNeutrino

+2

请注意,此解决方案不适用于垂直线和平行线。在'm-line.m = 0'的情况下,它是未定义的。 –