Java找到两条线的交点 [英] Java find intersection of two lines

查看:934
本文介绍了Java找到两条线的交点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我有一个类Line,它具有两个变量:mb,因此该行遵循公式mx + b.我有两条这样的台词.如何找到两条线的交点的xy坐标? (假设坡度不同)

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)

这里是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

要找到x-axis的交点,请执行以下操作:

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)

要查找y,请使用函数表达式,并将x替换为其值(b2-b1) / (m1-m2).

To find y, you use of the function expressions and replace x for its value (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);
}

这篇关于Java找到两条线的交点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