以对称方式计算两个线段之间的交集

发布于 2024-08-28 14:14:43 字数 420 浏览 13 评论 0 原文

使用常用公式计算两个 2D 线段之间的交集时,即 此处,如果将结果四舍五入为整数,则会得到非对称结果。

也就是说,有时,由于舍入错误,我会得到 intersection(A,B)!=intersection(B,A)

最好的解决方案是继续使用浮点数,并以一定的精度比较结果。但是,在计算交集后,我必须将结果舍入为整数,我不能继续使用浮点数。

到目前为止,我最好的解决方案是对平面上的线段使用一些完整的顺序,并使用交集来始终将较小的线段与较大的线段进行比较。

有更好的方法吗?我错过了什么吗?

When using the usual formulas to calculate intersection between two 2D segments, ie here, if you round the result to an integer, you get non-symmetric results.

That is, sometimes, due to rounding errors, I get that intersection(A,B)!=intersection(B,A).

The best solution is to keep working with floats, and compare the results up to a certain precision. However, I must round the results to integers after calculating the intersection, I cannot keep working with floats.

My best solution so far was to use some full order on the segments in the plane, and have intersection to always compare the smaller segment to the larger segment.

Is there a better method? Am I missing something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不爱素颜 2024-09-04 14:14:43

您不想比较段长度。

另外,我假设将 intersection(A',B')intersection(B",A") 进行比较时,可以理解 A' 的坐标代表性 相同 A"(同上 B'B"),否则无解。

话虽这么说,请考虑段 [PQ][RS],其中 PQ RS 是平面上的点。您需要线段的交集:

  • [PQ] [RS]
  • [QP] [RS]
  • [PQ] [SR]
  • [QP] [SR]
  • [RS] [PQ]
  • [SR]
  • [PQ] [RS] [QP]
  • [SR] [QP]

...始终返回相同的坐标对。

首先对每个段上的端点进行排序,然后对段本身进行排序(基于每个段的最小端点),这是保证可重现结果的唯一解决方案。排序本身在计算上可能是微不足道的,例如P当且仅当Px<<。 Qx || Px == Qx && py < Qy,尽管如果处理数百万个段,分支可能会变得昂贵(如果可能的话,请参阅如何利用 SIMD 就地交换段坐标来生成排序。)

You do not want to compare segment lengths.

Also, I assume that when comparing intersection(A',B') to intersection(B",A") it is understood that A''s coordinates are representationally identical to A"'s (idem for B' and B"), or else there is no solution.

This being said, consider segments [PQ] and [RS], where P, Q, R and S are points in the plane. You want the intersections of the segments:

  • [PQ] [RS]
  • [QP] [RS]
  • [PQ] [SR]
  • [QP] [SR]
  • [RS] [PQ]
  • [SR] [PQ]
  • [RS] [QP]
  • [SR] [QP]

... to always return the same coordinate pair.

Ordering, first of the endpoints on each segment, then of the segments themselves (based on each segments' least endpoint), is the only solution that guarantees reproducible results. The ordering itself can be computationally trivial, e.g. P<Q iff P.x < Q.x || P.x == Q.x && P.y < Q.y, although branching could get expensive if dealing with millions of segments (see how you can make use of SIMD to swap segment coordinates in-place if possible to generate the ordering.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文