CS 110: Introduction to Computing with Java

Lab 4

Pre-Lab

Do the following exercises before coming to lab.

1. What is printed by the following Java statements:

int i = 2, j = 3, k = 6;

if (i < k / j)

System.out.println(“Good”);

else

System.out.println(“Bad”);

System.out.println(“Done”);

if (i == k % j)

System.out.println(“True”);

else

if (i / k == k % j)

System.out.println(“Almost true”);

else

System.out.println(“False”);

switch (i * (j + k))

{

case 0:

System.out.println(“Zero”);

break;

case 1:

System.out.println(“One”);

break;

case 2:

System.out.println(“Two”);

break;

default:

System.out.println(“None of the above”);

break;

}

2. What is wrong with this set of Java statements and how would you fix it?

import java.util.Scanner;

. . .

Scanner scan = new Scanner(System.in);

if (scan.next() == “Hello”)

System.out.println(“Hello to you”);

else

System.out.println(“Goodbye”);

3. What is wrong with this set of Java statements and how would you fix it?

if (i < j)

System.out.println(“i is smaller”);

count++;

else

System.out.println(“i is larger or equal”);

count--;

4. What is wrong with this set of Java statements and how would you fix it?

// total all positive numbers entered, stop on entry of -1

final int SENTINEL_VALUE = -1;

int total = 0;

while (true)

{

int value = scan.nextInt();

if (value == SENTINEL_VALUE)

break;

else

total += value;

}

5. Rewrite the code in problem 4 using a “do . . . while” statement instead of a “while” statement.

You will not be allowed to work on the lab if you have not already completed these tasks.

Lab

Introduction

One of the things that computers can do well is implement algorithms that would be tedious for manual calculations. One general problem in mathematics is solving:

f(x) = 0 for all values of x (called roots) that make the equation true

When the function f(x) is a quadratic polynomial, we learned a formula in algebra that we can use to solve that equation for zero, one or two roots. We will use that formula in Project 1. However, when the function f(x) is not a quadratic polynomial, the problem can be solved using an iterative method (or algorithm) that would be tedious to do manually, but is easy for a computer to do. The method is called Newton’s method.

In Newton’s method, you provide an initial guess for a root and the method iterates to keeps improving the guess until the value of the guess becomes close enough to the value of a root that you can stop the iterations. Note that if there is more than one root, you may need to run the algorithm many times with different initial guesses to get the values of all the roots. (You actually may not be sure that you have gotten all the roots unless you know how many roots the equation is supposed to have.)

Basically, Newton’s method uses some geometry to improve the guess at a root. (There is also a way to look at this algorithm from the point of view of Calculus, but we choose to use the geometry explanation.) See the Diagram Newton Diagram.jpg that goes with the following explanation of the steps:

1. Make your first guess at a root (x = 0 is a valid guess)

2. Calculate f(x) at your guess (x = 0) which we assume is = 1

3. Calculate the slope of f(x) at your guess (x = 0) which we assume is 1/2

4. Your second guess is -2

5. Calculate f(x) at your guess (x = -2) which we assume is - 1/2

6. Calculate the slope of f(x) at your guess (x = -2) which we assume is 2

7. Your third guess is -1.75

8. Do your see that the guesses are geometrically converging on the true root where f(x) crosses the x-axis?

However, there are some problems with Newton’s Method. It may fail to converge in a reasonable number of iterations (such as 10) with a given function and a given initial guess. It also may fail due to a possible divide by zero in the algorithm (when the slope is zero). While your code is iterating it must check for these conditions. If they occur your code must stop the iterations and inform the user that the algorithm has failed to calculate a root and why.

You can download a set of .java files from Lab4.zip. The Java code provides a Class named Function that has a method named f that takes a double argument and returns the value of f(x). It also has a method named fprime that takes a double argument for x and returns the value of the slope of f(x).

The Java code provides a Newton class that implements the Newton’s method algorithm, but does not check for the conditions that can cause the algorithm to fail. Build your Dr Java project file using these files, save the two java source files in your project, and compile the project as in all previous labs.

The code that you have been provided executes Newton’s Method, but it fails to check for the two error conditions that are mentioned above. Run the main method and enter the following values as an initial guess. You should get the results indicated.

- 0.5 Root is: 5.292219477318755E-10 (essentially == 0.0) after 3 iterations.

+ 1.5 Root is: 1.732050807684724 (essentially == the square root of 3) after 4 iterations.

1.0 Root is: Infinity after 1 iterations. NOTE: fprime(1.0) is 0.0 and Newton’s method fails to converge.

100000000.0 Root is: 1.7320508075692247 (essentially == the square root of 3) after 43 iterations. NOTE: Made too many iterations.

In the main method in class Newton, there is a place inside the while loop where a comment line says

// you need to add your code here

Since these checks are for error conditions, it is usually considered acceptable to “break” out of the loop when they occur rather than check for these conditions in the “while (condition)”.

You must add a check for the max number of iterations being exceeded. There is an integer symbolic constant available for you to use. If your code finds that the max number of iterations has been exceeded, it must print “Loop terminated for max iterations.” and break out of the loop.

You must also add a check for the value of fprime being zero. If your code finds that fprime is zero, it must print “Loop terminated on fprime equals 0.” and break out of the loop.

Your finished program should produce the following results for the two error conditions:

1.0 Loop terminated on fprime equals 0. ? Due to your added code

Root is: 1.0 after 0 iterations.

100000000.0 Loop terminated for max iterations. ? Due to your added code

Root is: 97656.25000341334 after 10 iterations.

Run your program with an appropriate initial value to get it to produce each of the possible roots. Try values within the range of -2.0 to +2.0.

Purpose

This lab gives you some experience writing conditional statements inside a loop, another skill that you will use again in programs that you write.

Activities

Before you leave, have your TA check off that you completed the lab. Make sure that you save a copy of your work. You may complete the code on your own. Turn in your lab report to the TA during the week following the exam.

Lab Report

Write a document describing your experiences. Except for the graph, your lab report must be printed (not handwritten).

Answer the following questions related to what you did in this week’s lab:

1. Read the code in the class Function and draw a graph of the functions f(x) and fprime(x).

2. Based on the graph, how many roots are there and what are their correct values?.

3. Are the values produced by Newton’s Method exactly correct answers for the roots? Why or why not?

Note: You should work alone on the lab report.