0

给定一条由 (x1, y1) 和 (x2, y2) 定义的线段,找到线上 y = 某个值的位置。

我知道我可以获得直线方程,然后使用联立方程求解,但这是否可以使用 Line2D 或任何其他 Java 类?

任何建议或意见将不胜感激!

开尔文。

4

2 回答 2

0

对于这样的任务,我建议使用 apache commons math。

http://commons.apache.org/math/apidocs/index.html

有多种方法可以做到这一点。一种方法是

org.apache.commons.math3.geometry.euclidean.twod.Line lineOne = new org.apache.commons.math3.geometry.euclidean.twod.Line(p,angle);

org.apache.commons.math3.geometry.euclidean.twod.Line horizontalLine = new org.apache.commons.math3.geometry.euclidean.twod.Line(new vector2d(0,yToSolveFor),pi/2);

Vector2D intersection=lineOne.intersect(horizontalLine);
intersection.getX(); // The answer
于 2012-08-20T17:22:59.077 回答
0

我认为 Java API 中没有任何东西可以实际计算交集。我认为最接近的方法是使用 Line2D 来测试线段是否与(垂直)线y = k相交以获得某个常数k

Line2D line = new Line2D.Double(x1, y1, x2, y2);
if (line.intersectsLine(Double.MIN_VALUE, k, Double.MAX_VALUE, k)) {
    double x = (x2 - x1) * (k - y1) / (y2 - y1);
    // intersection is at (x, k)
} else {
    // intersection is outside extend of the line segment
}

但是,只检查y1 != y2,计算交点,然后检查x坐标是否在 [x1, x2] 范围内可能会更有效。

于 2012-08-20T17:20:05.260 回答