alexbol99 / flatten-js

Javascript library for 2d geometry
MIT License
553 stars 58 forks source link

Intersection between two very close lines returns zero intersections #99

Closed garma83 closed 3 years ago

garma83 commented 3 years ago

Hi,

I have two segments, like this

Segment { ps: Point { x: 34.35, y: 36.557426400375626 }, pe: Point { x: 25.4, y: 36.557426400375626 } } Segment { ps: Point { x: 25.4, y: 36.55742640037563 }, pe: Point { x: 31.25, y: 36.55742640037563 } }

As you can see the lines are very close but not exactly overlapping due to rounding errors earlier in the algorithm. In this case the lines are parallel to the y axis but that is not always the case (else I could round the y value)

When I run an intersect the intersect returns zero intersections. I assume this is because of the rounding error. Is this correct, and if yes, is there a way to influence the margin of error?

alexbol99 commented 3 years ago

Hi @erikpols ,

Strictly speaking, these two segments do not intersect. When this is the case, you can use distance method instead of intersection:

const [dist, shortest_segment] = segment1.distanceTo(segment2)

It returns: dist = 7.105427357601002e-15 And segment

 ps = Point {x: 25.4,y: 36.557426400375626}
 pe = Point {x: 25.4,y: 36.55742640037563}

Then you may decide whether to consider them intersected ot not and choose one of the ends of shortest segment as intersection point.

You are right, intersection is unstable when two segments are close, and for real world applications I often prefer to use distance, because it always work.

Thanks and B.R., Alex

garma83 commented 3 years ago

Ty! That works. I noticed that some other functions have some kind of variance parameter that allows for small deviations. Would be nice for the intersect function as well. But distanceTo is also useable.