// Recursive binary search root-finder // version of January 21st, 2003 - 21:30 // ---------------------------------------------------- // (c) Copyright 2003 Julian V. Noble. // // Permission is granted by the author to // // use this software for any application pro- // // vided this copyright notice is preserved. // // ---------------------------------------------------- #include #include double bin_root ( double, double, double, double (*pn) (double) ); double f1 ( double ); void initialize( double a, double b, double (*pn) (double) ); // global variables double ra, rb; int main(void) { typedef double (*PFI) ( double ); PFI n; // define a pointer to simple functions double a, b, eps, result; printf("What are a, b, and epsilon? "); scanf(" %le%le%le", &a, &b, &eps); printf( " %.10le\n %.10e\n %.10e\n", a, b, eps ) ; n = f1; initialize ( a, b, n ); result = bin_root( a, b, eps, n ); printf( " Root is %.10le\n", result ); return 0; } double f1 ( double x) { return x * exp (x) - 1; } void initialize( double a, double b, double (*pn) (double) ) { ra = (*pn) (a) ; rb = (*pn) (b) ; if ( ra * rb > 0 ) { printf( " Even number of roots\n"); abort(); } } double bin_root ( double a, double b, double eps, double (*pn) (double) ) { double c, rc ; c = 0.5 * ( a + b ) ; if ( fabs( a - b ) < eps ) { return c; } rc = (*pn) (c) ; if ( ra * rc > 0 ) { a = c; ra = rc; } else { b = c; rb = rc; } return bin_root( a, b, eps, pn ); }