Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The...

53
Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy Numerical Analysis Copyright 1999, James M. Slack

Transcript of Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The...

Page 1: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem SolvingWith Java

Chapter 5Loop Control StatementsThe for StatementThe while StatementThe do-while StatementNumerical AccuracyNumerical Analysis

Copyright 1999, James M. Slack

Page 2: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 2

Loops: IntroductionLoop

Group of statements the computerexecutes over and over, as longas some criterion holds

Three loop statements in Java forwhiledo-while

Statement

Statement

Statement

Statement

Page 3: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 3

Loops: IntroductionMany real-world activities

involve loopsExample: Library checkout

Clear up patron's overduematerials and outstanding fines, if any.

Scan or type patron's ID number. Update ID if not current and valid.

Scan material code for each item.Stamp due date on each item.Give materials and library card back to the patron.

Checkout librarian does these steps until library closes

Page 4: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 4

Loops: KindsTwo kinds of loops

CountingEvent-controlled

Counting loopComputer knows, when it begins the loop, how many

times to execute the bodyCounting loop statement in Java: for

Event-controlledComputer stops the loop when a condition is no longer

trueEvent-controlled loop statements in Java: while, do-while

Page 5: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 5

Loops: KindsCounting loops are subset of event-controlled

"Event" of counting loop: counting variable reaches the limit

Event-controlled loops

Counting loops

Page 6: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 6

The for StatementThe counting loop statement in JavaExample

for (int count = 1; count <= 5; count++){ System.out.println(count);}

Output12345

Initialization Condition Increment

Iscondition

true?

Yes

Flow ofcontrol

for-body

Next statement inprogram

initalizationpart

increment part

No

Page 7: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 7

The for Statement: ExampleSum the first 20 integers

int total = 0;

for (int number = 1; number <= 20; number++){ total = total + number;}System.out.println("1 + 2 + ... + 20 is " + total);

Output1 + 2 + ... + 20 is 210

Yes

Flow ofcontrol

total = total +number

Next statement inprogram

int number = 1

number++

No

Is number<= 20?

Page 8: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 8

The for Statement: ExampleWhat does this display?

for (int count = 10; count <= 6; count++){ System.out.println(count);}

Iscondition

true?

Yes

Flow ofcontrol

for-body

Next statement inprogram

initalizationpart

increment part

No

Page 9: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 9

The for Statement: SyntaxCan leave out initialization, condition, or increment

int total = 0, number = 1;

for (; number <= 20;){ total = total + number; number++;}System.out.println("1 + 2 + ... + 20 is " + total);

Don't need to use same variable throughoutint y = 10;

for (int x = 0; x < y; y--){ System.out.println(x + " " + y);}

(Confusing!)

Page 10: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 10

The for Statement: Draw CirclesExample: drawing circles in turtle graphics

Can simulate circles with drawPolygon()

Too manysides makesdrawing tooslow

20 to 40 sideslooks ok

360 sides4.2 seconds

180 sides1.9 seconds

90 sides0.9 seconds

45 sides0.4 seconds

20 sides0.2 seconds

10 sides0.1 seconds

Page 11: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 11

The for Statement: drawPolygon()The drawPolygon() method (Chapter 2)

// drawPolygon: Draws a regular polygon with the given// number of sides, and all sides are of// length sizevoid drawPolygon(int numSides, int size)throws TurtleException{ for (int side = 1; side <= numSides; side++) { this.move(size); this.turnRight(360 / numSides); }}

Page 12: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 12

The for Statement: drawPolygon()Drawing circles with drawPolygon()

How to draw circle with specific radius?Circumference of a circle

2 x x radiusDistance around a polygon

sides x sizeSet these equal to each other, solve for size

2 x x radius = sides x size size = (2 x x radius) / sides

In Javaint size = (int) Math.round(2 * Math.PI * radius) / NUM_SIDES;

Page 13: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 13

The for Statement: drawCircle()Drawing circles with drawPolygon()

First version of drawCircle()// drawCircle: (First version) Draws a circle of the given// radius, to the right of the turtle. The turtle// finishes at the same position and direction as// before. The pen must be down beforehand, and is// down afterward.static final int NUM_SIDES = 20; // Must divide into 360public void drawCircle(int radius)throws TurtleException{ int size = (int) Math.round(2 * Math.PI * radius) / NUM_SIDES; this.drawPolygon(NUM_SIDES, size);}

