Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //---------------------------------------------------------------------------
- // solve cubic equation x^3 + a*x^2 + b*x + c
- // x - array of size 3
- // In case 3 real roots: => x[0], x[1], x[2], return 3
- // 2 real roots: x[0], x[1], return 2
- // 1 real root : x[0], x[1] ± i*x[2], return 1
- unsigned int solveP3(double *x,double a,double b,double c) {
- double a2 = a*a;
- double q = (a2 - 3*b)/9;
- double r = (a*(2*a2-9*b) + 27*c)/54;
- double r2 = r*r;
- double q3 = q*q*q;
- double A,B;
- if(r2<q3)
- {
- double t=r/sqrt(q3);
- if( t<-1) t=-1;
- if( t> 1) t= 1;
- t=acos(t);
- a/=3; q=-2*sqrt(q);
- x[0]=q*cos(t/3)-a;
- x[1]=q*cos((t+M_2PI)/3)-a;
- x[2]=q*cos((t-M_2PI)/3)-a;
- return 3;
- }
- else
- {
- A =-pow(fabs(r)+sqrt(r2-q3),1./3);
- if( r<0 ) A=-A;
- B = (0==A ? 0 : q/A);
- a/=3;
- x[0] =(A+B)-a;
- x[1] =-0.5*(A+B)-a;
- x[2] = 0.5*sqrt(3.)*(A-B);
- if(fabs(x[2])<eps) { x[2]=x[1]; return 2; }
- return 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement