我有很多平行线段,例如 L1(P1, P2) 和 L2(P3, P4)。 点具有每个 x 和 y 坐标。 这些平行线段的角度在 0-180 度之间变化。
如何在 C++ 中有效地找到这些线段之间的垂直空间?
最佳答案
两条平行线之间的距离将是第一条(无限)线与第二条线上任意点(例如 P3)之间的距离。由于您使用的是坐标,因此使用公式的 vector 表示比尝试将线表示为方程更方便。使用该表示,在 2d 中,此距离由 |(P3 - P1) dot ( norm ( P2 - P1 ))|
给出,其中 norm
是垂直于 P2 - P1
:
另请注意,在 2d 中,垂直于 vector (x, y)
的垂线很容易由 (-y, x)
给出。因此:
class GeometryUtilities
{
public:
GeometryUtilities();
~GeometryUtilities();
static double LinePointDistance2D(double lineP1X, double lineP1Y, double lineP2X, double lineP2Y, double pointX, double pointY);
static void Perpendicular2D(double x, double y, double &outX, double &outY);
static double Length2D(double x, double y);
};
double GeometryUtilities::LinePointDistance2D(double lineP1X, double lineP1Y, double lineP2X, double lineP2Y, double pointX, double pointY)
{
double vecx = lineP2X - lineP1X;
double vecy = lineP2Y - lineP1Y;
double lineLen = Length2D(vecx, vecy);
if (lineLen == 0.0) // Replace with appropriate epsilon
{
return Length2D(pointX - lineP1X, pointY - lineP1Y);
}
double normx, normy;
Perpendicular2D(vecx/lineLen, vecy / lineLen, normx, normy);
double dot = ((pointX - lineP1X) * normx + (pointY - lineP1Y) * normy); // Compute dot product (P3 - P1) dot( norm ( P2 - P1 ))
return abs(dot);
}
void GeometryUtilities::Perpendicular2D(double x, double y, double &outX, double &outY)
{
outX = -y;
outY = x;
}
double GeometryUtilities::Length2D(double x, double y)
{
return sqrt(x*x + y*y);
}
在生产中,您可能希望引入某种 Point
类,这将大大美化此 API,但是由于未显示,我编写的代码完全使用 double 值。
关于c++ - 如何找到两条平行线段之间的垂直距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28810760/