Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compute the intersection point of two lines?

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] 
like image 212
bolt19 Avatar asked Dec 19 '13 09:12

bolt19


People also ask

How do you calculate the point of intersection?

When the graphs of y = f(x) and y = g(x) intersect , both graphs have exactly the same x and y values. So we can find the point or points of intersection by solving the equation f(x) = g(x). The solution of this equation will give us the x value(s) of the point(s) of intersection.


1 Answers

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.)

def line_intersection(line1, line2):     xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])     ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])      def det(a, b):         return a[0] * b[1] - a[1] * b[0]      div = det(xdiff, ydiff)     if div == 0:        raise Exception('lines do not intersect')      d = (det(*line1), det(*line2))     x = det(d, xdiff) / div     y = det(d, ydiff) / div     return x, y  print line_intersection((A, B), (C, D)) 

And FYI, I would use tuples instead of lists for your points. E.g.

A = (X, Y) 

EDIT: Initially there was a typo. That was fixed Sept 2014 thanks to @zidik.

This is simply the Python transliteration of the following formula, where the lines are (a1, a2) and (b1, b2) and the intersection is p. (If the denominator is zero, the lines have no unique intersection.)

like image 149
Paul Draper Avatar answered Oct 01 '22 03:10

Paul Draper