# Some Cool programs using while and for loops

• Introduction

• In the webpage, I like to show you the power of the loop by solving 2 common Mathematical problems using a computer.

• We have learn enough Java programming to construct complicated and useful programs...

• Our own Function Class

• You have seen some Mathematical functions in the Math class (see: click here )

• We want to define our own functions; so we will use our own class called "MyFunction"

• We will have one single function f(x) in this class:

 ``` public class MyFunction { public static double f(double x) // Sample function { return (x * x - 3); // x2 - 3 } } ```

• We use static because the function f(x) operate on numbers which are not objects !

• Here is a program that reminds you how to use a static function:

 ``` public class TestProg { public static void main(String[] args) { double x; for ( x = 0.0; x < 10.5; x++ ) System.out.println("x = " + x + ", f(x) = " + MyFunction.f(x) ); } } ```

• We can change the function f(x) to an arbitrary function (we don't have to use x2 - 3)

Solving an equation with the computer

• Finding the root of a function

• Problem:

• Given a continuous function f(x)
• Given an interval (a, b) such that the sign of f(a) and f(b) are opposite.

• Determine a zero z of the function f(x) that lies in the interval (a, b), i.e.:

• f(z) = 0
• a   <   z   <   b

(NOTE: from calculus, because f(x) has opposite signs for x = a and x = b and f(x) is continuous, we know there is a zero in (a, b) !)

• The following is a numerical technique to find an approximate root of a function.

This technique is called the bisection technique

 The bisection technique ``` a = left point of interval b = right point of interval while ( width of the interval > ε ) { m = (a + b)/2.0; // midpoint of interval if ( f(m) has the same sign as f(b) ) { b = m; // Next search interval is ( a, (a+b)/2 ) } else { a = m; // Next search interval is ( (a+b)/2, b ) } } ```

• Here is a picture that shows what the bisection method is doing:

• In the left figure, the function value f(m) and f(b) have the same sign.

We can clearly see that the zero in this case must be in the interval ( a, (a+b)/2 )

By setting:

```	 b = m;
```
We change the search interval to (a, m) or (a, (a+b)/2) in the next iteration.

• In the right figure, the function value f(m) and f(b) have opposite signs.

We can clearly see that the zero in this case must be in the interval ( (a+b)/2, b )

By setting:

```         a = m;
```
We change the search interval to (a, m) or ((a+b)/2, b) in the next iteration.

• Packaging the Bisection algorithm in Java:

• We will have more mathematical tools like "solveEquation", so we put this method into a class called MathToolBox

• We will have only 1 method in the class for now, we will add more as we go...

• The one useful method that we develop finds the zero (root) of an equation, we will call this method solveEquation()

• What information will the method solveEquation() need to perform its task (= find zero of an equation):

• The function f(x) = 0
• An interval (a, b) that contains a zero (i.e., sign of f(a) and f(b) are opposite)

• How to provide the information to the method solveEquation()

• f(x): taken from method f(x) in the class MyFunction (see: click here )
• Interval (a, b): as parameters to solveEquation()
(in other words, solveEquation() is called as solveEquation(x, y) where x and y are 2 double values)

• The MathToolBox class with the solveEquation() method:

 ``` public class MathToolBox { public static double solveEquation(double a, double b) { double leftPoint, rightPoint, midPoint; // Interval points double y_leftPoint, y_rightPoint, y_midPoint; // Function values /* ------------------------------------------------------ Sanity check 1: b > a ------------------------------------------------------ */ if ( b < a ) { System.out.println("Error: illegal interval "); return(0); // We need to return something.... } /* ------------------------------------------------------ Sanity check 2: sign f(a) and f(b) must be different ------------------------------------------------------ */ if ( (MyFunction.f(a) > 0 && MyFunction.f(b) > 0) || (MyFunction.f(a) < 0 && MyFunction.f(b) < 0) ) { System.out.println("Error: interval may not contain a zero"); return(0); // We need to return something.... } /* --------------------------------------------------- The Bisection Algorithm --------------------------------------------------- */ leftPoint = a; // Initial interval is (a, b) rightPoint = b; while ( rightPoint - leftPoint > EPSILON ) // See note { midPoint = (leftPoint + rightPoint)/2.0; // Find the middle y_midPoint = MyFunction.f(midPoint); y_rightPoint = MyFunction.f(rightPoint); if ( (y_midPoint < 0 && y_rightPoint < 0) || (y_midPoint > 0 && y_rightPoint > 0) ) { rightPoint = midPoint; } else { leftPoint = midPoint; } } return (leftPoint + rightPoint)/2.0; } public static final double EPSILON = 0.000001; // Minimum accuracy } ```

• NOTE: (rightPoint - leftPoint) is the width of the interval that contains the zero of the function.

If the interval width is less that EPSILON, then the error of the solution cannot be more than EPSILON !

```
What does it mean for "rightPoint - leftPoint < EPSILON":

|<------  < EPSILON ----->|
-------+-------------------------+-------
leftPoint                rightPoint

An example will make it clear: take EPSILON = 0.001

-------+-------------------------+-------
leftPoint = 3.145        rightPoint = 3.146

Then 3.1455 is a good approximation of the solution
```

• Example Program: (Demo above code)

Finding definite integrals using the computer

• Finding the definite integral of a function

• Problem:

• Given a continuous function f(x)
• Given an interval (a, b)

• Determine the area under the graph of f(x) between x = a and x = b

NOTE: from calculus, this problem is also known as the definite integral:

• The following is a well-known numerical technique to find the definite integral of a function.

This technique is called the rectangle method:

1. Divide the interval (a, b) into n disjoint pieces, each of the same width.

2. Approximate the area under the function f(x) for each sub-interval by a rectangle whose:

• width (of the rectangle) is the width of the sub-interval (= (b-a)/n)
• height (of the rectangle) is the function value at the left point of the sub-interval (= f(leftPoint))

• The following diagram is a depiction of how rectangle method works, i.e., it show that we can use a series of (tiny) rectangles to approximate any definite integral:

• OK, we know what we need to do, and more importantly, the nature of the work is very repetitive - this kind of work is ideally suited for computers.

The following diagram shows use what (i.e., the steps) exactly is repeated:

Repeat these steps for each sub-interval (xi, xi+1):

1. Compute the area of the rectangle under graph f(x) - the area of this rectangle is equal to f(xi) (xi+1 - xi) - see figure.

2. Add this area to the total.

• Notice that (xi+1 - xi) is always the same (because each sub-interval is equal length)

So we can move (xi+1 - xi) outside the summation.

• Furthermore, we know the value of (xi+1 - xi) because the original interval has a length (b - a) and it is cut into n pieces.

So each sub-interval has a length of (b - a)/n !!!

• Packaging the Rectangle Rule algorithm in Java:

• We will call the method "rectangleRule", and we will add this method into the MathToolBox class.

• (So we will have 2 methods in the class !!!)

• What information will the method rectangleRule() need to perform its task (= find an approximation of a definite integral by cutting the interval up into n pieces):

• The function f(x) = 0
• An interval (a, b)
• The number of pieces to cut n

• How to provide the information to the method rectangleRule()

• f(x): taken from method f(x) in the class MyFunction (see: click here )
• Interval (a, b): as parameters to rectangleRule()
• n: also as a parameter to rectangleRule()

(in other words, rectangleRule() is called as rectangleRule(a, b, n) where a and b are 2 double values and n is an integer)

• The MathToolBox class with the rectangleRule() method added:

 ``` public class MathToolBox { public static double rectangleRule(double a, double b, int n) { double h; // Length of each sub-interval double x_i; int i; double integral; /* --------------------------------------------------- Sanity check: b > a --------------------------------------------------- */ if ( b < a ) { System.out.println("Error: illegal interval "); return(0); // We need to return something.... } /* --------------------------------------------------- The Rectangle Rule Algorithm --------------------------------------------------- */ h = (b-a)/n; integral = 0.0; x_i = a; // First sub-interval point for ( i = 1; i <= n; i++ ) { integral = integral + MyFunction.f(x_i) * h; // ^^^^^^^^^^^^^^^^^^^^^ Area of rectangle x_i = x_i + h; } return ( integral ); } /** * (NO CHANGES MADE TO solveEquation() !!!! */ public static double solveEquation(double a, double b, int n) { .... (unchanged !!) } public static final double EPSILON = 0.000001; // Minimum accuracy } ```

• Example Program: (Demo above code)