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.)


Solution:


import java.util.*;
import java.lang.Math.*;

public static void main(String [] args){
  //designing a tool to read from a keyboard
  Scanner keyboard = new Scanner(System.in);

  //asking the user to input a number and reading this number
  System.out.println("Please enter a real number between 0.8 and 1.2.");
  double b = keyboard.nextDouble();

  //asking the user to input the desired accuracy
  System.out.println("Please enter the desired accuracy.");
  double epsilon = keyboard.nextDouble();

  //declaring and initializing variables
  double a = 1.0;
  double d;

  if (!(0.8 <= b && b <= 1.2))
    {System.out.println("Your number is outside the interval [0.8,1.2], sorry.");}
  else
    {boolean done = false;
     while (!done)
       {d = a - a * b * a;
        if (Math.abs(d) < epsilon)
          {done = true;}
        else
          {a = a + d;}
       }
     System.out.println(a);
     }
   }

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.