我如何在 C++ 中使用此函数原型实现二分方法
double p1::root(double (*pf)(double k), int a, int b, double e)
我不知道如何去做,我知道我必须循环来精确定位中点,
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);
}
然后在 main 中我有这个
double (*pf)(double k);
pf = &p1::test_function;
//double result = p1::root(pf, a, b, e);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许数值食谱会给你一个想法。提示:它是递归的。
Maybe Numerical Recipes will give you an idea. Hint: it's recursive.