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