This is following the question I asked in this thread : Link error missing vtable
I defined a class 'function' and two others classes 'polynomial' and 'affine' that inherit from 'function'.
class function {
public:
function(){};
virtual function* clone()const=0;
virtual float operator()(float x)const=0; //gives the image of a number by the function
virtual function* derivative()const=0;
virtual float inverse(float y)const=0;
virtual ~function(){}
};
class polynomial : public function {
protected:
int degree;
private:
float *coefficient;
public:
polynomial(int d);
virtual~polynomial();
virtual function* clone()const;
int get_degree()const;
float operator[](int i)const; //reads coefficient number i
float& operator[](int i); //updates coefficient number i
virtual float operator()(float x)const;
virtual function* derivative()const;
virtual float inverse(float y)const;
};
class affine : public polynomial {
int a;
int b;
//ax+b
public:
affine(int d,float a_, float b_);
function* clone()const;
float operator()(float x)const;
function* derivative()const;
float inverse(float y)const;
~affine(){}
};
Method inverse in polyomial does not seem to work fine. It is based on the Newton method applied to the function x->f(x)-y for fixed y (the element for which we're computing the inverse) and the current polynomial f.
float polynomial::inverse(float y)const
{
int i=0;
float x0=1;
function* deriv=derivative();
float x1=x0+(y-operator()(x0))/(deriv->operator()(x0));
while(i<=100 && abs(x1-x0)>1e-5)
{
x0=x1;
x1=x0+(y-operator()(x0))/(deriv->operator()(x0));
i++;
}
if(abs(x1-x0)<=1e-5)
{
//delete deriv; //I get memory problems when I uncomment this line
return x1;
}
else
{
cout<<"Maximum iteration reached in polynomial method 'inverse'"<<endl;
//delete deriv; //same here
return -1;
}
}
double polynomial::operator()(double x)const
{
double value=0;
for(int i=0;i<=degree;i++) value+=coefficient[i]*pow(x,i);
return value;
}
polynomial* polynomial::derivative()const
{
if(degree==0)
{
return new affine(0,0,0);
}
polynomial* deriv=new polynomial(degree-1);
for(int i=0;i<degree;i++)
deriv[i]=(i+1)*coefficient[i+1];
return deriv;
}
I test this method with p:x->x^3 :
#include "function.h"
int main(int argc, const char * argv[])
{
polynomial p(3);
for(int i=0;i<=2;i++) p[i]=0;
p[3]=1;
cout<<"27^(1/3)="<<p.inverse(27);
return 0;
}
This script outputs 27^(1/3)=Maximum iteration reached in polynomial method 'inverse'
-1
even if I put 10,000 instead of 100. I've read some articles on the internet and it seems that it's a common way to compute the inverse.
Well, the problem was in method 'derivative'. Instead of using the 'operator[]' that I redefined, I used '->coefficient[]' and the main script worked fine for
p.inverse(27)
(only 14 iterations). I just replacedderiv[i]=(i+1)*coefficient[i+1];
withderiv->coefficient[i]=(i+1)*coefficient[i+1];