I have the following class defined in code
When I try to build the project I get an error in the calculate_root function.
It's telling me to replace F with &froot::F and to replace G with &froot::G, but this doesn't work.
I can kind of see why there is a problem, in that I'm trying to call find_root by passing a class member when it is expecting a pointer to a function
How should I change the syntax of the find_root, and root, declaration so that it will accept functions which are declared inside the same class?
Thanks for your help.
Any sugestions greatly appreciated.
Code:
//header file
class froot{
public:
void calculate_root(int i);
double F(double x);
double G(double x);
double find_root(double (*g)(double),double x1,double x2,int &depth);
double root(double x1,double x2,double (*g)(double),double f1,double f2,int &depth);
private:
};
//Source File
double froot::find_root(double (*g)(double), double x1, double x2, int &depth)
{
double f1=(*g)(x1);
double f2=(*g)(x2);
if(f1*f2>0.0){
cout<<"ERROR in find_root(): values at end-points have same sign"<<endl;
exit(EXIT_FAILURE);
return 0;
}
else if(x2-x1>0.0)
return root(x1,x2,*g,f1,f2,depth);
else
return root(x2,x1,*g,f2,f1,depth);
}
double froot::root(double x1, double x2, double (*g)(double), double f1, double f2, int &depth)
{
//This function calculates the root of a function using the bisection method
const int max_depth=1000;
const double x_limit=1e-12;
double estimated_root;
double x_mid=(x1+x2)*0.5;
if(x2-x1<=x_limit)
estimated_root=x_mid;
else if(++depth>max_depth){
cout<<"WARNING: Maximum limit of "<<max_depth<<" bisections reached in root().\n";
estimated_root=x_mid;
}
else{
double f_mid=(*g)(x_mid);
if(f_mid==0.0){
//Zero at x_mid
estimated_root=x_mid;
}
else if((*g)(x1)*f_mid<0.0){
//Zero in first segment
estimated_root=root(x1,x_mid,*g,f1,f_mid,depth);
}
else{
//Zero in second segment
estimated_root=root(x_mid,x2,*g,f_mid,f2,depth);
}
}
return estimated_root;
}
double froot::F(double x)
{
return exp(x)+pow(2.0,-x)+2.0*cos(x)-6.0;
}
double froot::G(double x)
{
return x-cos(x);
}
void froot::calculate_root(int i)
{
int depth;
double sol;
if(i==1){
depth=0;
sol=find_root(F,1.0,2.0,depth);
}
else{
depth=0;
sol=find_root(G,0.0,PI/2,depth);
}
}
It's telling me to replace F with &froot::F and to replace G with &froot::G, but this doesn't work.
I can kind of see why there is a problem, in that I'm trying to call find_root by passing a class member when it is expecting a pointer to a function
How should I change the syntax of the find_root, and root, declaration so that it will accept functions which are declared inside the same class?
Thanks for your help.
Any sugestions greatly appreciated.
Comment