点到两点连线的距离

问题描述 投票:0回答:2

我试图在 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);}

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

c++ distance
2个回答
3
投票

公式在您的情况下如下:

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;

0
投票

在下面的测试代码中,你的代码和我的结果一样。

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.