# Intersection point of line segments

I need to find the intersection point of 2 line segments (lines are finite, i.e., they have end points).

e.g. segment 1 from $(x_1, y_1)$ to $(x_2, y_2)$ -- segment 2 from $(x_3, y_3)$ to $(x_4, y_4)$

you can assume $m_1$ and $m_2$ are the gradients of segment 1 and segment 2 respectively

similarly, $c_1$ and $c_2$ being the y-intercepts of segment 1 and segment 2 respectively

Using $y=mx+c$ I can easily find the equations of both lines and then derive the intersection point from those equations and check if that point actually lies on both the line segments (intersection point may not lie between the end points).

My problem is when I calculate the gradients $m_1$ and $m_2$ I do $\frac{y_2-y_1}{x_2-x_1}$ there for if one of the lines is vertical then I am going to have problems. How can I deal with this?

Another problem is that if the two segments intersect at a point which is also the same as one of the end points then I want to assume that they are not intersecting.

e.g. if segment 1 is from $(2, 3)$ to $(3, 7)$ and segment 2 is from $(3, 7)$ to $(7, 3)$ then I want to assume they don't intersect.

## migrated from stackoverflow.comDec 9 '11 at 0:15

This question came from our site for professional and enthusiast programmers.

Instead of taking $x,y$ as the variables to solve for, write $(x,y)$ $= (x_1,y_1)+t(x_2-x_1,y_2-y_1)$ $= (x_3,y_3)+u(x_4-x_3,y_4-y_3)$ and solve for $t$ and $u$. Then it doesn't matter a bit whether your line segments are horizontal or vertical or whatever, and you can check for being within the segments just by looking at whether $0 < t < 1$ and $0 < u < 1$.