/* * NEWTON-RAPHSON ALGORITHM 2.3 * * To find a solution to f(x) = 0 given an * initial approximation p0: * * INPUT: initial approximation p0; tolerance TOL; * maximum number of iterations NO. * * OUTPUT: approximate solution p or a message of failure */ #include #include #include #define true 1 #define false 0 #define PI 3.1415926535897932384626433832795 static double absval(double); static double F(double); static double FP(double); static void INPUT(int *, double *, double *, int *); static void OUTPUT(FILE **, int *); int main() { double TOL,P0,D,F0,FP0; int OK,I,NO,FLAG; FILE *OUP[1]; P0 = PI/4.0; TOL = 1.0e-13; NO = 200; OUTPUT(OUP, &FLAG); F0 = F(P0); /* STEP 1 */ I = 1; OK = true; /* STEP 2 */ while ((I<=NO) && true == OK) { /* STEP 3 */ /* compute P(I) */ FP0 = FP(P0); D = F0/FP0; /* STEP 6 */ P0 = P0 - D; F0 = F(P0); if (FLAG == 2) fprintf(*OUP,"%3d %14.8e %14.7e\n",I,P0,F0); /* STEP 4 */ if (absval(D) < TOL) { /* procedure completed successfully */ fprintf(*OUP,"\nNewton's method successed\n"); fprintf(*OUP,"\nApproximate solution = %.10e\n",P0); fprintf(*OUP,"with F(P) = %.10e\n",F0); fprintf(*OUP,"Number of iterations = %d\n",I); fprintf(*OUP,"Tolerance = %.10e\n",TOL); OK = false; } /* STEP 5 */ else I++; } if (true == OK) { /* STEP 7 */ /* procedure completed unsuccessfully */ fprintf(*OUP,"\nNewton's method failed\n"); fprintf(*OUP,"\nIteration number %d",NO); fprintf(*OUP," gave approximation %.10e\n",P0); fprintf(*OUP,"with F(P) = %.10e not within tolerance %.10e\n",F0,TOL); } fclose(*OUP); return 0; } /* Change functions F and FP for a new problem */ static double F(double X) { double f; f = cos(X) - X; return f; } /* FP is the derivative of F */ static double FP(double X) { double fp; fp = -sin(X) - 1; return fp; } 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,"Newtons Method\n"); if (*FLAG == 2) fprintf(*OUP, " I P F(P)\n"); } /* Absolute Value Function */ static double absval(double val) { if (val >= 0) return val; else return -val; }