Intersection of two lines defined By Two Line Segments

#!/usr/bin/python3 # =================================================================== # math.stackexchange.com/questions/375083/given-coordinates-of- # beginning-and-end-of-two-intersecting-line-segments-how-do # ------------------------------------------------------------------- # Lines # 1 line segments cross at the origin # # -100,100 * | * 100,100 # \ | / # \ | / # \ | / # \|/ # ----------+---------- # /|\ # / | \ # / | \ # / | \ # -100,-100 * | * 100,-100 # # ------------------------------------------------------------------- # Lines # 2 line segments don't cross; don't intersect at the origin # # | * 100,100 # | / # | * 50,50 # | # | # ----------+---------- # | # | # | # 0,-100 *--------* 100,-100 # # ------------------------------------------------------------------- # Lines # 3 line segments don't cross # # -100,100 * | * 100,100 # \ | / # -50,50 * | * 50,50 # | # | # ----------+---------- # | # | # # ------------------------------------------------------------------- # Line # 4 parallel lines (do not cross) # # -100,100 | # * * 0,100 # \ | \ # \ | \ # \| \ # ----------*------*--- # 0,0 | 100,0 # | # | # # =================================================================== # ---- each entry is two lines: ((x1,y1,x2,y2),(u1,v1,u2,v2)) # ---- line segments are used to define lines intersections = [ ((100,100,-100,-100), (-100,100,100,-100)), ((100,100,50,50), (100,-100,0,-100)), ((100,100,50,50), (-100,100,-50,50)), ((-100,100,0,0), (0,100,100,0)) ] # ------------------------------------------------------------------- # ---- calculate the intersection of two lines (segments) # ---- defined by X,Y coordinates. # ---- Note: the intersection point must be tested if you want to # ---- see if the two line segments intersect. lines go on to # ---- infinity. line segments have end points. # ------------------------------------------------------------------- def calculate_intersection(line1,line2): x1 = line1[0] y1 = line1[1] x2 = line1[2] y2 = line1[3] u1 = line2[0] v1 = line2[1] u2 = line2[2] v2 = line2[3] # ---- calculate X try: x = -1 * ((x1 - x2) * (u1 * v2 - u2 * v1) - (u2 - u1) * (x2 * y1 - x1 * y2)) / ((v1 - v2) * (x1 - x2) - (u2 - u1) * (y2 - y1)) except Exception as e: print(e) return (False,0,0) # ---- calculate Y try: y = -1 * (u1 * v2 * y1 - u1 * v2 * y2 - u2 * v1 * y1 + u2 * v1 * y2 - v1 * x1 * y2 + v1 * x2 * y1 + v2 * x1 * y2 - v2 * x2 * y1) / (-1 * u1 * y1 + u1 * y2 + u2 * y1 - u2 * y2 + v1 * x1 - v1 * x2 - v2 * x1 + v2 * x2) except Exception as e: print(e) return (False,0,0) return (True,x,y) # ------------------------------------------------------------------- # ---- main # ------------------------------------------------------------------- test_count = 1 # intersection test counter for line_pair in intersections: tf,x,y = calculate_intersection(line_pair[0],line_pair[1]) if tf: print(f'line{test_count} x = {x:.2f} y = {y:.2f}') test_count += 1