> restart; > # 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. > alg024 := proc() local F, OK, P0, P1, TOL, NO, FLAG, NAME, OUP, F0, I, F1, P, FP; > printf(`This is the Secant Method\n`); > printf(`Input the function F(x) in terms of x\n`); > printf(`For example: cos(x)\n`); > F := scanf(`%a`)[1]; > F := unapply(F,x); > OK := FALSE; > while OK = FALSE do > printf(`Input initial approximations P0 and P1 separated by a blank\n`); > P0 := scanf(`%f`)[1]; > P1 := scanf(`%f`)[1]; > if P0 = P1 then > printf(`P0 cannot equal P1\n`); > else > OK := TRUE; > fi; > od; > OK := FALSE; > while OK = FALSE do > printf(`Input tolerance\n`); > TOL := scanf(`%f`)[1]; > if TOL <= 0 then > printf(`Tolerance must be positive\n`); > else > OK := TRUE; > fi; > od; > OK := FALSE; > while OK = FALSE do > printf(`Input maximum number of iterations - no decimal point\n`); > NO := scanf(`%d`)[1]; > if NO <= 0 then > printf(`Must be positive integer\n`); > else > OK := TRUE; > fi; > od; > if OK = TRUE then > printf(`Select output destination\n`); > printf(`1. Screen\n`); > printf(`2. Text file\n`); > printf(`Enter 1 or 2\n`); > FLAG := scanf(`%d`)[1]; > if FLAG = 2 then > printf(`Input the file name in the form - drive:\\name.ext\n`); > printf(`For example: A:\\OUTPUT.DTA\n`); > NAME := scanf(`%s`)[1]; > OUP := fopen(NAME,WRITE,TEXT); > else > OUP := default; > fi; > printf(`Select amount of output\n`); > printf(`1. Answer only\n`); > printf(`2. All intermediate approximations\n`); > printf(`Enter 1 or 2\n`); > FLAG := scanf(`%d`)[1]; > fprintf(OUP, `Secant Method\n`); > if FLAG = 2 then > fprintf(OUP, ` I P F(P)\n`); > fi; > # Step 1 > I := 2; > F0 := F(P0); > F1 := F(P1); > OK := TRUE; > # Step 2 > while I <= NO and OK = TRUE do > # Step 3 > # Compute P(I) > P := P1-F1*(P1-P0)/(F1-F0); > FP := F(P); > if FLAG = 2 then > fprintf(OUP,`%3d %15.8e %15.8e\n`,I,P,FP); > fi; > # Step 4 > if abs(P-P1) < TOL then > # Procedure completed successfully > fprintf(OUP,`\nApproximate solution P = %12.8f\n`,P); > fprintf(OUP,`with F(P) = %12.8f\n`,FP); > fprintf(OUP,`Number of iterations = %d\n`,I); > fprintf(OUP,`Tolerance = %14.8e\n`,TOL); > OK := FALSE; > # Step 5 > else > I := I+1; > # Step 6 > # Update P0, F0, P1, F1 > P0 := P1; > F0 := F1; > P1 := P; > F1 := FP; > fi; > od; > if OK = TRUE then > # Step 7 > # Procedure completed unsuccessfully > fprintf(OUP,`\nIteration number %d`,NO); > fprintf(OUP,` gave approximation %12.8f\n`,P); > fprintf(OUP,`with F(P) = %12.8f not within tolerance %15.8e\n`,FP,TOL); > fi; > if OUP <> default then > fclose(OUP): > printf(`Output file %s created successfully`,NAME); > fi; > fi; > RETURN(0); > end; > alg024();