/* * FIXED-POINT ALGORITHM 2.2 * * To find a solution to p = g(p) given an * initial approximation p0 * This code is to solve Illustration problem on Page 61 of the textbook. * Formulation (d) is used. * * INPUT: initial approximation; tolerance TOL; * maximum number of iterations NO. * * OUTPUT: approximate solution p or * a message that the method fails. */ #include #include #include #define true 1 #define false 0 static void OUTPUT(int *); /* Set up output files for saving the answer */ static double G(double ); /* function g */ using namespace std; int main() { double TOL, P0, P; int I, NO, FLAG, OK; char AA; P0 = 1.5; // init. guess TOL = 1.0e-14; // tolerance for |p-p0| NO = 200; // max. number of iterations OUTPUT(&FLAG); /* STEP 1 */ I = 1; /* STEP 2 */ OK = true; while(I<=NO && OK) { /* STEP 3 */ /* compute P(I) */ P = G(P0); if (FLAG == 2) printf("%3d %15.8e\n", I, P); /* STEP 4 */ if (fabs(P-P0) < TOL) { /* procedure completed successfully */ printf("\nApproximate solution P = %12.8f\n", P); printf("Number of iterations = %3d", I); printf(" Tolerance = %14.8e\n",TOL); printf("|p-p0| = %14.8e\n", fabs(P-P0)); OK = false; } else { /* STEP 5 */ I++; /* STEP 6 */ /* update P0 */ P0 = P; } } if (true == OK) { /* STEP 7 */ /* procedure completed unsuccessfully */ printf("\nIteration number %3d", NO); printf(" gave approximation %12.8f\n", P); printf("not within tolerance %14.8e\n",TOL); } return 1; } /* Change function G for a new problem */ static double G(double X) { double g; g = sqrt(10.0 / (4.0 + X)); return g; } static void OUTPUT(int *FLAG) { char NAME[30]; printf("Select amount of output\n"); printf("1. Answer only\n"); printf("2. All intermeditate approximations\n"); printf("Enter 1 or 2: "); scanf("%d", FLAG); printf("FIXED-POINT METHOD\n"); if (*FLAG == 2) printf(" I P\n"); }