计算点到线段的距离,需要分为三种情况进行讨论:(1)点在线段上,距离为0;(2)点的投影在线段上,距离等效于点到直线的距离;(3)点的投影在线段外,距离为点到最近线段端点的距离。
代码如下:
import math
def point_to_line_distance(point, line_start, line_end):
eps = 1e-6
def sign(x):
if abs(x) < eps:
return 0
return 1 if x > 0 else -1
def distance(a, b):
return math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)
def cross_product(a, b, c):
return (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])
def dot_product(a, b):
return a[0] * b[0] + a[1] * b[1]
s1 = (line_end[0] - line_start[0], line_end[1] - line_start[1])
s2 = (point[0] - line_start[0], point[1] - line_start[1])
s3 = (point[0] - line_end[0], point[1] - line_end[1])
if line_start[0] == line_end[0] and line_start[1] == line_end[1]:
return distance(point, line_start)
if sign(dot_product(s1, s2)) < 0:
return distance(point, line_start)
elif sign(dot_product(s1, s3)) > 0:
return distance(point, line_end)
else:
return abs(cross_product(line_start, point, line_end)) / distance(line_start, line_end)
# 测试代码
a = (3, 3)
b = (1, 0)
c = (2, 0)
print(point_to_line_distance(a, b, c))