Computes size of 20-sided polygonto achieve desired radius

Page 14: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 14

The for Statement: drawCircle()Test drawCircle()

// This program draws a circle inside a square, // to see how accurate the circle drawing method is

import turtlegraphics.*;import SmartTurtle;

public class TestCircle{ static final int CIRCLE_SIZE = 300;

public static void main[] (String args) throws TurtleException { SmartTurtle myTurtle = new SmartTurtle(); myTurtle.goLeft(200); myTurtle.turnAround(); myTurtle.move(CIRCLE_SIZE); myTurtle.turnAround(); myTurtle.drawSquare(CIRCLE_SIZE * 2); myTurtle.move(CIRCLE_SIZE); myTurtle.drawCircle(CIRCLE_SIZE); }}

Oops!

Page 15: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 15

The for Statement: drawCircle()What's wrong with drawCircle()?

Turtle draws first side of polygonstraight up

Turtle draws last side of polygonat an angle

Need to balancethese two anglesAt beginning

this.turnRight(360 / NUM_SIDES / 2);

At endthis.turnLeft(360 / NUM_SIDES / 2);

First edge ofpolygon

Last edge ofpolygon

Turtle's startingposition

Page 16: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 16

The for Statement: drawCircle()Final version of drawCircle()

// drawCircle: (Final version) Draws a circle of the given// radius, to the right of the turtle. The turtle// finishes at the same position and direction as// before. The pen must be down beforehand, and is// down afterward.static final int NUM_SIDES = 20; // must divide into 360 // with an even quotientpublic void drawCircle(int radius)throws TurtleException{ this.turnRight(360 / NUM_SIDES / 2); int size = (int) Math.round(2 * Math.PI * radius) / NUM_SIDES; this.drawPolygon(NUM_SIDES, size); this.turnLeft(360 / NUM_SIDES / 2);}

New restriction: number of sides mustdivide into 360 with even quotient(So can divide this by 2 for startand end angles)

Ah...

Page 17: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 17

The while StatementOne of two event-controlled loop

statementsBody keeps executing as

long as condition is trueExample

int i = 0;while (i < 3){ System.out.println(i); i++;}

Output012

Iscondition

true?

Yes

Flow ofcontrol

while-body

No

Next statement inprogram

Page 18: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 18

The while Statementwhile similar to if statement

while statementwhile (i < 3){ System.out.println(i); i++;}

if statementif (i < 3){ System.out.println(i); i++;}

whilestatement

Iscondition

true?

Yes

Flow ofcontrol

while-body

No

Next statement inprogram

ifstatement

Iscondition

true?

Yes

Flow ofcontrol

if-body

No

Next statement inprogram

Page 19: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 19

The while Statement: SentinelsSentinel loop

Sentinel: not data, but marks the end of dataSentinel loop: reads data values until sentinel

ExampleSum series of numbers terminated

by zero

10, 20, 30, 0

Data values Sentinel

Page 20: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 20

The while Statement: SentinelsSentinel loop example

int sum = 0, number;

number = Keyboard.readInt("Enter first number: ");

while (number != 0) { sum = sum + number; number = Keyboard.readInt("Enter next number: ");}System.out.println("The sum is " + sum);

Trace

Enter first number: 10Enter next number: 20Enter next number: 30Enter next number: 0The sum is 60

Statement number sum

int sum = 0, number; — 0number = Keyboard.readInt("Enter first number (0 to stop): )"); 10 0while (number != 0) 10 0 sum = sum + number; 10 10 number = Keyboard.readInt("Enter next number (0 to stop): )"); 20 10while (number != 0) 10 10 sum = sum + number; 10 30 number = Keyboard.readInt("Enter next number (0 to stop): )"); 30 30while (number != 0) 30 30 sum = sum + number; 30 60 number = Keyboard.readInt("Enter next number (0 to stop): )"); 0 60while (number != 0) 0 60System.out.println("The sum is " + sum); 0 60

Page 21: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 21

The while Statement: Infinite LoopInfinite loop

Loop that doesn't stopEasy to write accidentally with while statement

Infinite loop example 1while (x < 3){ y++;}

Infinite loop example 2sum = 0;count = 0;while (count < 100){ sum = sum + count;}System.out.println("Sum of numbers from 1 to 100 is " + sum);

