【Python】计算点到线段的距离

本文介绍了一个Python函数,用于计算点到线段的距离,考虑了点在线段上、投影在线段上以及投影在线段外三种情况,提供了详细的几何解释和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

计算点到线段的距离,需要分为三种情况进行讨论:(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))

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值