how do i implement the bisection method using this function prototype in C++
double p1::root(double (*pf)(double k), int a, int b, double e)
im not sure how to go about it, i understand that i have to loop that pinpoints the midpoint and such
double p1::root(double (*pf)(double k),开发者_运维百科 int a, int b, double e) {
// void nrerror(char error_text[]);
int j;
float dx, f, fmid, xmid, rtb;
f = (*pf)(a);
fmid = (*pf)(b);
//if (f*fmid >= 0.0) nrerror("root must be bracketed for bisection in rtbis")\
;
rtb = f < 0.0 ? (dx=b-a,a) : (dx=a-b,b);
for(j = 1;j <40; j++) {
fmid = (*pf)(xmid = rtb+(dx *= .5));
if (fmid <= 0.0) rtb = xmid;
if (fabs(dx) < e || fmid == 0.0) return rtb;
}
// nrerror("too many bisections in rtbis");
return 0.0;
}
double p1::test_function(double k) {
return (pow(k, 3) -2);
}
then in main i have this
double (*pf)(double k);
pf = &p1::test_function;
//double result = p1::root(pf, a, b, e);
Maybe Numerical Recipes will give you an idea. Hint: it's recursive.
精彩评论