我正在画一张画布上的大量相连边,它们都以某种方式排列,以便这些边的特定扩展总是与另一个扩展边相交。这个点在进一步计算中是必需的 - 它在画布上不相关。我的代码对于一般情况运行良好,但是如果边的相应扩展超出范围,则交点并不总是存在(但是,线不平行)- 至少不在此程序的范围内。有人有什么想法来提高此代码的精度吗?我实际上稍后会使用BigDecimals,但是对于绘图步骤,我最初认为使用double就足够了。
这个将边延伸到两侧:
这个函数找到两个集合的交集:
这个将边延伸到两侧:
public Line2D.Double ExteLine(Point2D p, Point2D q){
double slope, y3, y4;
slope = (q.getY() - p.getY())/(q.getX() - p.getX());
y3 = (slope * (100000 - p.getX())) + p.getY();
y4 = (slope * (-100000 - p.getX())) + p.getY();
Point2D out1 = new Point2D.Double(100000, y3);
Point2D out2 = new Point2D.Double(-100000, y4);
Line2D.Double line = new Line2D.Double(out1, out2);
return line; }
这个函数找到两个集合的交集:
public Point2D.Double getIntersectionPoint(Line2D.Double line1, Line2D.Double line2) {
if (! line1.intersectsLine(line2)) {
System.out.println("No intersection");
return null;}
double s1 = line1.getX1(),
sp2 = line1.getY1(),
rx = line1.getX2()-s1,
ry = line1.getY2()-sp2;
double qx = line2.getX1(),
qy = line2.getY1(),
sx = line2.getX2()-qx,
sy = line2.getY2()-qy;
double det = sx*ry - sy*rx;
if (det == 0) { System.out.println("Det = 0");
return null;}
else {
double z = (sx*(qy-sp2)+sy*(s1-qx))/det;
if (z==0 || z==1) return null;
return new Point2D.Double(
(double)(s1+z*rx), (double)(sp2+z*ry));
}
}
if (abs(a-b) < 1.0E-6)
而不是if(a==b)
。 - undefined