问题描述
我目前在我的程序以下行。我有另外两个整数变量, X
和是
。
I have currently the following line in my program. I have two other whole number variables, x
and y
.
我想看看这个新点(X,Y)
是在这条线。我一直在寻找以下主题:
I wish to see if this new point(x, y)
is on this line. I have been looking at the following thread:
Given开始和结束点,以及一个距离,计算一个点沿着线的
我已经出来了以下内容:
I've come up with the following:
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!
}
}
这似乎并不奏效,或者是这种想法乱作一团?
It doesn't seem to be working, or is this idea whack?
推荐答案
浮点数有一个有限的precision,所以你会得到计算舍入误差,结果是值应该在数学上是平等的意志最终略有不同。
Floating point numbers have a limited precision, so you'll get rounding errors from the calculations, with the result that values that should mathematically be equal will end up slightly different.
您将需要一个小容忍误差比较:
You'll need to compare with a small tolerance for error:
if (std::abs(dvcx-dvx) < tolerance && std::abs(dvcy-dvy) < tolerance)
{
// the point is (more or less) on the line!
}
最艰难的部分是选择宽容。如果你不能接受任何错误,那么你需要使用的东西比固定precision浮点值等 - 可能是整数,计算重新安排,以避免分裂和其他不准确的操作。
The hard part is choosing that tolerance. If you can't accept any errors, then you'll need to use something other than fixed-precision floating point values - perhaps integers, with the calculations rearranged to avoid division and other inexact operations.
在任何情况下,你可以做到这一点更简单地说,如果没有一个像平方根任何东西。你想看看这两个矢量平行;它们是如果向量积为零或,等价地,如果它们具有相等的切线。所以,你只需要
In any case, you can do this more simply, without anything like a square root. You want to find out if the two vectors are parallel; they are if the vector product is zero or, equivalently, if they have equal tangents. So you just need
if (vx * vcy == vy * vcx) // might still need a tolerance for floating-point
{
// the point is on the line!
}
如果你的输入都是整数,足够小,乘法不会溢出,那么就没有必要进行浮点运算都没有。
If your inputs are integers, small enough that the multiplication won't overflow, then there's no need for floating-point arithmetic at all.
这篇关于看看一个点位于一个行(矢量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!