点到线段的最短距离算法

转载

http://blog.sina.com.cn/s/blog_5d5c80840101bnhw.html

使用C#实现上述算法:

public static doublePointToSegDist(double x, double y, double x1, double y1, double x2,double y2)

{

double cross =(x2 - x1) * (x - x1) + (y2 - y1) * (y - y1);

if (cross <=0) return Math.Sqrt((x - x1) * (x - x1) + (y - y1) * (y -y1));


double d2 = (x2 - x1) * (x2- x1) + (y2 - y1) * (y2 - y1);

if (cross >=d2) return Math.Sqrt((x - x2) * (x - x2) + (y - y2) * (y -y2));

 

double r = cross /d2;

double px = x1 + (x2 - x1) *r;

double py = y1 + (y2 - y1) *r;

return Math.Sqrt((x - px) *(x - px) + (py - y1) * (py - y1));

}

 

除了代码简单、计算量少的优点外,上述代码不依赖其它函数和自定义的数据结构,便于直接使用或者转换为其他编程语言(诸如C++、java等)使用而无需做较大的改动。

猜你喜欢

转载自blog.csdn.net/hetongde/article/details/79173029