检查两条线是否几乎平行会产生错误的结果 [英] Checking if two lines are nearly parallel gives wrong results

查看:46
本文介绍了检查两条线是否几乎平行会产生错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下方程式查找两条线是否平行.但是当线几乎平行并且最终在远处相遇时,我遇到了问题.我想要一个方程,将这两条几乎平行的线视为平行.

I'm using the following equation to find if two lines are parallel or not. But I'm having problems when the lines are nearly parallel and finally meet in the far distance. I want an equation that considers these two nearly parallel lines as parallel.

var la = new Line {X1 = 1005, Y1 = 773, X2 = 1202, Y2 = 1198};
var lb = new Line {X1 = 1239, Y1 = 1181, X2 = 1550, Y2 = 1856};

var d = (lb.Y2 - lb.Y1) * (la.X2 - la.X1) - (lb.X2 - lb.X1) * (la.Y2 - la.Y1);
if (Math.Abs(d) < 0.001)
{
    // Return if lines are parallel
}

令我惊讶的是,上述 d 的等式得出的数字远大于0.我在这里错了吗?我使用的方程式错误吗?

To my surprise the above equation for d results in a number far greater than 0. What a I getting wrong here? Am I using the wrong equation?

我正在使用这篇文章: http://paulbourke.net/geometry/pointlineplane/

I'm using this article: http://paulbourke.net/geometry/pointlineplane/

推荐答案

难以比较坡度.具有斜率7和8的两条线比具有斜率1和2的两条线彼此更靠近,尽管斜率差始终相同.

Slopes are hard to compare. Two lines with the slopes 7 and 8 are closer to each other than two lines with the slopes 1 and 2, although the slope difference is always the same.

相反,我们应该将可以计算出的角度与点积进行比较:

Instead, we should compare the resulting angle which can be calculated with the dot product:

dx1 = la.X2 - la.X1
dy1 = la.Y2 - la.Y1
dx2 = lb.X2 - lb.X1
dy2 = lb.Y2 - lb.Y1
cosAngle = abs((dx1 * dx2 + dy1 * dy2) / sqrt((dx1 * dx1 + dy1 * dy1) * (dx2 * dx2 + dy2 * dy2)))

如果直线是完美的平行线(或反平行线), cosAngle 将为1.它将减小两条直线之间的角度的余弦值.因此,如果两线之间的夹角为10°,则 cosAngle 将为0.9848.您可以指定一个任意阈值,在该阈值之上,线被视为平行.然后

If the lines are perfect parallel (or anti-parallel), cosAngle will be 1. It will decrease by the cosine of the angle in between both lines. So if there is an angle of 10° between the lines, cosAngle will be 0.9848. You can specify an arbitrary threshold above which lines are considered parallel. Then

if(cosAngle > threshold) //threshold = cos(threshold angle)
    // parallel or anti-parallel
else
    // not parallel 

如果要区分反并行度,请不要使用 abs .负值代表反平行性.

If you want to distinguish anti-parallelness, leave the abs away. Then negative values stand for anti-parallelity.

这篇关于检查两条线是否几乎平行会产生错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