Discrete Mathematics for Computer Science

(Romina) #1
Program Correctness 59

RESULT: Approximation of v/-1

Root = 4
DecimalPlace Value = 1
for i = I to 8 do
DecimalPlace Value = DecimalPlace Value/ 10
/* Search for the digit at the decimal place.*/
Digit = 9
/* 9 is the largest possible value for Digit. *1
AddOn = Digit. DecimalPlace Value
while((Root + AddOn) • (Root + AddOn) > 17) do
1* Digit is too big, so try a smaller value. "1
Digit = Digit - 1
AddOn = Digit .DecimalPlaceValue
/* At the end of the while loop the next digit is found. */
Root = Root + AddOn
print Root

The code starts by approximating Vii by 4. The variable DecimalPlace Value is used

to keep track of which decimal digit is being added to the approximation. When i is equal
to n, DecimalPlaceValue will be equal to 10-n. The first value added to the previous ap-
proximation is Digit. 10-n where Digit is 9. The while loop sees if adding Digit. 10-n
gives a new value for the approximation by computing

(Root + Digit. 10-n)2 < 17

If the value of Digit gives

(Root+ Digit. 10-n)2 > 17

a new, smaller value of Digit is tried. At some point, Digit will take on a first value, say
Digitfirst, for which


(Root + Digitfirst. 10-n)2 < 17

The new approximation for Vii will be formed by adding Digitfirst 10'- to Root to form
the next approximation. The first iteration of the for loop gives the value 1 for Digitfir,.
Consequently,


Root = 4 + .10-1 = 4.1

for i = 1. Now, in the second iteration, Digitfist takes the value 2, so


Root = 4.1 + 2.10-2 = 4.12
Free download pdf