我遇到了C ++ Polynomial类的问题,我无法找到解决方案。
我试图以这种方式推导出一个理性的函数:
z=dnum.derive();
cout<<"Derive Num: "<<z<<endl;
y=dden.derive();
cout<<"Derive Den: "<<y<<endl;
t=z*dden;
cout<<"NumAdd1: "<<t<<endl;
s=y*dnum;
cout<<"NumAdd2: "<<s<<endl;
dnum=t-s;
cout<<"New NUM: "<<dnum<<endl;
t=dden*dden;
dden=t;
cout<<"New DEN: "<<dden<<endl;
结果如下:
Original Num: 3.30688e-05 x^5 +0.000992063 x^4 +0.0138889 x^3 +0.111111 x^2 +0.5 x +1
Original Den: -3.30688e-05 x^5 +0.000992063 x^4 -0.0138889 x^3 +0.111111 x^2 -0.5 x +1
Derive Num: 0.000165344 x^4 +0.00396825 x^3 +0.0416667 x^2 +0.222222 x +0.5
Derive Den: -0.000165344 x^4 +0.00396825 x^3 -0.0416667 x^2 +0.222222 x -0.5
NumAdd1: -5.46772e-09 x^9 +3.28063e-08 x^8 +2.62451e-07 x^7 -2.75573e-06 x^6 -1.65344e-05 x^5 +0.000220459 x^4 +0.000881834 x^3 -0.0138889 x^2 -0.0277778 x +0.5
NumAdd2: -5.46772e-09 x^9 -3.28063e-08 x^8 +2.62451e-07 x^7 +2.75573e-06 x^6 -1.65344e-05 x^5 -0.000220459 x^4 +0.000881834 x^3 +0.0138889 x^2 -0.0277778 x -0.5
New NUM: 6.56127e-08 x^8 -8.13575e-19 x^7 -5.51146e-06 x^6 -2.7349e-17 x^5 +0.000440917 x^4 +4.996e-16 x^3 -0.0277778 x^2 -5.32907e-15 x +1
New DEN: 1.09354e-09 x^10 -6.56127e-08 x^9 +1.90277e-06 x^8 -3.49059e-05 x^7 +0.000446429 x^6 -0.00407848 x^5 +0.0262346 x^4 -0.111111 x^3 +0.25 x^2
导数的分子似乎是正确的,但分母不是因为没有低于2的单项式,而例如,应该有“+1”。
我认为operator*
的重载有问题(但它适用于分子)
Polynomial Polynomial::operator*(const Polynomial fact)const {
double *new_coeff;
int degree;
degree = deg + fact.deg;
new_coeff= new double[degree+1];
for(int i=0;i<=degree;i++) new_coeff[i]=0.0;
for(int i=0;i<=deg;i++){
for(int j=0;j<=fact.deg;j++){
if((coeff[i]!=0) && (fact.coeff[j]!=0)){
new_coeff[i+j] += coeff[i]*fact.coeff[j];
}
}
}
return Polynomial(degree,new_coeff);
}
或operator=
Polynomial & Polynomial::operator= ( const Polynomial &poly )
{
if ( this == &poly ) return ( *this );
else{
deg=poly.getdegree();
coeff= new double[deg+1];
for (int i=0; i <= deg; i++)
coeff[i] = poly.coeff[i];
}
return ( *this );
}
你有什么建议吗?
P.S。如果我的问题有问题,请原谅我......这是我在这里的第一篇文章。