How to calculate the vertex of a parabola given three points

后端 未结 8 1138
故里飘歌
故里飘歌 2020-11-30 03:11

I have three X/Y points that form a parabola. I simply need to calculate what the vertex of the parabola is that goes through these three points. Preferably a quick way as I

8条回答
  •  野性不改
    2020-11-30 04:14

    Running at https://ideone.com/y0SxKU

    #include 
    using namespace std;
    // calculate the vertex of a parabola given three points
    // https://stackoverflow.com/q/717762/16582
    
    // @AZDean implementation with given x values
    
    void CalcParabolaVertex(int x1, int y1, int x2, int y2, int x3, int y3, double& xv,  double& yv)
    {
        double denom = (x1 - x2) * (x1 - x3) * (x2 - x3);
        double A     = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / denom;
        double B     = (x3*x3 * (y1 - y2) + x2*x2 * (y3 - y1) + x1*x1 * (y2 - y3)) / denom;
        double C     = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + x1 * x2 * (x1 - x2) * y3) / denom;
    
        xv = -B / (2*A);
        yv = C - B*B / (4*A);
    }
    
    // @piSHOCK immplementation assuming regular x values ( wrong!!! )
    
    void CalcParabolaVertex2( int y1, int y2, int y3, double& xv,  double& yv)
    {
    double d1 = y1 - y2;
    double d2 = y1 - y3;
    
    double a =    -d1 + 0.5 * d2;
    double b = 2 * d1 - 0.5 * d2;
    double c = -y1;
    
    xv =    -0.5      * b / a;
    yv = c - 0.25 * b * b / a;  
    }
    
    // corrected immplementation assuming regular x values
    
    void CalcParabolaVertex3( int y1, int y2, int y3, double& xv,  double& yv)
    {
    double d1 = y1 - y2;
    double d2 = y1 - y3;
    
    double a = d1 - 0.5 * d2;
    double b = -2 * d1 + 0.5 * d2;
    double c = y1;
    
    xv =    -0.5      * b / a;
    yv = c - 0.25 * b * b / a;  
    }
    
    
    int main() {
        double xv, yv;
        CalcParabolaVertex( 0, 100, 1, 500, 2, 200, xv, yv );
        cout << xv <<" "<< yv << "\n";
        CalcParabolaVertex2( 100, 500, 200, xv, yv );
        cout << xv <<" "<< yv << "\n";
        CalcParabolaVertex3( 100, 500, 200, xv, yv );
        cout << xv <<" "<< yv << "\n";
        return 0;
    }
    

    I have added a couple of unit tests for negative going peaks: running live at https://ideone.com/WGK90S

提交回复
热议问题