There is still a big problem with our root-finding implementation: we must
mindlessly evaluate the same three statements over and over again, and we must
decide when to stop. Fortunately, it is easy to ask Maple to take over both of
these tasks for us. Let's rewrite our implementation with a loop.
We'll begin once again by initializing f, pos, and neg.
| f := x -> cos(x) - x; |
| pos := 0.0; |
| neg := 1.0; |
Each of these statements needs to be evaluated only once.
Next, we must repeatedly evaluate the final three statements until we get close
to an answer. How should we define ``close''?
Click here for the answer
Here is a loop that repeatedly evaluates the three last statements in our
implementation until the difference between pos and neg becomes
acceptably small:
| while (abs(pos - neg) >= 1e-6) do
ave := (pos + neg) / 2.0;
val := f(ave);
if (val < 0)
then neg := ave;
else pos := ave;
fi;
od; |
This graphically shows the operation of the loop. As val tends toward
zero, ave tends toward the root.
Joseph L. Zachary
Hamlet Project
Department of Computer Science
University of Utah