英文:
Method shapely.intersection returns a wrong answer
问题
我尝试使用方法shapely.intersection
在二维中找到两条边的交点,但得到了错误的答案。
Shapely模块版本为2.0.1
from shapely.geometry import LineString
a = LineString([[30.0,0.0],[36.0,30.0]])
b = LineString([[32.8,14.0],[35.2,26.0]])
intersection = a.intersection(b)
很容易检查到边b
完全位于边a
上,因此交点的结果应该等于b
,但是代码返回了一个点(边b
的中心点)
Point(34,20)
英文:
I try to find intersection of two edges in 2D using method shapely.intersection and get a wrong answer
Shapely module v.2.0.1
from shapely.geometry import LineString
a = LineString([[30.0,0.0],[36.0,30.0]])
b = LineString([[32.8,14.0],[35.2,26.0]])
intersection = a.intersection(b)
It is easy to check that edge b
entirely lays on edge a
, and so the result of intersection will be equals b
but code returns one point (the center of the edge b
)
Point(34,20)
答案1
得分: 1
你所看到的是浮点数运算中不完美精度的结果。这个问题详细讨论了这个主题。
shapely.intersection
提供了指定网格大小以限制计算精度的选项:
> shapely.intersection(a, b, 0.1)
<MULTILINESTRING ((32.8 14, 34 20), (34 20, 35.2 26))>
返回的 MultiLineString
由多个线段组成(我没有深入研究原因)。您可以使用返回的 MultiLineString
的 oriented_envelope
属性,将连接的线段缩减回单个 LineString
(只要它们实际上是连接的且共线的):
> line_string = shapely.intersection(a, b, 0.1)
> line_string.oriented_envelope
<LINESTRING (32.8 14, 35.2 26)>
英文:
What you're seeing is the result of imperfect precision in floating point math. This question discusses the topic extensively.
shapely.intersection
gives you the option to specify a grid size to limit the precision of the calculations:
> shapely.intersection(a, b, 0.1)
<MULTILINESTRING ((32.8 14, 34 20), (34 20, 35.2 26))>
The returned MultiLineString
consists of multiple segements (I haven't looked into why). You can use the oriented_envelope
property of the returned MultiLineString
to reduce the connected segments back into a single LineString
(as long as they are actually connected and colinear):
> line_string = shapely.intersection(a, b, 0.1)
> line_string.oriented_envelope
<LINESTRING (32.8 14, 35.2 26)>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论