2015-03-02 479 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時,您沒有此問題。

相關問題