Shortest Distance From a Point to a Line

Test Problem

Find the minimum distance from a point to a line.

image missing

Test Code

#!/usr/bin/python3
# ====================================================================
# shortest distance from a point to a line
# ====================================================================

import numpy as np

# --------------------------------------------------------------------
# ---- calculate the distance to closest point on a line
# --------------------------------------------------------------------

def closest_point_distance(p1,p2,p):

    if p2[0] == p1[0]: 
        print('divide by zero') 
        return abs(p1[0]-p[0])

    # from: stackoverflow.com/questions/39840030/
    #       distance-between-point-and-a-line-from-two-points
    # abs((x2-x1)*(y1-y0) - (x1-x0)*(y2-y1)) /
    # np.sqrt(np.square(x2-x1) + np.square(y2-y1))

    d = abs((p2[0]-p1[0])*(p1[1]-p[1]) - (p1[0]-p[0])*(p2[1]-p1[1]))/ \
        np.sqrt(np.square(p2[0]-p1[0]) + np.square(p2[1]-p1[1]))
    
    return d
    
# --------------------------------------------------------------------
# ---- main
# --------------------------------------------------------------------

if __name__ == '__main__':

    import sys
    
    print()
    print('Distance tests')
    print()

    print('test 1 - initial test')

    p1 = (5,1)
    p2 = (3,3)
    p  = (2,6)
    d  = closest_point_distance(p1,p2,p)
    print(d)
    
    print('test 2 - reverse direction')

    p1 = (3,3)
    p2 = (5,1)
    p  = (2,6)
    d  = closest_point_distance(p1,p2,p)
    print(d)
    
    print('test 3 - point is on the line')

    p1 = (5,1)
    p2 = (3,3)
    p  = (4,2)
    d  = closest_point_distance(p1,p2,p)
    print(d)

    print('test 4 - point is between p1 and p2')

    p1 = (5,1)
    p2 = (3,3)
    p  = (5,3)
    d  = closest_point_distance(p1,p2,p)
    print(d)

    print('test 5 - initial test with negative x')

    p1 = (-5,1)
    p2 = (-3,3)
    p  = (-2,6)
    d = closest_point_distance(p1,p2,p)
    print(d)
    
    print('test 6 - slope 0 degrees')

    p1 = (5,1)
    p2 = (3,1)
    p  = (1,2)
    d  = closest_point_distance(p1,p2,p)
    print(d)

    print('test 7 - slope 90 degrees')

    p1 = (-1,1)
    p2 = (-1,3)
    p  = (1,4)
    d  = closest_point_distance(p1,p2,p)
    print(d)