pythondistance

draw the angle of perpendicular distance between point and a line


i tray with this coordinates, the point is R=(x0,y0),the line is AB where A=(x1,y1) and B=(x2,y2), but i didn't know if it is really perpendicular, and i can't draw the angle projection.

R = (2, 6) 
A = (8, 4)  
B = (2 ,1.8)

How can I choose the coordinates to get the perpendicular?


Solution

  • Write the (parameterised) equation of the straight line as

    x=x1+t(x2-x1), y=y1+t(y2-y1)
    

    Write the (squared) distance of point (x0,y0) from this line:

    R^2=(x1+t(x2-x1)-x0)^2+(y1+t(y2-y1))^2
    

    Differentiate R^2 with respect to t to find the minimum. (Line of code below).

    Use this value of t to get the projection point. Note that if t lies outside [0,1] then the projection point is outside the line segment.

    import math
    import matplotlib.pyplot as plt
    
    x0, y0 = 2, 6
    
    x1, y1 = 8, 4
    x2, y2 = 2, 1.8
    
    t = -( (x2-x1)*(x1-x0)+(y2-y1)*(y1-y0) ) / ( (x2-x1)**2 + (y2-y1)**2 )
    p, q = x1 + t * ( x2 - x1 ), y1 + t * ( y2 - y1 )
    
    print( "Projection point is ", p, q )
    print( "Nearest distance (to extended line) is ", math.sqrt( ( p - x0 ) ** 2 + ( q - y0 ) ** 2 ) )
    
    plt.plot( [x0,x1,x2], [y0,y1,y2], 'o' )
    plt.plot( [x1,x2], [y1,y2], '-' )
    plt.plot( [x0,p ], [y0,q ], '--' )
    plt.show()
    

    Output:

    Projection point is  3.357492654260529 2.2977473065621936
    Nearest distance (to extended line) is  3.9432805267237567
    

    enter image description here