fork(7) download
  1. #include <iostream>
  2. using namespace std;
  3. // calculate the vertex of a parabola given three points
  4. // https://stackoverflow.com/q/717762/16582
  5.  
  6. // @AZDean implementation with given x values
  7.  
  8. void CalcParabolaVertex(int x1, int y1, int x2, int y2, int x3, int y3, double& xv, double& yv)
  9. {
  10. double denom = (x1 - x2) * (x1 - x3) * (x2 - x3);
  11. double A = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / denom;
  12. double B = (x3*x3 * (y1 - y2) + x2*x2 * (y3 - y1) + x1*x1 * (y2 - y3)) / denom;
  13. double C = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + x1 * x2 * (x1 - x2) * y3) / denom;
  14.  
  15. xv = -B / (2*A);
  16. yv = C - B*B / (4*A);
  17. }
  18.  
  19. // @piSHOCK immplementation assuming regular x values ( wrong!!! )
  20.  
  21. void CalcParabolaVertex2( int y1, int y2, int y3, double& xv, double& yv)
  22. {
  23. double d1 = y1 - y2;
  24. double d2 = y1 - y3;
  25.  
  26. double a = -d1 + 0.5 * d2;
  27. double b = 2 * d1 - 0.5 * d2;
  28. double c = -y1;
  29.  
  30. xv = -0.5 * b / a;
  31. yv = c - 0.25 * b * b / a;
  32. }
  33.  
  34. // corrected immplementation assuming regular x values
  35.  
  36. void CalcParabolaVertex3( int y1, int y2, int y3, double& xv, double& yv)
  37. {
  38. double d1 = y1 - y2;
  39. double d2 = y1 - y3;
  40.  
  41. double a = d1 - 0.5 * d2;
  42. double b = -2 * d1 + 0.5 * d2;
  43. double c = y1;
  44.  
  45. xv = -0.5 * b / a;
  46. yv = c - 0.25 * b * b / a;
  47. }
  48.  
  49.  
  50. int main() {
  51. double xv, yv;
  52. CalcParabolaVertex( 0, 100, 1, 500, 2, 200, xv, yv );
  53. cout << xv <<" "<< yv << "\n";
  54. CalcParabolaVertex2( 100, 500, 200, xv, yv );
  55. cout << xv <<" "<< yv << "\n";
  56. CalcParabolaVertex3( 100, 500, 200, xv, yv );
  57. cout << xv <<" "<< yv << "\n";
  58. return 0;
  59. }
Success #stdin #stdout 0s 4392KB
stdin
Standard input is empty
stdout
1.07143 501.786
1.07143 -501.786
1.07143 501.786