c++ 一点到两点所成直线的距离

gjmwrych  于 2023-03-05  发布在  其他
关注(0)|答案(2)|浏览(162)

我试图在C++中求出从点3(newPoint)到点1(prevPoint)和点2(curPoint)形成的直线的垂直距离。
我以前用过这个公式,但现在经过反复检查,我怀疑我的程序的正确性。
编辑:所有点(prevPoint、curPoint、newPoint)都是Point类型

struct Point {
    string name;
    int x;
    int y;
    bool visited;
};

double d = distance(prevPoint, curPoint);
double dx = (curPoint.x - prevPoint.x) / d;
double dy = (curPoint.y - prevPoint.y) / d;
double distToLine = abs((newPoint.x - prevPoint.x) * dy - (newPoint.y - prevPoint.y) * dx);

distance函数:

double distance(Point a, Point b) {
double dx = a.x - b.x;
double dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);}

我的代码是正确的吗?我需要一些正确的公式,如果它不是。谢谢!

xqnpmsa8

xqnpmsa81#

在您的情况下,formula将如下所示:

double d = distance(prevPoint, curPoint);
double area = abs((curPoint.x - prevPoint.x) * (newPoint.y - prevPoint.y) - (curPoint.y - prevPoint.y) * (newPoint.x - prevPoint.x));
double distToLine = area / d;
xxb16uws

xxb16uws2#

在下面的测试代码中,您的代码与我的代码具有相同的结果。

struct Point
{
    int x,y;
    Point( int x=0, int y=0 ) : x(x),y(y) {}
};

double MyMethod( Point prevPoint, Point curPoint, Point newPoint )
{
    //For simplicity, solve the problem in a coordinate system with the origin at prevPoint.
    Point B( curPoint.x-prevPoint.x, curPoint.y-prevPoint.y );
    Point C( newPoint.x-prevPoint.x, newPoint.y-prevPoint.y );

    // Considering the Vector P as
    //  P = t*B - C
    // where, t is scalar.
    //
    // What we need to do is find the value of t that minimizes the length of this P.
    // Objective Function is :
    //  Err(t) = (P dot P) = (t*Bx - Cx)^2 + (t*By - Cy)^2
    // And Then
    //  dErr(t)/dt  =  2*(t*Bx - Cx)Bx + 2*(t*By - Cy)By = 0
    // So
    //  t = (CxBx + CyBy) / (BxBx + ByBy)
    double t = ( C.x*B.x + C.y*B.y ) / double(B.x*B.x + B.y*B.y);

    // Now the distance we want to obtain is length of P (with the calculated t value).
    double Px = t*B.x - C.x;
    double Py = t*B.y - C.y;
    return sqrt( Px*Px + Py*Py );
}

namespace YourCode
{
    double distance(Point a, Point b)
    {
        double dx = a.x - b.x;
        double dy = a.y - b.y;
        return sqrt(dx * dx + dy * dy);
    }

    double YourMethod( Point prevPoint, Point curPoint, Point newPoint )
    {
        double d = distance(prevPoint, curPoint);
        double dx = (curPoint.x - prevPoint.x) / d;
        double dy = (curPoint.y - prevPoint.y) / d;
        double distToLine = abs((newPoint.x - prevPoint.x) * dy - (newPoint.y - prevPoint.y) * dx);
        return distToLine;
    }
}

int main(int argc, char *argv[])
{
    Point A( 3,10 );
    Point B( -5, 22 );
    Point C( 1,4 );

    std::cout << YourCode::YourMethod(A,B,C) << std::endl;
    std::cout << MyMethod(A,B,C) << std::endl;
    
    return 0;
}

相关问题