gpt4 book ai didi

c++ - 如何找到两条平行线段之间的垂直距离?

转载 作者:搜寻专家 更新时间:2023-10-31 00:12:55 24 4
gpt4 key购买 nike

我有很多平行线段,例如 L1(P1, P2) 和 L2(P3, P4)。点具有每个 x 和 y 坐标。这些平行线段的角度在 0-180 度之间变化。

如何在 C++ 中有效地找到这些线段之间的垂直空间? Distance between two parallel line segments

最佳答案

两条平行线之间的距离将是第一条(无限)线与第二条线上任意点(例如 P3)之间的距离。由于您使用的是坐标,因此使用公式的 vector 表示比尝试将线表示为方程更方便。使用该表示,在 2d 中,此距离由 |(P3 - P1) dot ( norm ( P2 - P1 ))| 给出,其中 norm 是垂直于 P2 - P1:

enter image description here

另请注意,在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com