原理参考-百度百科(http://baike.baidu.com/link?url=eA-bEvbcOBM2XmA4rzIG-lgci4MQdQcr7lCzCHBW-qG-qcPaDNovXp_jYxS2FUjlrOh1obH_D3Yv6ME2JYOxPyCgKhHIaXCHe-k9e69_c2tUxMTY90Z5-Oh9pZ-8LRf_)
先说一下中间出现的问题,开三次方的时候不能直接pow(x,1.0/3.0); 要分x大于零小于零,pow只接受大于零的参数。
另外,由于工程中只考虑实数,这里复数没有实现。
//cubicSolute.h
#pragma once
class cubicSolute
{
public:
cubicSolute(void);
~cubicSolute(void);
void setCoefficient(double a,double b,double c,double d)//设方程系数
{
this->a =a;
this->b =b;
this->c =c;
this->d =d;
}
void judge();
double getX1(){return X1;}
double getX2(){return X2;}
double getX3(){return X3;}
private:
double a,b,c,d;
double A,B,C;
double delt;//判别式
double X1,X2,X3;
};
//cubicSolute.cpp
#include "cubicSolute.h"
#include <math.h>
cubicSolute::cubicSolute(void)
{
}
cubicSolute::~cubicSolute(void)
{
}
//Δ根的判别式
void cubicSolute::judge()
{
A = pow(b,2)-3*a*c;
B = b*c-9*a*d;
C = pow(c,2)-3*b*d;
delt = pow(B,2)-4*A*C;
//当A=B=0时,公式1.+定理6
if ((A==0&&B==0)||(delt==0&&A==0))
{
X1 = -b/(3*a);
X2 = X1;
X3 = X1;
}
//Δ=B2-4AC>0时,公式2
if (delt>0)
{
double Y1 = A*b+3*a*((-B+pow(delt,0.5))/2);
double Y2 = A*b+3*a*((-B-pow(delt,0.5))/2);
//解决负数开三方出问题
double Y1_three,Y2_three;
if (Y1<0)
Y1_three = - pow(-Y1,1.0/3.0);
else
Y1_three = pow(Y1,1.0/3.0);
if (Y2<0)
Y2_three = - pow(-Y2,1.0/3.0);
else
Y2_three = pow(Y2,1.0/3.0);
X1 = (-b-(Y1_three+Y2_three))/(3*a);
//X1,X2为复数,这里不需要,未实现。
}
//当Δ=B2-4AC=0时,公式3
if (delt==0&&(A!=0))
{
double K = B/A;
X1 = -b/a + K;
X2 = -K/2.0;
X3 = X2;
}
//当Δ=B2-4AC<0时,公式4
if (delt<0)
{
double T = (2*A*b-3*a*B)/(2*A*pow(A,0.5));//(A>0,-1<T<1)
double theita = acos(T);
X1 = (-b-2*pow(A,0.5)*cos(theita/3.0))/(3*a);
X2 = (-b+pow(A,0.5)*(cos(theita/3.0)+pow(3,0.5)*sin(theita/3.0)))/(3*a);
X3 = (-b+pow(A,0.5)*(cos(theita/3.0)-pow(3,0.5)*sin(theita/3.0)))/(3*a);
}
}
测试ok