1
$\begingroup$

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?

$\endgroup$
  • $\begingroup$ i don't understand this code, can you use $\LaTeX$ please? $\endgroup$ – Dr. Sonnhard Graubner Sep 12 '16 at 9:22
  • $\begingroup$ 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) $\endgroup$ – 5xum Sep 12 '16 at 9:23
1
$\begingroup$

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.

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

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.

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

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.