gpt4 book ai didi

Java找到两条线的交点

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:54:40 26 4
gpt4 key购买 nike

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

这是类行:

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

最佳答案

假设您有这两个功能:

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

要找到 x 轴 的交点,我们这样做:

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)

所以:

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找到两条线的交点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31506740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com