You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算矩形内部给定点各角度射线到边界的距离?求Python/C++简易算法

矩形内点射线到边界距离计算方案

核心逻辑

无需复杂的象限判断,通过参数化射线求交即可快速得到结果:

  • 首先将角度从角度制转换为弧度制,计算对应方向的单位向量:dx = cos(弧度值),dy = sin(弧度值)
  • 分别计算射线和矩形4条边界相交的参数t(因为使用了单位向量,有效t值直接等于射线到交点的距离):
    • 左边界x=0:dx小于0时有效,t_left = (-Xp) / dx
    • 右边界x=Xm:dx大于0时有效,t_right = (Xm - Xp) / dx
    • 下边界y=0:dy小于0时有效,t_bottom = (-Yp) / dy
    • 上边界y=Ym:dy大于0时有效,t_top = (Ym - Yp) / dy
  • 收集所有大于1e-8的有效t值(忽略负t对应的反方向交点,小阈值用于避免浮点计算误差),最小的t就是当前角度对应的距离。

Python 实现代码

import math

def calculate_distance(Xm: float, Ym: float, Xp: float, Yp: float, angle_deg: float) -> float:
    eps = 1e-8
    rad = math.radians(angle_deg)
    dx = math.cos(rad)
    dy = math.sin(rad)
    valid_t = []
    # 计算左右边界交点
    if abs(dx) > eps:
        t = (Xm - Xp) / dx if dx > 0 else (-Xp) / dx
        if t > eps:
            valid_t.append(t)
    # 计算上下边界交点
    if abs(dy) > eps:
        t = (Ym - Yp) / dy if dy > 0 else (-Yp) / dy
        if t > eps:
            valid_t.append(t)
    return min(valid_t)

# 批量计算0°到359°所有角度的距离示例
def calc_all_angles(Xm: float, Ym: float, Xp: float, Yp: float) -> list[float]:
    return [calculate_distance(Xm, Ym, Xp, Yp, a) for a in range(360)]

C++ 实现代码

#include <vector>
#include <cmath>
#include <algorithm>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

float calculateDistance(float Xm, float Ym, float Xp, float Yp, float angleDeg) {
    const float eps = 1e-8f;
    float rad = angleDeg * M_PI / 180.0f;
    float dx = cos(rad);
    float dy = sin(rad);
    float minT = 1e18f;

    // 处理左右边界
    if (fabs(dx) > eps) {
        float t = dx > 0 ? (Xm - Xp) / dx : (-Xp) / dx;
        if (t > eps && t < minT) minT = t;
    }
    // 处理上下边界
    if (fabs(dy) > eps) {
        float t = dy > 0 ? (Ym - Yp) / dy : (-Yp) / dy;
        if (t > eps && t < minT) minT = t;
    }
    return minT;
}

// 批量计算0°到359°所有角度的距离
std::vector<float> calcAllAngles(float Xm, float Ym, float Xp, float Yp) {
    std::vector<float> res(360);
    for (int a = 0; a < 360; a++) {
        res[a] = calculateDistance(Xm, Ym, Xp, Yp, a);
    }
    return res;
}

内容的提问来源于stack exchange,提问作者Aziz zeGeek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:39:01