我们在我的编程课上学习数值方法,介绍给我们的第一个算法是求根的二分法。这是我使用递归实现它的尝试:
#include <math.h>
#include <stdio.h>
#define tolerance 0.00001
double my_function(double z){
double answer = 5*pow(z,2) + 5*z - 2;
return answer;
}
double bisection(double (*fxn)(double),double a, double b){
double m = ((a+b)/2);
if (fabs(b-a) < tolerance){
double root = a;
printf("value of a is %lf\n",root);
return a;
}
else if (fxn(m) > 0){
b = m;
}
else if (fxn(m) < 0){
a = m;
}
bisection(my_function, a, b);
}
int main(){
double g = 0.01;
double z = 1;
double x = bisection(my_function,g,z);
printf("root is %lf\n",x);
return 0;
}
这是输出:
value of a is 0.306225
root is nan
根是正确的(稍微偏离,但在容差范围内),但在返回值和打印它之间的某个地方,它以某种方式变成了 NaN。我难住了。我究竟做错了什么?