> restart; > # STEFFENSEN'S ALGORITHM 2.6 > # > # To find a solution to g(x) = x > # given an initial approximation p0: > # > # INPUT: initial approximation p0; tolerance TOL; > # maximum number of iterations N0. > # > # OUTPUT: approximate solution p or > # a message that the method fails. > alg026 := proc() local G, OK, P0, TOL, NO, FLAG, NAME, OUP, I, P1, P2, D, P; > printf(`This is Steffensens Method.\n`); > printf(`Input the function G(x) in terms of x\n`); > printf(`For example: cos(x)\n`); > G := scanf(`%a`)[1]; > G := unapply(G,x); > OK := FALSE; > printf(`Input initial approximation\n`); > P0 := scanf(`%f`)[1]; > 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, `STEFFENSEN'S METHOD\n`); > if FLAG = 2 then > fprintf(OUP, ` I P\n`); > fi; > # Step 1 > I := 1; > OK := TRUE; > # Step 2 > while I <= NO and OK = TRUE do > # Step 3 > # Compute P(1) with superscript (I-1) > P1 := G(P0); > # Compute P(2) with superscript (I-1) > P2 := G(P1); > if abs(P2-2*P1+P0) < 1.0e-20 then > FLAG := 1; > D := 10; > fprintf(OUP,`Denominator = 0, method fails\n`); > fprintf(OUP,`best possible is P2(%2d) = %15.8f\n`,I,P2); > OK := FALSE; > else > D := (P1-P0)*(P1-P0)/(P2-2*P1+P0); > fi; > # Compute P(0) with superscript (I) > P := P0-D; > if FLAG = 2 then > fprintf(OUP, `%3d%15.8e\n`, I, P); > fi; > # Step 4 > if abs(D) < TOL then > # Procedure completed successfully > fprintf(OUP, `\nApproximate solution := %12.8f\n`, P); > fprintf(OUP, `Number of iterations := %3d`, I); > fprintf(OUP, ` Tolerance := %15.8e\n`,TOL); > OK := FALSE; > else > # Step 5 > I := I+1; > # Step 6 > # Update P0 > P0 := P; > fi; > od; > if OK = TRUE then > # Step 7 > # Procedure completed unsuccessfully > fprintf(OUP, `\nIteration number %3d`, NO); > fprintf(OUP, ` gave approximation %12.8f\n`, P); > fprintf(OUP, `not within tolerance %14e\n`,TOL); > fi; > if OUP <> default then > fclose(OUP): > printf(`Output file %s created successfully`,NAME); > fi; > fi; > RETURN(0); > end; > alg026();