I have two segments A and B (each defined by two points) which intersect. The point X is the intersection of A and B. How can I find the coordonates of X ?
-
2Do you really believe that you are the first man with this question? – MBo Apr 28 '17 at 16:58
-
1No but I haven't found a simple answer in Stack OverFlow. – Brice Gay Apr 28 '17 at 17:03
-
What simple answer did you expect? There are some pitfalls in this "simple problem" and solution must account for them. – MBo Apr 29 '17 at 02:36
2 Answers
I assume you're working in two dimensions. Let's introduce some notation. Let the first line segment be defined by the points
P1 = (x1, y1)
and
P2 = (x2, y2).
The second line segment is defined by the points
P3 = (x3, y3)
and
P4 = (x4, y4).
Any point on the first line segment can be represented by the parametric expression
s P1 + (1 - s) P2
where s is a real number between 0 and 1. Likewise, any point on the second line can be similarly represented as
t P3 + (1 - t) P4.
The point of intersection is where these two expressions are equal:
s P1 + (1 - s) P2 = t P3 + (1 - t) P4
Reducing this to x and y coordinates yields two equations in two unknowns, s and t. Solve for s and/or t then yields the point of intersection by substituting back into the original equations.
Note that using a parametric line representation like this (unlike the approach of computing the slope-intercept form) works even if one of the line segments happens to have infinite slope.
Also, as an added bonus, if either s or t ends up being outside the range [0, 1], then the two line segments don't intersect (the lines containing the segments intersect somewhere beyond one or both segments). Finally, if the two simultaneous equations don't have a solution, the lines containing the two segments are parallel. (They may even be on the same line. Distinguishing that case, including whether the segments meet at an endpoint or overlap partially or fully, is left as an exercise for the reader. :))

- 232,168
- 48
- 399
- 521
Say your two points on segment A are (x1, y1)
and (x2, y2)
. These two points are enough to determine the equation of the straight line:
y - y1 = slope.(x - x1)
where slope is = (y2-y1)/(x2-x1)
So using this trick, you can find the equations of both segments A and B. These will be of the form y = p_A + q_A x and y = p_B + q_B x
for each of the segments.
The point (x*, y*)
where two segments intersect is where y* = p_A + q_A x*
and y* = p_B + q_Bx*
, so that p_A + q_A x* = p_B + q_B x*
. From here you have the value of x*,
and you can find y*
by replacing this value of x in any of the segments' equations.
Hope this helps!

- 77,632
- 48
- 245
- 261

- 11
- 2
-
1This approach fails if either segment happens to be vertical (infinite slope). – Ted Hopp Apr 28 '17 at 17:38