37.3 怎么解一元四次方程?
用“费拉里”方法求解:将四次方程化为两个二次方程,然后求解二次方程。
----------------------------------------------main.cpp ------------------------------------------
main.cpp
float* roots_quartic_equation(float a, float b, float c, float d, float e) {
//the first element is the number of the real roots, and other elements are the real roots.
//Ferrari's solution.
float *roots = new float[5];
if (a == 0) {
roots = roots_cubic_equation(b, c, d, e);
}
else {
float b1 = b/a;
float c1 = c/a;
float d1 = d/a;
float e1 = e/a;
if ((b1 == 0) && (c1 == 0) && (d1 == 0)) {
//in this special case, such as a=1, b=c=d=0, e=-1, the roots should be +1 and -1
if (e1 > 0) {
roots[0] = 0.0;
}
else {
roots[1] = sqrt(sqrt(-e1));
roots[2] = -sqrt(sqrt(-e1));
roots[0] = 2.0;
}
}
else {
float *roots_y = new float[4];
roots_y = roots_cubic_equation(-1.0, c1, 4*e1-b1*d1, d1*d1+e1*b1*b1-4*e1*c1);
float y = roots_y[1];
float B1, B2, C1, C2;
if (b1*b1-4*c1+4*y == 0) {
B1 = b/2;
B2 = b/2;
C1 = y/2;
C2 = y/2;
}
else {
B1 = b/2 - sqrt(b1*b1-4*c1+4*y)/2;
B2 = b/2 + sqrt(b1*b1-4*c1+4*y)/2;
C1 = y/2 - (b1*y -2*d1)/(2*sqrt(b1*b1-4*c1+4*y));
C2 = y/2 + (b1*y -2*d1)/(2*sqrt(b1*b1-4*c1+4*y));
}
float *roots_x1 = new float[3];
float *roots_x2 = new float[3];
roots_x1 = roots_quadratic_equation(1.0, B1, C1);
roots_x2 = roots_quadratic_equation(1.0, B2, C2);
if (roots_x1[0] != 0) {
for (int i=1; i<roots_x1[0]+1; i++) {
roots[i] = roots_x1[i];
}
}
if (roots_x2[0] != 0) {
int roots_x1_number = int(roots_x1[0]);
for (int j=1; j<roots_x2[0]+1; j++) {
roots[roots_x1_number+j] =roots_x2[j];
}
}
roots[0] = roots_x1[0] + roots_x2[0];
}
}
return roots;
}
int main(){
float *r;
// r = roots_quartic_equation(1.0, -4.0, 6.0, -4.0, 1.0);//1,1,1,1
// r = roots_quartic_equation(1.0, -10.0, 35.0, -50.0, 24.0);//1,2,3,4
// r = roots_quartic_equation(1.0, 0.0, -5.0, 0.0, 4.0);//1,-1,2,-2
// r = roots_quartic_equation(1.0, 0.0, 0.0, 0.0, 0.0);//0,0,0,0
r = roots_quartic_equation(1.0, 0.0, 0.0, 0.0, -16.0);//-2,2
for (int i=0; i<(r[0]+1); i++) {
std::cout << "r[" << i << "]=" << r[i] << endl;
}
}
另一种解一元四次方程的方法:“笛卡尔”方法(即“待定系数法”)参考“问题四十”中的“第六步”
版权声明:本文为libing_zeng原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。