> restart; > # 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 > alg023 := proc() local F, FP, OK, P0, TOL, NO, FLAG, NAME, OUP, F0, I, FP0, D; > printf(`This is Newton's Method\n`); > printf(`Input the function F(x) in terms of x\n`); > printf(`For example: cos(x)\n`); > F := scanf(`%a`)[1]; > FP := unapply(diff(F,x),x); > F := unapply(F,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, `Newton's Method\n`); > if FLAG = 2 then > fprintf(OUP, ` I P F(P)\n`); > fi; > F0 := F(P0); > # Step 1 > I := 1; > OK := TRUE; > # Step 2 > while I <= NO and OK = TRUE do > # Step 3 > # Compute P(I) > FP0 := FP(P0); > D := F0/FP0; > # Step 6 > P0 := P0 - D; > F0 := F(P0); > if FLAG = 2 then > fprintf(OUP,`%3d %14.8e %14.7e\n`,I,P0,F0); > fi; > # Step 4 > if abs(D) < TOL then > # Procedure completed successfully > fprintf(OUP,`\nApproximate solution = %12.8f\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 := I+1; > fi; > od; > if OK = TRUE then > # Step 7 > # Procedure completed unsuccessfully > 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); > fi; > if OUP <> default then > fclose(OUP): > printf(`Output file %s created successfully`,NAME); > fi; > fi; > RETURN(0); > end; > alg023();