您的位置:首页 > 其它

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

2016-09-08 11:05 330 查看
原文地址



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



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

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

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

[cpp] view
plain copy

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

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

下面是书中的写法。

[cpp] view
plain copy

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、如果是求两条线段的交点,先判断两条线段是否相交。

      若相交,则问题可转化成两条直线求交点。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: