I have two lines that intersect at a point. I know the endpoints of the two lines. How do I compute the intersection point in Python?
# Given these endpoints
#line 1
A = [X, Y]
B = [X, Y]
#line 2
C = [X, Y]
D = [X, Y]
# Compute this:
point_of_intersection = [X, Y]
Can't stand aside,
So we have linear system:
let's do it with Cramer's rule, so solution can be found in determinants:
where D is main determinant of the system:
and Dx and Dy can be found from matricies:
and
(notice, as C column consequently substitues the coef. columns of x and y)
So now the python, for clarity for us, to not mess things up let's do mapping between math and python. We will use array
L
for storing our coefs A, B, C of the line equations and intestead of prettyx
,y
we'll have[0]
,[1]
, but anyway. Thus, what I wrote above will have the following form further in the code:for D
for Dx
for Dy
Now go for coding:
line
- produces coefs A, B, C of line equation by two points provided,intersection
- finds intersection point (if any) of two lines provided by coefs.Usage example:
I didn't find an intuitive explanation on the web, so now that I worked it out, here's my solution. This is for infinite lines (what I needed), not segments.
Some terms you might remember:
Given those definitions, here are some functions:
Here's a simple test between two (infinite) lines:
Output:
Using formula from: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
Unlike other suggestions, this is short and doesn't use external libraries like
numpy
. (Not that using other libraries is bad...it's nice not need to, especially for such a simple problem.)And FYI, I would use tuples instead of lists for your points. E.g.