// Bisect3.cc // Recursive function // Example: Find the point of zero by bisection // Version 3: func(x) and epsilon as parameters #include #include double f(const double x) // declaration and { return sin(x) - 0.5*x ; } // definition of function f(x) double g(const double x) // declaration and { return -(x-1.234567)*(x+0.987654) ; }// definition of function g(x) // declaration of Bisect3 double Bisect3(double (* const func)(double), const double a, const double b, const double eps=1e-6); main() { const double EPS = 1e-6; // accuracy constant double a,b,x0; cout << endl; cout << " Determine point of zero in [a,b] by bisection " << endl; cout << "f(a) > 0, a : "; cin >> a; cout << "f(b) < 0, b : "; cin >> b; cout << endl; x0 = Bisect3(f,a,b,EPS); // call recursive function with f // x0 = Bisect3(g,a,b,EPS); // call recursive function with g cout << endl << " point of zero = " << x0 << endl; cout << endl; } // --------------------------------------------------------------- // Recursive function Bisect3 // --------------------------------------------------------------- // definition of Bisect3 double Bisect3(double (* const func)(double), const double a, const double b, const double eps) { double x0, fc, c = (a+b)/2; fc = func(c); // calculate value of parameter function if ( fabs(fc) < eps ) { x0 = c; // end of recursion } else if ( fc > 0.0 ) { x0 = Bisect3(func,c,b,eps); // search in right intervall } else // i.e., fc < 0.0 { x0 = Bisect3(func,a,c,eps); // search in left intervall } return x0; // return the solution }