【问题标题】:How can I find the perpendicular distance between two parallel line segments?如何找到两条平行线段之间的垂直距离?
【发布时间】:2015-03-02 13:18:17
【问题描述】:

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

如何在 c++ 中有效地找到这些线段之间的垂直空间?

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 您在获取formula 时遇到问题吗?还是用 C++ 表达这个公式?
  • 我无法用 C++ 表达公式,也许我只需要一些简单的例子就可以从那里开始
  • 这对我有帮助:youtube.com/watch?v=KUXbhlAGeok

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


【解决方案1】:

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

另请注意,在 2d 中,与向量 (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,但是由于它没有显示,我纯粹使用双精度来编写代码。

【讨论】:

  • 谢谢。没有考虑过使用向量,但对我来说更容易理解。 +1 示例代码!
【解决方案2】:

快速谷歌搜索产生这篇维基百科文章。 http://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line

要计算距离,您需要将一条线的方程式表示为ax + by + c = 0。然后,您可以使用另一条线的点来使用维基百科文章中给出的公式计算距离。

要从直线上的两个点获得ax + by + c = 0 形式的直线方程,请使用此网页https://bobobobo.wordpress.com/2008/01/07/solving-linear-equations-ax-by-c-0/ 中描述的方法 然后,您获得该行的值 a、b 和 c。

一旦有了公式,就可以直接将其转换为 c++。

我不鼓励使用 mx + b = y 形式的直线方程,因为您可能会发现自己遇到 m 无限大的情况。那么计算距离将非常困难。使用公式ax + by + c = 0 时不会出现这个问题。

【讨论】: