废话不多说,直接上代码:
#include <stdio.h>
#include <math.h>
double func(double x) {
return cos(x) - x*x*x;
}
/* a,b: endpoints of an interval where we search
e: half of upper bound for relative error
m: maximal number of iteration
*/
double FalsiMethod(double (*f)(double), double a, double b, double e, int m) {
double c, fc;
int n, side = 0;
/* starting values at endpoints of interval */
double fa = f(a);
double fb = f(b);
for (n = 0; n < m; n++) {
c = (fa * b - fb * a) / (fa - fb);
if (fabs(b - a) < e * fabs(b + a))
break;
fc = f(c);
if (fc * fb > 0) {
/* fc and fb have same sign, copy c to b */
b = c; fb = fc;
if (side == -1)
fa /= 2;
side = -1;
} else if (fa * fc > 0) {
/* fc and fa have same sign, copy c to a */
a = c; fa = fc;
if (side == +1)
fb /= 2;
side = +1;
} else {
/* fc * f_ very small (looks like zero) */
break;
}
}
return c;
}
int main(void) {
printf("%0.15f\n", FalsiMethod(&func, 0, 1, 5E-15, 100));
return 0;
}
参考链接:
- https://en.wikipedia.org/wiki/Regula_falsi