(* * BISECTON ALGORITHM 2.1 * * To find a solution to f(x)=0 given the continuous function * f on the interval [a,b], where f(a) and f(b) have * opposite signs * * INPUT: endpoints a,b; tolerance TOL; * maximum number of iterations NO. * * OUTPUT: approximate solution p or a message that the * algorithm fails. *) TEMP = Input["This is the Bisection Method.\n Input the function F(X) in terms of x.\n"]; F[x_] := Evaluate[TEMP]; OK = 0; While[OK == 0, A = Input["Input endpoint a\n"]; B = Input["Input endpoint b\n"]; If[A > B, X = A; A = B; B = X; ]; If[A == B, Input["A cannot equal B.\n Enter 1 [enter] to continue\n"], FA = F[A]; FB = F[B]; If[FA*FB > 0, Input["F(A) and F(B) have the same sign.\n Enter 1 [enter] to continue\n"], OK = 1; ]; ]; ]; 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, NO = Input["Input maximum number of iterations\n no decimal points\n"]; If[NO<=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"; ]; Write[OUP,"Bisection Method\n"]; FLAG = Input["Select amount of output.\n Enter '1' for answer only\n Enter '2' for all intermediate approximations\n"]; If[FLAG == 2, Write[OUP," i P F(P)\n"]; ]; (*STEP 1*) i = 1; (*STEP 2*) OK = 1; While[i <= NO && OK == 1, (*STEP 3, compute P(i)*) CC = (B-A)/2; P = N[A+CC]; (*STEP 4*) FP = F[P]; If[FLAG == 2, Write[OUP,"",i," ",SetPrecision[P,10]," ",SetPrecision[FP,10]]; ]; If[(Abs[FP]<10^-20) || (CC 0.00), A = P; FA = FP, B = P; FB = FP; ]; ]; ]; If[OK == 1, (*STEP 7, procedure completed successfully *) Write[OUP,"Iteration number ",NO]; Write[OUP,"gave approximation ",SetPrecision[P,10]]; Write[OUP,"F(P)= ",SetPrecision[FP,10]," not within tolerance: \n",SetPrecision[TOL,10]]; ]; If[OUP == "OutputStream[",NAME," 3]", Print["Output file: ",NAME," created successfully\n"]; Close[OUP] ]; ]; Quit[];