> bisect := proc()
local f, a, b, t, eps, itr;
printf("Bisection
method for solving f(x)=0.\n");
printf("Enter f(x):\n");
f := unapply( scanf("%a")[1], x ); #Look up "unapply"!
# Equivalent to
# f := scanf("%a")[1]; f := unapply(f,x);
printf("Enter initial a,b st. f(a)*f(b)<0:\n");
a := scanf("%f")[1];
b := scanf("%f")[1];
if f(a)*f(b) >=0 then
printf("f(%f)=%f,
f(%f)=%f. Try again!\n\n",a,f(a),b,f(b));
RETURN(bisect()); #Look up
"RETURN"!
fi;
eps :=1.0*10^(-7); #tolerance
itr := 0; #initial
number of iterations
do #iterations
t := (a+b)/2;
itr := itr + 1;
printf("itr%2d: f(%12.8f)=%12.8f\n",t,f(t));
#Convergence criterion:
if abs(f(t))< eps or b-a< eps then
printf("Approx soln x=%10.8f, f(x)=%10.8f\n",t,f(t));
RETURN(); #alternative exit, or, you can
move printing statement
#out of do loop and put "break" here
instead as shown in class
fi;
if f(a)*f(t) < 0 then b:= t;
elif f(t)*f(b) < 0 then a:=t;
fi;
od;
end: