/* Bisection method
Implements the bisection method for finding roots.
Solves f(x) = 0, given an initial interval [a,b] such that f has
differing signs at the endpoints. Quits when f((a+b)/2) is close
enough to zero. Function f must be continuous. It must be implemented
as double f(double) in this file or elsewhere.
An example implementation with f(x) = x^3 - x - 1.
Suitable input values for a and b are -2.0 and 2.0.
The algorithm bisects the initial interval successively, until
the value of f at the midpoint differs from zero by less than
TOLERANCE, which defaults to .0001.
The program reports the current interval, and the values of f at the
endpoints at each stage.
In Linux (with the gcc compiler) use this command to compile the program
cc -o bisec bisec.c -lm
and run the program using the command
./bisec
In WINDOWS (with the tcc compiler) use this command to compile the program
tcc bisec.c
and run the program using the command
bisec
*/
#include
#include
main()
{
double a,b,mid;
double f_a,f_b,f_mid;
double error_bound,tolerance;
int iteration;
/* declare the function f(x) */
double fof();
printf("enter value for point a: ");
scanf("%lf",&a);
printf("\nenter value for point b: ");
scanf("%lf",&b);
mid = .5 * (b+a);
f_a = fof(a);
f_b = fof(b);
/* Check values [a,b] such that f has
differing signs at the endpoints */
if (f_a * f_b > 0.0) {
printf("bad initial points -- may not bracket root\n");
exit(-1);
}
f_mid = fof(mid);
iteration = 0;
tolerance = .0001;
error_bound = .5 * (b - a);
printf("i a b mid f_of_a f_of_b f_mid err_bound\n");
printf("%d %lf %lf %lf %lf %lf %lf %lf\n",
iteration,a,b,mid,f_a,f_b,f_mid,error_bound);
while ((error_bound > tolerance) && (iteration < 20)){
if (f_a * f_mid < 0.0) {
b = mid;
f_b = f_mid;
mid = .5 * (a+mid);
}
else {
a = mid;
f_a = f_mid;
mid = .5 * (b+mid);
}
f_mid = fof(mid);
error_bound = .5 * (b - a);
iteration++;
printf("%d %lf %lf %lf %lf %lf %lf %lf\n",iteration,a,b,mid,f_a,f_b,f_mid,
error_bound);
}
printf("Solution is x = %lf function = %lf iterations = %d error_bound = %lf\n\n\n",
mid,f_mid,iteration,error_bound);
}
double fof(x)
double x;
{
/* This is the function */
return(x*x + 4*x + 4.);
}