Page 22: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 22

The while Statement: Infinite LoopInfinite loop example 3

answer = Keyboard.readChar("Say hi? (y/n)");while (answer == 'y') System.out.println("Hi!"); answer = Keyboard.readChar("Say hi? (y/n)");System.out.println("Bye!");

Infinite loop example 3int x = 0;while (x < 10);{ System.out.println(x); x++;}

Page 23: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 23

The while Statement: Infinite LoopWhy doesn't compiler catch infinite loops?

Halting problem: Impossible for a computer program to detect all possible infinite loops in another program

Up to the programmer to avoid infinite loops

When you write a while statement

Make sure some statement in the while-body makes the

condition false

Page 24: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 24

The while Statement: MenusExample: Writing menu-based programs

Menu: List of selections that user can pick fromWriting a text-based menu system with while

Present menuGet selection from userAs long as not quit

•Do the selection•Present the menu•Get next selection

File Edit View Flip Window Help

DrawingNewOpenSaveSave AsExit

File

Save

Page 25: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 25

The while Statement: MenusSkeleton for text-based menu

// Present the menu the first time// Get first selection from userwhile (selection != quitOption){ // Do selection // Present the menu again // Get next selection from user}

Example: Compute bank balance--- Bank Balance Menu ---0. Quit1. Enter beginning balance2. Enter interest rate3. Compute ending balanceEnter selection (0, 1, 2, or 3): _

Menu0. Quit1. Enter beginning balance2. Enter interest rate3. Compute ending balance

Page 26: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 26

The while Statement: MenusBank Balance Program

Present menuGet selection from userAs long as not quit

•Do the selection•Present the menu•Get next selection

int selection;double balance = 0.00;double rate = 0.00;

// Display program titleSystem.out.println("--- Compute End-of-Year Bank Balance ---");System.out.println();

// Display menu, get first selectionSystem.out.println("--- Bank Balance Menu ---");System.out.println("0. Quit");System.out.println("1. Enter beginning balance");System.out.println("2. Enter interest rate");System.out.println("3. Compute ending balance");selection = Keyboard.readInt("Enter selection (0, 1, 2, or 3): ", 0, 3);

Page 27: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 27

The while Statement: Menus// Handle the first selection; keep handling selections until// user picks the quit selection (0)while (selection != 0){ switch (selection) { case 1: balance = Keyboard.readDouble("Enter beginning balance: "); break; case 2: rate = Keyboard.readDouble("Enter interest rate: "); break; case 3: System.out.println("Ending balance is " + (balance + balance * rate)); break; default: System.out.println("Problem with switch statement"); break; }

// Display menu, get next selection System.out.println(); System.out.println("--- Bank Balance Menu ---"); System.out.println("0. Quit"); System.out.println("1. Enter beginning balance"); System.out.println("2. Enter interest rate"); System.out.println("3. Compute ending balance"); selection = Keyboard.readInt("Enter selection (0, 1, 2, or 3): ", 0, 3);}

System.out.println("Bye!");

Page 28: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 28

The while Statement: CountingWriting counting loops with while

Can convert for statement to while

for (initialization ; condition ; increment ){ for-body}

initialization;while (condition){ for-body; increment;}

int total = 0;

for (int number = 1; number <= 20; number++){ total = total + number;}

int number = 1, total = 0;

while (number <= 20){ total = total + number; number++;}

Page 29: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 29

Kinds of Loops

statement

condition

Yes

Conditionat the

top

body

No

Flow ofcontrol

statement

No

Yes

Flow ofcontrol

body

statement

Yes

body(begin)

body(end)

No

Flow ofcontrolCondition

at thebottom

Conditionin the

middle

conditioncondition

Page 30: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 30

Kinds of LoopsCondition at the top

Condition tested before the body Java statements: for and while

Condition at the bottomCondition tested after the body Java statements: do-while

Condition in the middleCondition tested inside the bodyNo built-in Java statement

Page 31: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 31

The do-while StatementThe "other" event-controlled loop

statementBody keeps executing as

long as condition is trueExample

int i = 0;do{ System.out.println(i); i++;} while (i < 3);

Output012

Iscondition

true?

No

Flow ofcontrol

do-while-body

Yes

Next statement inprogram

Page 32: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 32

