# How to find a crossing point between two lines?

I need to find the point of intersection between two lines. For example:

The first point of the first line: 1107x332
The second point of the first line: 1193x368
The first point of the second line: 1150x450
The second point of the second line: 1150x250


I have the following code:

float x = -((x1*y2-x2*y1)*(x4-x3)-(x3*y4-x4*y3)*(x2-x1))/((y1-y2)*(x4-x3)-(y3-y4)*(x2-x1));
float y = ((y3-y4)*(-x)-(x3*y4-x4*y3))/(x4-x3);


But I have a problem with diving by 0 here: $x_4-x_3=1150-1150=0$. $$x=\frac{-(x_1y_2-x_2y_1)(x_4-x_3)-(x_3y_4-x_4y_3)(x_2-x_1)}{(y_1-y_2)(x_4-x_3)-(y_3-y_4)(x_2-x_1)}$$ $$y=\frac{(y_3-y_4)(-x)-(x_3y_4-x_4y_3)}{x_4-x_3}$$ Here $x_1,y_1$ are the coordinates of the first point of the first line. $x_2,y_2$ are those of the second point of the first line and so on.

In my example, the lines are crossing somewhere, i.e. they are not parallel. What's wrong with my formulas?

• i don't understand this code, can you use $\LaTeX$ please? – Dr. Sonnhard Graubner Sep 12 '16 at 9:22
• Is it possible that the two lines are parallel? I mean, either the code is wrong (no idea, because it's unreadable to me- please use mathjax for formulas) or the two lines are parallel (so they don't cross, so it makes sense that the formulas break down) – 5xum Sep 12 '16 at 9:23

Since it works with horizontal slope but not vertical, there is a trick. For the 4 points interchange (x,y) coordinates. And again interchange back after getting solution of intersection point to get correct coordinates.

• I used this solution and it worked like a charm :) Thanks! – JavaRunner Sep 12 '16 at 10:11
• Glad it was help.. – Narasimham Sep 12 '16 at 10:20

Your code seems correct, but it does not work if one of the line is vertical, because you have the differences $x_2-x_1$ and $x_4-x_3$ at the denominator. So these case have to be treated as special cases. Note that another special case is when the two lines are parallel.

• Could you please tell me what's the formula I should use in case of vertical line? – JavaRunner Sep 12 '16 at 9:34
• can you use the lines in the form $$y=mx+n,y=ax+b$$? – Dr. Sonnhard Graubner Sep 12 '16 at 9:36
• @Narasimham, wow it works :))) – JavaRunner Sep 12 '16 at 9:47
• I shall then put in answers. Recently some down-votes ! – Narasimham Sep 12 '16 at 10:02

can you use the lines in the form $$y=mx+n,y=ax+b$$? then we can set $y=n$ and $$y=ax+b$$ and $y=n$ is a vertical line