/* * BISECTION ALGORITHM 2.1 * * To find a solution to f(x) = 0 given the continuous function * f on the interval [A,B], where f(A) and f(B) have * opposite signs: * * THis code solves Example 1 on Page 50 of the book. * * INPUT: endpoints A,B; tolerance TOL; * maximum number of iterations NI. * * OUTPUT: approximate solution p or * a message that the algorithm fails. */ #include #include #include #include #define ZERO 1.0E-20 #define true 1 #define false 0 static double absval(double); /* return absolute value of a number */ static double Func(double); /* Compute f(x) */ static void OUTPUT(int *); /* Set up output files for saving the answer */ using namespace std; main() { double A,FA,B,FB,C,P,FP,TOL; // A, B are end points of the interval. // C is the length of the half interval. // P is the middle point of the interval. // TOL is the tolerance for the minimum of the length of the interval [A,B] int I,NI,OK,FLAG; // I is the counter of steps. // NI is the maximum number of iterations // Initialize the problem A = 1.0; B = 2.0; FA = Func(A); FB = Func(B); TOL = 1.0e-9; // Tolerance for specifying the minimum of the length of the interval [A, B] NI = 50; OUTPUT(&FLAG); /* STEP 1 */ I = 1; /* STEP 2 */ OK = true; while ((I<=NI) && OK) { /* STEP 3 */ /* compute P at the I's step */ C = (B - A) / 2.0; P = A + C; /* STEP 4 */ FP = Func(P); /* print out all intermeditate approximations */ if (FLAG == 2) cout<= 0) return val; else return -val; }