//http://www.timestocome.com //linda cobb //winter 98-99 //bisection method for finding the roots of an equation //**** caution //algorithm fails if more than one root and brackets are //symmetric.. //added in hack to correct this error corrected algorithm //finds real roots if they exist. even if there are two //roots bracketed area //no longer fails on functions such as 2x^2 +3x +1 btwn +-9 #include #include extern double function(double x); double bisection(double x1, double x2, double error) { printf("\n l %lf, r %lf", x1, x2);getchar(); printf("\n f(l) %lf, f(r) %lf", function(x1), function(x2)); if(sqrt(function(x1)*function(x1)) <= error){ return(x1); } if(function(x1)*function((x1+x2)/2.0) < 0){ //root bracketed here bisection(x1, ((x1+x2)/2.0), error); }else{ if(sqrt((x1-x2)*(x1-x2)) <= error/10.0){ //prevents core dumps when stack full printf("stuck in corner"); bisection(-x2, x1/2.0, error); } else{ bisection(((x2+x1)/2.0), x2, error); } } }