Advertisement
Guest User

Cubic equation solver in C

a guest
Mar 31st, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. //---------------------------------------------------------------------------
  2. // solve cubic equation x^3 + a*x^2 + b*x + c
  3. // x - array of size 3
  4. // In case 3 real roots: => x[0], x[1], x[2], return 3
  5. // 2 real roots: x[0], x[1], return 2
  6. // 1 real root : x[0], x[1] ± i*x[2], return 1
  7. unsigned int solveP3(double *x,double a,double b,double c) {
  8. double a2 = a*a;
  9. double q = (a2 - 3*b)/9;
  10. double r = (a*(2*a2-9*b) + 27*c)/54;
  11. double r2 = r*r;
  12. double q3 = q*q*q;
  13. double A,B;
  14. if(r2<q3)
  15. {
  16. double t=r/sqrt(q3);
  17. if( t<-1) t=-1;
  18. if( t> 1) t= 1;
  19. t=acos(t);
  20. a/=3; q=-2*sqrt(q);
  21. x[0]=q*cos(t/3)-a;
  22. x[1]=q*cos((t+M_2PI)/3)-a;
  23. x[2]=q*cos((t-M_2PI)/3)-a;
  24. return 3;
  25. }
  26. else
  27. {
  28. A =-pow(fabs(r)+sqrt(r2-q3),1./3);
  29. if( r<0 ) A=-A;
  30. B = (0==A ? 0 : q/A);
  31.  
  32. a/=3;
  33. x[0] =(A+B)-a;
  34. x[1] =-0.5*(A+B)-a;
  35. x[2] = 0.5*sqrt(3.)*(A-B);
  36. if(fabs(x[2])<eps) { x[2]=x[1]; return 2; }
  37.  
  38. return 1;
  39. }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement