求兩條直線(線段)的交點

如圖,如何求得直線 AB 與直線 CD 的交點P?算法


以上內容摘自《算法藝術與信息學競賽》。學習


思路就是利用叉積求得點P分線段DC的比,而後利用高中學習的定比分點座標公式求得分點P的座標。spa

看不懂的能夠去複習下 定比分點 的知識。code

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

#define N 105

const double eps = 1e-6;

const double Pi = acos(-1.0);

struct Point
{
    Point(){}
    Point(double x,double y):x(x),y(y){}
    double x,y;
};

struct Seg
{
    Point p1,p2;
};

int sgn(double x)
{
    return x<-eps ? -1 : (x>eps);
}

double Cross(const Point& p1,const Point& p2,const Point& p3,const Point& p4)
{
    return (p2.x-p1.x)*(p4.y-p3.y) - (p2.y-p1.y)*(p4.x-p3.x);
}

double Area(const Point& p1,const Point& p2,const Point& p3)
{
    return Cross(p1,p2,p1,p3);
}

double fArea(const Point& p1,const Point& p2,const Point& p3)
{
    return fabs(Area(p1,p2,p3));
}

bool Meet(const Point& p1,const Point& p2,const Point& p3,const Point& p4)
{
    return max(min(p1.x,p2.x),min(p3.x,p4.x)) <= min(max(p1.x,p2.x),max(p3.x,p4.x))
        && max(min(p1.y,p2.y),min(p3.y,p4.y)) <= min(max(p1.y,p2.y),max(p3.y,p4.y))
        && sgn(Cross(p3,p2,p3,p4) * Cross(p3,p4,p3,p1)) >= 0
        && sgn(Cross(p1,p4,p1,p2) * Cross(p1,p2,p1,p3)) >= 0;
}

Point Inter(const Point& p1,const Point& p2,const Point& p3,const Point& p4)
{
    double k = fArea(p1,p2,p3) / fArea(p1,p2,p4);
    return Point((p3.x + k*p4.x)/(1+k),(p3.y + k*p4.y)/(1+k));
}

代碼方面,我並無按照書上的寫法來寫,而是直接求出「比」k,而後利用通分前的公式計算。


書上那樣寫多是由於前面已經求得了兩個叉積,直接使用更方便的關係。htm

下面是書中的寫法。get

Point Inter(const Point& p1,const Point& p2,const Point& p3,const Point& p4)
{
    double s1 = fArea(p1,p2,p3) , s2 = fArea(p1,p2,p4);
    return Point((p4.x*s1+p3.x*s2)/(s1+s2),(p4.y*s1+p3.y*s2)/(s1+s2));
}

Ps:string

一、求交點以前,要保證兩條直線不共線。it

二、若是是求兩條線段的交點,先判斷兩條線段是否相交。io

      若相交,則問題可轉化成兩條直線求交點。class

相關文章
相關標籤/搜索