一元三次方程-盛金公式求解
阿新 • • 發佈:2019-01-23
原理參考-百度百科(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
//cubicSolute.cpp#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; };
#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