(* * 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 n0. * * OUTPUT: approximate solution p or a message that the * method fails. *) TEMP = Input["This is Newton's Method.\n Input the function F(X) in terms of x.\n\n For example: Cos[x]\n"]; F[x_] := Evaluate[TEMP] DER = D[TEMP,x]; FP[x_] := Evaluate[DER] P0 = Input["Input initial approximation"]; OK = 0; While[OK == 0, TOL = Input["Input the tolerance\n"]; If[TOL <= 0, Input["Tolerance must be positive.\n Enter 1 [enter] to continue\n"], OK = 1; ]; ]; OK = 0; While[OK == 0, n0 = Input["Input maximum number of iterations\n no decimal points\n"]; If[n0 <= 0, Input["Must be a positive integer.\n Enter 1 [enter] to continue\n"], OK = 1; ]; ]; If[OK == 1, FLAG = Input["Select output destination\n 1. Screen\n 2. Text file\n Enter 1 or 2\n"]; If[FLAG == 2, NAME = InputString["Input the file name\n For example: output.dta\n"]; OUP = OpenWrite[NAME,FormatType->OutputForm], OUP = "stdout" ]; FLAG = Input["Select amount of output.\n Enter '1' for answer only\n Enter '2' for all intermediate approximations\n"]; Write[OUP,"Newton's Method\n"]; If[FLAG == 2, Write[OUP," i P F(P)\n"], ]; F0 = N[F[P0]]; (*STEP 1*) i = 1; OK = 1; (*STEP 2*) While[i <= n0 && OK == 1, (*STEP 3, Compute P(i)*) FP0 = N[FP[P0]]; d = F0/FP0; (*STEP 6*) P0 = P0-d; F0 = N[F[P0]]; If[FLAG == 2, Write[OUP,i," ",SetPrecision[P0,10]," ",SetPrecision[F0,10]] ]; (*STEP 4*) If[Abs[d] < TOL, (*Procedure completed successfully*) Write[OUP,"Approximate solution = \n",SetPrecision[P0,10]]; Write[OUP,"with F(P) = \n",SetPrecision[F0,10]]; Write[OUP,"Number of iterations = \n",i]; Write[OUP,"Tolerance = \n",SetPrecision[TOL,10]]; OK = 0, (*STEP 5*) i = i+1; ]; ]; If[OK == 1, (*STEP 7, Procedure completed unsuccessfully*) Write[OUP,"Iteration number ",n0]; Write[OUP,"gave approximation \n",SetPrecision[P0,10]]; Write[OUP,"with F(P) = ",SetPrecision[F0,10]]; Write[OUP," not within tolerance \n",SetPrecision[TOL,10]]; ]; If[OUP == "OutputStream[",NAME," 3]", Print["Output file: ",NAME," created successfully\n"]; Close[OUP]; ]; ]; Quit[];