已知一条直线经过两个点,使用Python求直线外其中一个点到直线的距离

已知一条直线经过两个点 P1(x1, y1) 和 P2(x2, y2),求直线外其中一个点 P3(x3, y3) 到直线的距离可以通过以下步骤计算:

1、计算直线的斜率 m 和截距 b。

2、使用点到直线的距离公式计算 P3 到直线的距离。

距离公式为:

python 复制代码
距离 = |(m*x3-y3+ b)| / sqrt(m^2 + 1)

其中 m 是直线的斜率,b 是直线的截距,sqrt 表示平方根。

以下是一个 Python 函数,它接受直线经过的两个点 (x1, y1) 和 (x2, y2) 以及外部点的坐标 (x3, y3),并返回该点到直线的距离:

python 复制代码
import math

def distance_from_point_to_line(x1, y1, x2, y2, x3, y3):
    # 计算直线的斜率
    if x2 != x1:  # 避免除以零
        m = (y2 - y1) / (x2 - x1)
    else:
        # 如果两点在同一条垂直线上,则斜率不存在,直接返回 x 方向的距离
        return abs(x3 - x1)
    
    # 计算直线的截距
    b = y1 - m * x1
    
    # 使用点到直线的距离公式计算距离
    distance = abs(m*x3-y3+ b) / math.sqrt(m**2 + 1)
    return distance

# 示例使用
x1, y1 = 0, 0
x2, y2 = 1, 1
x3, y3 = 2, 2

distance = distance_from_point_to_line(x1, y1, x2, y2, x3, y3)
print(f"The distance from the point ({x3}, {y3}) to the line defined by ({x1}, {y1}) and ({x2}, {y2}) is {distance}")

Tips:

斜率 m 的垂直线(即过 P1 点的垂线)的斜率 m_vertical 为 -1/m。

相关推荐
阿尔的代码屋5 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django