The do-while StatementDifference from while statement

do-while executes body at least oncewhile statement may not execute body at all

Examplewhile do-while

int i = 10; int i = 10;while (i < 3) do{ { System.out.println(i); System.out.println(i); i++; i++;} } while (i < 3);

Output(nothing) 10

Page 33: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 33

The do-while Statement: FormatPoor style Preferred style

do do{ { do-while-body do-while-body} } while (condition);while (condition);

Looks like the beginningof a while statement

The brace before whiledistinguishes it as part

of a do-while

Page 34: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 34

The do-while Statement: ExampleProgram to help children learn multiplication

int guessNum = 0, response;

System.out.println("What is " + operand1 + " times " + operand2 + "?");do{ guessNum++; response = Keyboard.readInt("Enter guess number " + guessNum + ": ");} while (response != operand1 * operand2);

System.out.println("Correct!");

Equivalent while statement requires two copies of body One before loop starts One inside the loop

Page 35: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 35

Numerical Accuracy// Add up 0.10 until the sum is 1.0 (Wrong)

public class AddTo1{ public static void main(String[] args) { double total = 0.0;

while (total != 1.0) { total = total + 0.10; System.out.println("Total so far: " + total); } System.out.println("Done"); }} Total so far: 0.1

Total so far: 0.2Total so far: 0.30000000000000004Total so far: 0.4Total so far: 0.5Total so far: 0.6Total so far: 0.7Total so far: 0.7999999999999999Total so far: 0.8999999999999999Total so far: 0.9999999999999999Total so far: 1.0999999999999999Total so far: 1.2Total so far: 1.3Total so far: 1.4000000000000001

Page 36: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 36

Numerical Accuracy: Round-off0.1+0.1+0.1+ 0.1+0.1+0.1+0.1+0.1+0.1+0.1 1.0?Round-off error

Can happen only with floating-point arithmeticComputer stores numbers in binary, not base 10Representable number: can store in finite number of

digitsUnrepresentable in base 10: 1/3 = 0.333333333...Representable in base 10: 1/4 = 0.25

Some representable numbers in base 10 are unrepresentable in binary

0.10 (decimal) = 0.00011001100110011001100 . . . (binary)

Can only store approximation of 0.10

Page 37: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 37

Numerical Accuracy: Round-offRound-off error can happen with representable

numbersExample:

1.3707275390625 (decimal) = 1.0101111011101 (binary)Suppose computer can only store 8 binary digits

Computer's version of number is an approximation

6250035400390.01010000000011.0

3671875.10101111.1

6253707275390.11010101111011.1

DecimalBinary

Page 38: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 38

Numerical Accuracy: ComparisonsDon’t compare floating-point numbers with == or !=

double total = 0.0;while (total != 1.0) ... // Avoid

Instead:Use integers

int total = 0;while (total != 10) ... // Use 1 for 1/10

Use <=, >=, <, or > double total = 0.0;while (total <= 1.0) ... // Good approach

Check if numbers are very closedouble total = 0.0;

// Can set exact tolerancewhile (Math.abs(total - 1.0) > 0.00001) ...

Page 39: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 39

Numerical Accuracy: ArithmeticAvoid arithmetic on floating-point numbers

that are very different in sizeSimulate space probe from earth to Proxima Centauri

double centimetersToProximaCentauri = 4067815793829482158.0;

