点と直線間の距離

2022/09/04

Python3.8.2

def distance_between_point_and_line(p,a,b,c):
    x,y = p
    n = abs(a*x + b*y + c)
    d = (a**2+b**2)**0.5
    return n/d

この時の、直線状の点は以下。
def closest_point_on_line(p,a,b,c):
    d = (a*p[0]+b*p[1]+c)/(a*a + b*b)
    x = p[0] - a*d
    y = p[1] - b*d
    return [x,y]


点と線分間の距離

def distance_between_point_and_line_segment(p0,p1,p2):
    x0,y0 = p0; x1,y1 = p1; x2,y2 = p2
    a = x2 - x1; b = y2 - y1;
    a2 = a * a; b2 = b * b
    r2 = a2 + b2;
    tt = -(a*(x1-x0)+b*(y1-y0))
    if tt < 0:
        return (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0);
    if tt > r2:
        return (x2-x0)*(x2-x0) + (y2-y0)*(y2-y0);
    f1 = a*(y1-y0)-b*(x1-x0);
    return (f1*f1)/r2;