I am working on bisection method to calculate interest rate in C++,but there is some problems with my codes:the root is always 7.62939E-06.Please help me figure out why my program always fails.
The header file: (hasRoot is a class which has only one member function f:fv+pv*pow(1+rate,nPer)+pmt/rate*(pow(1+rate,nPer)-1)).
Code:
#include "hasRoot.h"class rootFinder{
private:
double tol;
/*the allowed difference between the calculated root and the actual root.*/
int MaxIter; //the maximum iteration times
public:
rootFinder(double a=0.00001,int b=20000){
tol=a;
MaxIter=b;
}
double functionsolver(hasRoot&);
};
The implementation part:
Code:
#include "rootFinder.h"
#include <cmath>
double rootFinder::functionsolver(hasRoot& objecttobesolved){
int counter=1; //Counts the iteration times.
double left=0;
double right=1;
for (;counter<=MaxIter;counter++){
double mid=(left+right)/2.0;
if( fabs(objecttobesolved.f(mid))<=tol || (right-left)<tol){
return mid;
break;
}
if( objecttobesolved.f(mid)*objecttobesolved.f(right)>0)
right=mid;
if( objecttobesolved.f(mid)*objecttobesolved.f(right)<0)
left=mid;
}
}
Everytime I run it,no matter what are the values of pv(present value),fv(future value),pmt(payment) and nPer(number of Periods),I always get the same result 7.62939E-06.