Programming in C

(Barry) #1
Functions Calling Functions Calling... 131

floating arithmetic. In accordance with this rule, the division of the absolute value of
–6.0 by 4 produces a result of 1.5.
Now that you’ve defined a function that computes the absolute value of a number,
you can use it in any future programs in which you might need such a calculation per-
formed. In fact, the next program (Program 8.8) is just such an example.


Functions Calling Functions Calling...


With calculators as commonplace as watches, it’s usually no big deal to find the square
root of a particular number should the need arise. But years ago, students were taught
manual techniques that could be used to arrive at an approximation of the square root of
a number. One such approximation method that lends itself most readily to solution by a
computer is known as the Newton-Raphson Iteration Technique. In Program 8.8, you write
a square root function that uses this technique to arrive at an approximation of the
square root of a number.
The Newton-Raphson method can be easily described as follows.You begin by
selecting a “guess” at the square root of the number.The closer that this guess is to the
actual square root, the fewer the number of calculations that have to be performed to
arrive at the square root. For the sake of argument, however, assume that you are not
very good at guessing and, therefore, always make an initial guess of 1.
The number whose square root you want to obtain is divided by the initial guess and
is then added to the value of guess.This intermediate result is then divided by 2.The
result of this division becomes the new guess for another go-around with the formula.
That is, the number whose square root you are calculating is divided by this new guess,
added into this new guess, and then divided by 2.This result then becomes the new
guess and another iteration is performed.
Because you don’t want to continue this iterative process forever, you need some way
of knowing when to stop. Because the successive guesses that are derived by repeated
evaluation of the formula get closer and closer to the true value of the square root, you
can set a limit that you can use for deciding when to terminate the process.The differ-
ence between the square of the guess and the number itself can then be compared
against this limit—usually called epsilon(ε). If the difference is less than ε, the desired
accuracy for the square root has been obtained and the iterative process can be
terminated.
This procedure can be expressed in terms of an algorithm, as shown next.
Newton-Raphson Method to Compute the Square Root of x
Step 1: Set the value of guessto 1.
Step 2: If |guess^2 - x| < ε,proceed to step 4.
Step 3: Set the value of guessto (x/ guess + guess) / 2and return to
step 2.
Step 4: The guessis the approximation of the square root.

Free download pdf