## CS 1401 Assignment #5

Date Assigned: Monday, October 1, or Tuesday, October 2, 2007.

Due Date: Monday, October 8, or Tuesday, October 9, 2007, before the beginning of your lab section.

Objective: The main objective of this assignment is to practice using loops.

Programming assignment: Let us simulate the way a computer performs arithmetic operations. In the computer, addition and multiplication are directly hardware supported, but division a/b is performed as a * (1/b), where 1/b is computed by using a complex iterative procedure. For a real number b close to 1.0, the starting approximation a(0) to 1/b is 1. Once we know an i-th approximation a(i), we compute the next approximation a(i+1) as a(i) + d, where

d = a(i) - a(i) * b * a(i).

Iterations stop when the absolute value |d| of the difference d is smaller than a pre-defined small value epsilon.

Write a program that, given a real number b between 0.8 and 1.2, uses the above algorithm to return its inverse 1/b. Your program should display an appropriate error message is a user tries to input a number which is outside the interval [0.8, 1.2].

Example: Suppose that we want to compute 1/0.8 with the accuracy epsilon = 0.01. As the initial approximation, we take a(0) = 1.0. On the next iteration, we take

d = a(0) - a(0) * b * a(0) = 1 - 1 * 0.8 * 1 = 1 - 0.8 = 0.2.

Then, a(1) = a(0) + d = 1 + 0.2 = 1.2. After that, we compute

d = a(1) - a(1) * b * a(1) = 1.2 - 1.2 * 0.8 * 1.2 = 1.2 - 1.152 = 0.048.

Then, a(2) = a(1) + d = 1.2 + 0.048 = 1.248. After that, we compute

d = a(2) - a(2) * b * a(2) = 1.248 - 1.248 * 0.8 * 1.248 = 0.00199...

This difference is smaller than epsilon = 0.01, so we stop, and return 1.248 as the result. (The exact value of 1/0.8 is 1.25.)

Homework assignment: on a separate sheet of paper, solve Ex. 6, 10, 18, and 24 at the end of Chapter 5.

Deliverables: as instructed by your TA.