while (centimetersToProximaCentauri > 0.0){ // Simulate action of space probe here ... centimetersToProximaCentauri = centimetersToProximaCentauri - 1.0;}

This loop is infinite: computer stores 4067815793829482158.0 as 4067815793829482000.0

4067815793829482000.0 - 1.04067815793829482000.0

One solution: use kilometers instead

Page 40: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 40

Condition-in-the-Middle LoopsHypothetical condition-in-the-middle loop (not Java)

loop{ number = Keyboard.readInt("Number (0 to stop): "); until (number == 0); sum = sum + number;}

Can use as while or do-whileMove until up for while, down for do-while

Equivalent while loopnumber = Keyboard.readInt("Enter first number (0 to stop): ");

while (number != 0) { sum = sum + number; number = Keyboard.readInt("Enter next number (0 to stop): ");}

Must duplicate part of body before loop starts

Page 41: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 41

Condition-in-the-Middle LoopsCan use break statement to stop loop early

Put "if (condition) break" in infinite loopwhile (true) { number = Keyboard.readInt("Number (0 to stop): "); if (number == 0) break; sum = sum + number;}System.out.println("Sum is " + sum);

Doesn't work if break is inside switchMust label the loop statement

loop:while (true){ switch (...) { case xx: break loop; ...

Page 42: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 42

The continue StatementSyntax

continue;orcontinue label;

Examplefor (i = 0; i < 100; i++){ if (i % 2 == 0) // Ignore even numbers { continue; } System.out.println(i);}

ActionControl skips rest of loop iteration; starts next iteration for loop: computer executes the increment part before

starting next iteration

Page 43: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 43

Numerical AnalysisStudy of use of arithmetic in computer programsSome issues in numerical analysis

Minimize round-off errorsSolve problems that don't have exact

solution (or exact solution is difficult to find)Finding roots of mathematical functions

Root of function: Value of x that makes function 0

Often difficult to find roots algebraicallyExample: find all roots of f(x) = x5 - 5x + 1

Page 44: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 44

Numerical Analysis: RootsFind roots of f(x) = x5 - 5x + 1

Plot the function

Three roots: one is between -1 and -2

-30

-20

-10

0

10

20

30

-2 -1 0 1 2

x

f(x)

Page 45: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 45

Numerical Analysis: BisectionUse bisection to find root of f(x) = x5 - 5x + 1

Plot shows a root between -1 and -2Pick 2 values of x, one on either side of root

Use -1.5 as approximation of root, plug into function

0.90625 > 0, so it replaces old "above 0" value

x value f(x) value

Above zero -1 5

Zero value ??? 0

Below zero -2 -21

90625.0

15.759375.7

1)5.1(5)5.1()5.1( 5

f

-1.5 0.90625

Page 46: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 46

Numerical Analysis: BisectionUse bisection to find root of f(x) = x5 - 5x + 1

Next evaluate f(x) at -1.75 (halfway between -1.5 and -2)

f(-1.75) is -6.66301 -6.66301 < 0, so it replaces old "below 0" value

x value f(x) value

Above zero -1.5 0.90625

Zero value ??? 0

Below zero -2 -21-1.75 -6.66301

Page 47: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 47

Numerical Analysis: BisectionKeep using bisection to get as close to 0 as desired

Each iteration cuts range by half

-8

-7

-6

-5

-4

-3

-2

-1

0

1

2

0 1 2 3 4 5 6 7 8 9 10 11 12

Iterations

Upper

Lower

Midpoint

f(Midpoint)

Page 48: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 48

Numerical Analysis: BisectionBisection advantages

Simple and effective Little or no round-off error

Bisection disadvantages Slow Only finds one root at a time Can't tell if function has other

roots Appropriate for continuous

intervals only

-2

-1.5

-1

-0.5

0

0.5

1

1.5

2

-1 -0.5 0 0.5 1

x

f(x)

Noncontinuousfunction

Page 49: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 49

Numerical Analysis: BisectionBisection Program

// Find zero of a function by bisection.// Displays bound1, bound2, midpoint between bound1 and// bound2, and f(midpoint). If f(midpoint) is not within// +/- ERROR, cuts area in half and repeats.// NOte: Required that f(bound2) < 0 < f(bound1), and there // exists f(x) such that f(x) == 0, x is between // bound1 and bound2, and f() is continuous between // f(bound1) and f(bound2)

import Keyboard;import Format;

public class Bisection{ static final double ERROR = 0.001; // Maximum difference between // generated solution and zero

static final int WIDTH = 14; // Width of output numbers static final int DECIMALS = 5; // Decimals of output numbers

// evaluateFunction: Returns f(x) (Put your function here) static double evaluateFunction(double x) { return Math.pow(x, 5) - (5 * x) + 1; }

Page 50: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 50

Numerical Analysis: Bisection public static void main(String[] args) throws java.io.IOException { double bound1, bound2;

System.out.println("--- Find Zeros of a Function " + "by Bisection ---"); System.out.println(); // Get initial bounds for the value of x from the user System.out.println("Enter two values that surround the value"); System.out.println("of x that makes the function 0."); bound1 = Keyboard.readDouble("Value of x that gives " + "positive value " + "from function: "); bound2 = Keyboard.readDouble("Value of x that gives " + "negative value " + "from function: "); System.out.println(); double midpoint;

System.out.println(Format.padRight("Bound1", WIDTH) + Format.padRight("Bound2", WIDTH) + Format.padRight("Midpoint", WIDTH) + Format.padRight("f(Midpoint)", WIDTH)); System.out.println();

Page 51: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 51

Numerical Analysis: Bisection // Do first cut before the loop midpoint = (bound1 + bound2) / 2; System.out.println(Format.pad(bound1, WIDTH, DECIMALS) + Format.pad(bound2, WIDTH, DECIMALS) + Format.pad(midpoint, WIDTH, DECIMALS) + Format.pad(evaluateFunction(midpoint), WIDTH, DECIMALS));

// Keep reducing the area between the bounds until the // f(midpoint) is within ERROR tolerance of 0.0 while (Math.abs(evaluateFunction(midpoint)) > ERROR) { if (evaluateFunction(midpoint) > 0.0) bound1 = midpoint; else bound2 = midpoint; midpoint = (bound1 + bound2) / 2; System.out.println(Format.pad(bound1, WIDTH, DECIMALS) + Format.pad(bound2, WIDTH, DECIMALS) + Format.pad(midpoint, WIDTH, DECIMALS) + Format.pad(evaluateFunction(midpoint), WIDTH, DECIMALS)); } }}

Program uses Format.pad() (from Chapter 7) Format.pad(floating-point-number, width, decimals) Format.pad(string, width)

Page 52: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 52

Num. Analysis: BisectionBisection program run on

f(x) = x5 - 5x + 1--- Find Zeros of a Function by Bisection ---

Enter two values that surround the valueof x that makes the function 0.Value of x that gives positive value from function: -1Value of x that gives negative value from function: -2

Bound1 Bound2 Midpoint f(Midpoint)

-1.00000 -2.00000 -1.50000 0.90625 -1.50000 -2.00000 -1.75000 -6.66309 -1.50000 -1.75000 -1.62500 -2.20596 -1.50000 -1.62500 -1.56250 -0.50073 -1.50000 -1.56250 -1.53125 0.23783 -1.53125 -1.56250 -1.54687 -0.12241 -1.53125 -1.54687 -1.53906 0.05994 -1.53906 -1.54687 -1.54297 -0.03068 -1.53906 -1.54297 -1.54102 0.01477 -1.54102 -1.54297 -1.54199 -0.00792 -1.54102 -1.54199 -1.54150 0.00343 -1.54150 -1.54199 -1.54175 -0.00224 -1.54150 -1.54175 -1.54163 0.00060

-30

-20

-10

0

10

20

30

-2 -1 0 1 2

x

f(x)

Page 53: Programming and Problem Solving With Java Chapter 5 Loop Control Statements The for Statement The while Statement The do-while Statement Numerical Accuracy.

Programming and Problem Solving With Java 53

Num. Analysis: BisectionBisection program run on

f(x) = (6x3 + 4x2 + 1) / 25x--- Find Zeros of a Function by Bisection ---

Enter two values that surround the valueof x that makes the function 0.Value of x that gives positive value from function: 1.0Value of x that gives negative value from function: -0.4

Bound1 Bound2 Midpoint f(Midpoint)

1.00000 -0.40000 0.30000 0.20293 0.30000 -0.40000 -0.05000 -0.80740 0.30000 -0.05000 0.12500 0.34375 0.12500 -0.05000 0.03750 1.07300 0.03750 -0.05000 -0.00625 -6.40099 0.03750 -0.00625 0.01562 2.56256 0.01562 -0.00625 0.00469 8.53409 0.00469 -0.00625 -0.00078 -51.20012 0.00469 -0.00078 0.00195 20.48031 0.00195 -0.00078 0.00059 68.26676 0.00059 -0.00078 -0.00010 -409.60002 0.00059 -0.00010 0.00024 163.84004 0.00024 -0.00010 0.00007 546.13335 0.00007 -0.00010 -0.00001 -3276.80000 0.00007 -0.00001 0.00003 1310.72000 0.00003 -0.00001 0.00001 4369.06667 0.00001 -0.00001 -0.00000 -26214.40000

-2

-1.5

-1

-0.5

0

0.5

1

1.5

2

-1 -0.5 0 0.5 1

x

f(x)