#include <iostream>
#include <math.h>
using namespace std;
class polynomial{
int degree;
float *coefs;
public:
polynomial(int d);
float operator()(float x);
void operator==(polynomial P);
polynomial operator^(int k);
float operator[](float x);
float *getcoefs();
};
polynomial::polynomial(int d){
int i;
degree=d;
if(d>=0){
coefs=(float *)malloc((d+1)*sizeof(float));
cout<<"Create a polynomial of degree "<<d<<"\n";
for (i=d;i>0;i--){
cout<<"The coefficient of x^"<<i<<" is : ";
cin>>coefs[i];
cout<<"\n";
}
cout<<"The constant is : ";
cin>>coefs[0];
cout<<"\n";
cout<<"The polynomial is created\n";
}
}
これは()演算子のオーバーロードであり、P(x)は多項式の値を返します。
float polynomial::operator()(float x){
float sum=0;
int i,kstart;
for(i=0;i<=degree;i++){
if(coefs[i]!=0){
kstart=i;
break;
}
}
for(i=kstart;i<=degree;i++){
sum+=coefs[i]*pow(x,i-kstart);
}
return sum;
}
これは、ある多項式の係数を別の多項式の係数にコピーする==のオーバーロードです。
void polynomial::operator==(polynomial P){
coefs=P.coefs;
}
これは^のオーバーロードであるため、P^kはPのk次導関数を返します。
polynomial polynomial::operator^(int k){
int i,j;
polynomial G(-1);
G.degree=this->degree;
G==(*this);
if(k>G.degree){
for(i=0;i<=G.degree;i++){
G.coefs[i]=0;
}
}
else{
for(i=0;i<k;i++){
G.coefs[i]=0;
for(j=i+1;j<=G.degree;j++){
G.coefs[j]*=(j-i);
}
}
}
return G;
}
float polynomial::operator[](float x){
return (x-(*this)(x)/(((*this)^1)(x)));
}
float *polynomial::getcoefs(){
return coefs;
}
int main(){
int i,d,maxiter,found;
float seed,x1,x2,e;
float *coefs;
cout<<"The polynomial's degree is : ";
cin>>d;
cout<<"\n";
polynomial P(d),temp(-1);
cout<<"-------Solve P(x)=0--------\n";
cout<<"Maxiterations = ";
cin>>maxiter;
cout<<"\n";
cout<<"Tolerance = ";
cin>>e;
cout<<"\n";
cout<<"Seed = ";
cin>>seed;
cout<<"\n";
found=0;
x1=seed;
for(i=0;i<maxiter;i++){
memcpy((void *)(&temp),(void *)(&P),sizeof(polynomial));
x2=P[x1];
if(fabs(x2-x1)<=e){
found=1;
break;
}
coefs=temp.getcoefs();
cout<<coefs[0]<<"\n";
cout<<coefs[1]<<"\n";
cout<<coefs[2]<<"\n";
x1=x2;
}
if(found==1){
cout<<"A possible solution is x = "<<x2<<"\n";
}
else{
cout<<"No solution found!\n";
}
system("PAUSE");
return EXIT_SUCCESS;
}
この問題は、次のテストラインで確認できます。
cout<<coefs[0]<<"\n";
cout<<coefs[1]<<"\n";
cout<<coefs[2]<<"\n";
係数は同じままである必要がありますが、今は変化します