现在的位置: 首页 > 综合 > 正文

求两条直线(线段)的交点

2013年10月03日 ⁄ 综合 ⁄ 共 1473字 ⁄ 字号 评论关闭

如图,如何求得直线 AB 与直线 CD 的交点P?

以上内容摘自《算法艺术与信息学竞赛》。

思路就是利用叉积求得点P分线段DC的比,然后利用高中学习的定比分点坐标公式求得分点P的坐标。

看不懂的可以去复习下 定比分点 的知识。

#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,然后利用通分前的公式计算。

书上那样写可能是因为前面已经求得了两个叉积,直接使用更方便的关系。

下面是书中的写法。

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:

1、求交点之前,要保证两条直线不共线。

2、如果是求两条线段的交点,先判断两条线段是否相交。

      若相交,则问题可转化成两条直线求交点。

抱歉!评论已关闭.