/* * 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(FILE **, int *); /* Set up output files for saving the answer */ static double absval(double); /* return absolute value of a number */ static double G(double ); /* function g */ int main() { double TOL, P0, P; int I, NO, FLAG, OK; char AA; FILE *OUP[1]; P0 = 1.5; // init. guess TOL = 1.0e-14; // tolerance for |p-p0| NO = 200; // max. number of iterations OUTPUT(OUP, &FLAG); /* STEP 1 */ I = 1; /* STEP 2 */ OK = true; while(I<=NO && OK) { /* STEP 3 */ /* compute P(I) */ P = G(P0); if (FLAG == 2) fprintf(*OUP, "%3d %15.8e\n", I, P); /* STEP 4 */ if (absval(P-P0) < TOL) { /* procedure completed successfully */ fprintf(*OUP, "\nApproximate solution P = %12.8f\n", P); fprintf(*OUP, "Number of iterations = %3d", I); fprintf(*OUP, " Tolerance = %14.8e\n",TOL); fprintf(*OUP, "|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 */ fprintf(*OUP, "\nIteration number %3d", NO); fprintf(*OUP, " gave approximation %12.8f\n", P); fprintf(*OUP, "not within tolerance %14.8e\n",TOL); } fclose(*OUP); 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(FILE **OUP, int *FLAG) { char NAME[30]; printf("Select output destination\n"); printf("1. Screen\n"); printf("2. Text file\n"); printf("Enter 1 or 2: "); scanf("%d", FLAG); if (*FLAG == 2) { printf("Input the file name in the form - drive:name.ext\n"); printf("For example: A:OUTPUT.DTA\n"); scanf("%s", NAME); *OUP = fopen(NAME, "w"); } else *OUP = stdout; 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); fprintf(*OUP, "FIXED-POINT METHOD\n"); if (*FLAG == 2) fprintf(*OUP, " I P\n"); } /* Absolute Value Function */ static double absval(double val) { if (val >= 0) return val; else return -val; }