java 代码 点到线段的最短距离

               

转自:http://hi.baidu.com/javalovers/item/74b6e60f9debaae6f45ba657

// 点到直线的最短距离的判断 点(x0,y0) 到由两点组成的线段(x1,y1) ,( x2,y2 )

       private double pointToLine(int x1, int y1, int x2, int y2, int x0,

              int y0) {

           double space = 0;

           double a, b, c;

           a = lineSpace(x1, y1, x2, y2);// 线段的长度

           b = lineSpace(x1, y1, x0, y0);// (x1,y1)到点的距离

           c = lineSpace(x2, y2, x0, y0);// (x2,y2)到点的距离

           if (c <= 0.000001 || b <= 0.000001) {

              space = 0;

              return space;

           }

           if (a <= 0.000001) {

              space = b;

              return space;

           }

           if (c * c >= a * a + b * b) {

              space = b;

              return space;

           }

           if (b * b >= a * a + c * c) {

              space = c;

              return space;

           }

           double p = (a + b + c) / 2;// 半周长

           double s = Math.sqrt(p * (p - a) * (p - b) * (p - c));// 海伦公式求面积

           space = 2 * s / a;// 返回点到线的距离(利用三角形面积公式求高)

           return space;

       }

       // 计算两点之间的距离

       private double lineSpace(int x1, int y1, int x2, int y2) {

           double lineLength = 0;

           lineLength = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2)

                  * (y1 - y2));

           return lineLength;

       }


           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在MATLAB中,我们可以使用向量运算和标量运算来计算点到线段的最短距离。下面将展示一个简单的MATLAB程序,用于计算点到线段的最短距离。 ```matlab function distance = shortestDistance(point, lineStart, lineEnd) % 计算线段的向量 lineVector = lineEnd - lineStart; % 计算点到线段的向量 pointVector = point - lineStart; % 计算点到线段结束的向量 endVector = point - lineEnd; % 计算点到线段的投影向量 projectionVector = dot(pointVector, lineVector) / dot(lineVector, lineVector) * lineVector; % 如果投影向量在线段向量的范围之外,则最短距离点到线段的起或结束的距离 if dot(projectionVector, lineVector) < 0 distance = norm(pointVector); elseif dot(endVector, lineVector) > 0 distance = norm(endVector); else % 否则,最短距离点到投影向量的距离 distance = norm(pointVector - projectionVector); end end ``` 在这个程序中,我们定义了一个名为`shortestDistance`的函数,它有三个输入参数:`point`代表的坐标,`lineStart`代表线段的起坐标,`lineEnd`代表线段的结束坐标。函数使用向量运算和标量运算来计算点到线段的最短距离。 首先,我们计算线段的向量`lineVector`、点到线段的向量`pointVector`和点到线段结束的向量`endVector`。 然后,我们计算点到线段的投影向量`projectionVector`,通过点到线段向量与线段向量的内积除以线段向量的模长,再乘以线段向量。 接下来,我们通过判断投影向量是否在线段向量的范围之外来确定最短距离点到线段的起或结束的距离,或是点到投影向量的距离。 最后,我们将最短距离返回。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值