2015-03-02 483 views
0

我有许多平行线段,例如L1(P1,P2)和L2(P3,P4)。 点有x和y坐标。这些平行线段在0-180度之间具有不同的角度。如何找到两条平行线段之间的垂直距离?

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

+2

到目前为止您尝试了什么? – user2079303 2015-03-02 13:20:26

+1

在导出[公式](http://en.wikipedia.org/wiki/Distance_between_two_straight_lines)时有困难吗?或者用C++表达那个公式? – 2015-03-02 13:30:40

+0

我无法在C++中表达公式,也许我只需要一些简单的例子就可以从那里开始 – baal 2015-03-02 13:37:22

回答

2

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

enter image description here

还要注意,在图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,但是因为它没有显示我写的代码使用纯粹双打。

+0

Thankk you。没有想过使用载体,但它对我来说更容易理解。示例代码+1! – baal 2015-03-03 14:49:08

0

快速谷歌搜索产生这个维基百科的文章。 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时,您没有此问题。

相关问题