/* * SECANT ALGORITHM 2.4 * * To find a solution to the equation f(x) = 0 * given initial approximations p0 and p1: * * INPUT: initial approximation p0, p1; tolerance TOL; * maximum number of iterations N0. * * OUTPUT: approximate solution p or * a message that the algorithm fails. * */ #include #include #include #define true 1 #define false 0 #define PI 3.1415926535897932384626433832795 static double F(double); static void OUTPUT(int *); int main() { double P0,F0,P1,F1,P,FP,TOL; int I,NO,OK,FLAG; OK = true; P0 = 0.5; P1 = PI/4.0; TOL = 1.0e-7; NO = 200; OUTPUT(&FLAG); /* STEP 1 */ I = 2; F0 = F(P0); F1 = F(P1); OK = true; /* STEP 2 */ while ((I<=NO) && true == OK) { /* STEP 3 */ /* compute P(I) */ P = P1 - F1 * (P1 - P0) / (F1 - F0); /* STEP 4 */ FP = F(P); if (FLAG == 2) printf("%3d %15.8e %15.8e \n",I,P,FP); if (fabs(P - P1) < TOL) { /* procedure completed successfully */ printf("\nSecant method succeeded\n"); printf("Approximate solution P = %12.8f\n",P); printf("with F(P) = %12.8f\n",FP); printf("Number of iterations = %3d",I); printf(" Tolerance = %14.8e\n",TOL); OK = false; } else { /* STEP 5 */ I++; /* STEP 6 */ /* update P0, F0, P1, F1 */ P0 = P1; F0 = F1; P1 = P; F1 = FP; } } if (OK) { /* STEP 7 */ /* procedure completed unsuccessfully */ printf("Secant method failed\n"); printf("\nIteration number %3d",NO); printf(" gave approximation %12.8f\n",P); printf("F(P) = %12.8f not within tolerance : %15.8e\n",FP,TOL); } return 0; } /* Change function F for a new problem */ static double F(double X) { double f; f = cos(X) - X; return f; } 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("Secant Method\n"); if (*FLAG == 2) printf(" I P F(P)\n"); }