c++ - 如何找到两条平行线段之间的垂直距离?

标签 c++ parallel-processing geometry lines euclidean-distance

我有很多平行线段,例如 L1(P1, P2) 和 L2(P3, P4)。 点具有每个 x 和 y 坐标。 这些平行线段的角度在 0-180 度之间变化。

如何在 C++ 中有效地找到这些线段之间的垂直空间? Distance between two parallel line segments

最佳答案

两条平行线之间的距离将是第一条(无限)线与第二条线上任意点(例如 P3)之间的距离。由于您使用的是坐标,因此使用公式的 vector 表示比尝试将线表示为方程更方便。使用该表示,在 2d 中,此距离由 |(P3 - P1) dot ( norm ( P2 - P1 ))| 给出,其中 norm 是垂直于 P2 - P1:

enter image description here

另请注意,在 2d 中,垂直于 vector (x, y) 的垂线很容易由 (-y, x) 给出。因此:

class GeometryUtilities
{
public:
    GeometryUtilities();
    ~GeometryUtilities();

    static double LinePointDistance2D(double lineP1X, double lineP1Y, double lineP2X, double lineP2Y, double pointX, double pointY);

    static void Perpendicular2D(double x, double y, double &outX, double &outY);

    static double Length2D(double x, double y);
};

double GeometryUtilities::LinePointDistance2D(double lineP1X, double lineP1Y, double lineP2X, double lineP2Y, double pointX, double pointY)
{
    double vecx = lineP2X - lineP1X;
    double vecy = lineP2Y - lineP1Y;
    double lineLen = Length2D(vecx, vecy);
    if (lineLen == 0.0) // Replace with appropriate epsilon
    {
        return Length2D(pointX - lineP1X, pointY - lineP1Y);
    }

    double normx, normy;
    Perpendicular2D(vecx/lineLen, vecy / lineLen, normx, normy);
    double dot = ((pointX - lineP1X) * normx + (pointY - lineP1Y) * normy); // Compute dot product (P3 - P1) dot( norm ( P2 - P1 ))
    return abs(dot);
}

void GeometryUtilities::Perpendicular2D(double x, double y, double &outX, double &outY)
{
    outX = -y;
    outY = x;
}

double GeometryUtilities::Length2D(double x, double y)
{
    return sqrt(x*x + y*y);
}

在生产中,您可能希望引入某种 Point 类,这将大大美化此 API,但是由于未显示,我编写的代码完全使用 double 值。

关于c++ - 如何找到两条平行线段之间的垂直距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28810760/

相关文章:

c++ - 覆盖具有不同返回类型的虚函数

c++ - 在哪里为 QMainWindow : in header file or in constructor? 声明某些 Qt 对象

Android NDK 相机示例 JPEG(30 Hz)

c++ - 将 std::string 转换为 boost::posix_time::ptime

c# - 如何在多线程中并行运行依赖任务?

java - 计算交点数值不准确

c++ - 3d 空间中两个 vector 之间的角度

c++ - 获取线程用于锁定互斥锁

Python 多处理程序未运行到最后

geometry - 用于三角形交叉加速结构的简单 C/C++ 库