C++ main module for mmsd Package  1.0
MATH_CubicPolynom.hpp
Go to the documentation of this file.
1 #ifndef MATH_CubicPolynom_HPP
2 #define MATH_CubicPolynom_HPP
3 
5 
6 template<class T>
7 void MATH_CubicPolynom::solve(const tReal& a,const tReal& b,const tReal& c,const tReal& d,
8  int& n, T solutions[3]) {
9 
10  //ax^3+bx^2+cx+d=0
11  if (a==0) {
12  MATH_QuadraticPolynom::solve<T>(b,c,d,n,solutions);
13  return ;
14  }
15 
16  //X^3+pX+q=0
17  //X=x-dx
18  tReal dx=-b/(3*a);
19  tReal p=c/a-b*b/(3*a*a);
20  tReal q=(b/(27*a))*(2*b*b/(a*a)-9*c/a)+d/a;
21 
22  tReal delta=-(4*p*p*p+27*q*q);
23 
24  if (delta<0) {
25  delta=sqrt(-delta/27);
26  tReal u=(-q+delta)/2;
27  if (u>0) u=pow(u,1./3.);
28  else u=-pow(-u,1./3.);
29 
30  tReal v=(-q-delta)/2;
31  if (v>0) v=pow(v,1./3.);
32  else v=-pow(-v,1./3.);
33  n=1;
34  solutions[0]=(T)(u+v+dx);
35 
36  } else if (delta>0) {
37  n=3;
38  tReal theta=acos((-q/2)*sqrt(27/(-p*p*p)))/3.;
39  tReal r=2*sqrt(-p/3);
40  for (int k=0;k<3;k++) {
41  solutions[k]=(T) (r*cos(theta+2*k*M_PI/3)+dx);
42  }
43  if (solutions[0]>solutions[1]) std::swap(solutions[0],solutions[1]);
44  if (solutions[1]>solutions[2]) {
45  std::swap(solutions[1],solutions[2]);
46  if (solutions[0]>solutions[1]) std::swap(solutions[0],solutions[1]);
47  }
48 
49  } else {
50  if ((p==0) && (q==0)) {
51  n=1;
52  solutions[0]=(T) dx;
53  } else {
54  n=2;
55  solutions[0]=(T) dx+3*q/p;
56  solutions[1]=(T) dx-1.5*q/p;
57  if (solutions[0]>solutions[1]) std::swap(solutions[0],solutions[1]);
58  }
59  }
60 
61 }
62 
63 #endif
static void solve(const tReal &a, const tReal &b, const tReal &c, const tReal &d, int &n, T solutions[3])
Definition: MATH_CubicPolynom.hpp:7
#define tReal
Definition: types.h:18