我的程序中目前有以下行我还有另外两个整数变量,x
和y
。
我想看看这个新的点是否在这条线上我一直在看以下线索:
Given a start and end point, and a distance, calculate a point along a line
我想到了以下几点:
if(x >= x1 && x <= x2 && (y >= y1 && y <= y2 || y <= y1 && y >= y2))
{
float vx = x2 - x1;
float vy = y2 - y1;
float mag = sqrt(vx*vx + vy*vy);
// need to get the unit vector (direction)
float dvx = vx/mag; // this would be the unit vector (direction) x for the line
float dvy = vy/mag; // this would be the unit vector (direction) y for the line
float vcx = x - x1;
float vcy = y - y1;
float magc = sqrt(vcx*vcx + vcy*vcy);
// need to get the unit vector (direction)
float dvcx = vcx/magc; // this would be the unit vector (direction) x for the point
float dvcy = vcy/magc; // this would be the unit vector (direction) y for the point
// I was thinking of comparing the direction of the two vectors, if they are the same then the point must lie on the line?
if(dvcx == dvx && dvcy == dvy)
{
// the point is on the line!
}
}
它似乎不起作用,还是这个主意有问题?
最佳答案
浮点数的精度有限,因此您将从计算中获得舍入误差,结果是应该在数学上相等的值最终会略有不同。
您需要与较小的误差容限进行比较:
if (std::abs(dvcx-dvx) < tolerance && std::abs(dvcy-dvy) < tolerance)
{
// the point is (more or less) on the line!
}
困难的部分是选择容忍度。如果不能接受任何错误,则需要使用固定精度浮点值以外的其他值(可能是整数),重新排列计算以避免除法和其他不精确操作。
在任何情况下,您都可以更简单地执行此操作,而不必使用平方根。你想知道这两个向量是平行的;它们是向量积是零还是相等的,如果它们有相等的切线。所以你只需要
if (vx * vcy == vy * vcx) // might still need a tolerance for floating-point
{
// the point is on the line!
}
如果您的输入是整数,小到乘法不会溢出,那么根本不需要浮点运算。
关于c++ - 查看点是否在直线上( vector ),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26849632/