解一元三次方程

· · 个人记录

公式是百度百科上抄的

计算方程 ax^3+bx^2+cx+d=0 的解(盛金公式)

double A = b*b-3*a*c;
double B = b*c-9*a*d;
double C = c*c-3*b*d;
double check = B*B-4*A*C;
if(A == 0 && B == 0) {
    cout << -c/b;
} else if(check > 0) {
    double y1 = A*b+3*a*((-B+sqrt(B*B-4*A*C))/2);
    double y2 = A*b+3*a*((-B-sqrt(B*B-4*A*C))/2);
    cout << (-b-(cbrt(y1)+cbrt(y2)))/(3*a);
} else if(check == 0) {
    double K = b/a;
    cout << (-b/a)+K << endl << -K/2;
} else {
    double T = (2*A*b-3*a*B)/(2*sqrt(pow(A,3)));
    double theta = acos(T);
    cout << (-b-(2*sqrt(A)*cos(theta/3)))/(3*a) << endl;
    cout << (-b+sqrt(A)*(cos(theta/3+sqrt(3)*sin(theta/3))))/(3*a) << endl;
    cout << (-b+sqrt(A)*(cos(theta/3-sqrt(3)*sin(theta/3))))/(3*a) << endl;
}