Top Banner
June 20, 2022 1 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This lecture was given in Fall, 2008 by Professor Sizemore and refers to an older Version of MATLAB than R2011A.
76

Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

Jan 17, 2016

Download

Documents

Dominic Higgins
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 1

Douglas R. Sizemore, Ph.D.

Professor of Computer Science

COS 131: Computing for Engineers

Chapter 9: Recursion

This lecture was given in Fall, 2008 by Professor Sizemore and refers to an olderVersion of MATLAB than R2011A.

Page 2: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 2

Introduction• Basic ideas of recursive programming:

– Three basic characteristics must be present for a recursive function to work

– Exceptions represent a powerful mechanism for detecting and trapping errors

– A wrapper function is used to set up the recursion

Page 3: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 3

Introduction• Recursion is an alternative technique by which a

code block can be repeated in a controlled manner.– Uses a basic mechanism for invoking functions to

manage the repetition of a block of code; a function which repeatedly calls its self until a terminating condition is reached

– Often, a recursive function needs a “wrapper function” to set up the recursion correctly, and to check for erroneous data conditions that might cause errors.

– The actual recursive function then becomes a private helper function – what do private and helper mean here?

Page 4: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 4

Concept: The Activation Stack• Must look deeper into the mechanism by

which function calls are mechanized

• Calling a function depends on a special kind of memory stack called an activation stack

• Enables the CPU to determine which functions are active or suspended awaiting the completion of other function calls

Page 5: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 5

Concept: The Activation Stack• Concept of a stack

– Stack is a fundamental data structure of computer science

– Can be modeled by looking at the trays at the front of the line in the Great Hall at Covenant

– Stack – a collection of objects of arbitrary size with a restricted number of operations we are allowed to perform on the collection

Page 6: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 6

Concept: The Activation Stack• Concept of a stack – picture representation of a

simple stack:

Illustration of a simplestack data structure;can only push a dataitem onto the stack andpop a data item off ofthe stack.

Page 7: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 7

Concept: The Activation Stack

• Concept of a stack– Only allowed the following operations with a

stack:• Push an object onto the stack

• Pop an object off the stack

• Peek at the top object without removing it

• Check whether the stack is empty

Page 8: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 8

Concept: The Activation Stack

• Activation Stack– Core concept that allows a function to call itself

– Means by which the operating system allocates memory to functions for local storage

– Local storage is required by functions for • Storing the location of the function to be evaluated

• Storing the location in memory to return to when the function execution completes

• Storing copies of the function parameter values

• Providing space for values of any local variables defined within the function

Page 9: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 9

Concept: The Activation Stack• Activation Stack

– When a user runs a application program• Operating system allocates sufficient memory to

– Load the application– Assign a block of memory to contain the activation stack

• When the application calls a function– Information specific to that function is assembled into an object

called a stack frame– Information is then pushed onto the activation stack– Calling program is suspended– Control is passed to the function specified in the frame on the top of

the stack

• When the function completes– Frame is popped off the stack and destroyed– Control is returned to the frame beneath; now on the top of the stack

Page 10: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 10

Concept: The Activation Stack

• Function Instances– We distinguished between class and object in chapter 2

• Class is the general data type used

• Object is an instance of the class as assigned to a specific variable

– For functions the .m file is the class and a particular implementation of that .m file as a function in a program is the object or instance of the .m file

Page 11: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 11

Recursion Defined

• From a data structures viewpoint there is no reason why a function could not “call itself”

• This is at the center of recursive programming

• Must have a terminating condition or the function would repeat endlessly

• Operating system will force termination of the process when the memory resources in the activation stack are exhausted

Page 12: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 12

Recursion Defined• A primary example of recursion is that of taking a

factorial of a number• n factorial represented in a traditional view:

– 5! = 5 * 4 * 3 * 2 * 1

– 5! = 5 * 4!

• n factorial represented in a recursive view:– n! = n * (n – 1)!

• Note the computational structure that as we complete a factorial we repeat the process for every integer so we can write a function that calls itself to complete the range of calculations required

Page 13: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 13

Recursion Defined• Our ability to build and use a recursive function

requires the following three characteristics:– Must be a terminating condition to stop the process

– Function must call a clone of itself

– Parameters to the call must move the function toward the terminating condition

• Note: a recursive function does not actually call itself; it requests a new stack frame and passes different parameter to the instance of the function that occupies the new frame

Page 14: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 14

Implementing a Recursive Function in MATLAB

• General template for a recursive function in MATLAB:

Page 15: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 15

Implementing a Recursive Function in MATLAB

• Guidelines for implementing a recursive function:– The <function name> can be any legal variable

name– The variable <result> may be any legal variable

name or a vector of variable names– Must supply one or more lines of documentation

to define purpose and implementation of the recursive function

– Each exit from the function must assign values to all of the result variables

Page 16: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 16

Implementing a Recursive Function in MATLAB• Guidelines for implementing a recursive

function:– First design decision is to determine the

condition(s) under which the recursive process should be stopped; how express as the <terminating condition N> tests

– The <initial value N> entries are the values(s) of the result(s) at the terminating condition(s)

– Second design decision is to determine the <operation> - the specific mathematical or logical operation that must be performed to combine the current formal parameters with result of the recursive call to create a new value of the <result>

Page 17: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 17

Implementing a Recursive Function in MATLAB• Guidelines for implementing a recursive

function:– Last design decision is to determine how to

compute the <actual_params> of the recursive call to ensure that the process moves towards at least on of the terminating condition N> states

Page 18: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 18

Implementing a Recursive Function in MATLAB• Listing 9.1: Function to compute N factorial

• Note: all the mathematical operations are performed as the activation stack “unwinds.”

See line by linedescription ofrecursive functionon page 207.

Page 19: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 19

Implementing a Recursive Function in MATLAB• Exercise 9.1: Analyzing recursive behavior

• Smith text, page 208, top

Page 20: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 20

Exceptions• Important to discuss how programs deal with

unexpected circumstances

• Exceptions represent a powerful tool for managing runtime errors caused by programming errors or bad data

• Example: an arithmetic divide by zero

• Could be buried deep in the middle of a complex set of calculations; possibly hard to find

Page 21: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 21

Exceptions• Historical approaches

– Some languages require any mathematical function that might produce an error to return the status of that calculation to the calling function

• Allows errors to be reported and processed• Diminishes the ability of a function to return a value• Regresses the ability to call the function

– Some languages use a globally accessible variable, such as IERROR, to report status

• Does not relieve the calling function of the need to check whether the IERROR value is bad, or solving the problem, or elevating it

– What value should the function return if it is unable to complete its assigned calculation?

Page 22: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 22

Exceptions• Generic Exception Implementation

– Most enlightened languages provide an exception mechanism where implementation is immediately suspended in the current stack frame if an error occurs

– Activation stack below this frame is then searched for the frame of a program that has “volunteered” to process this type of exception

Page 23: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 23

Exceptions• Generic Exception Implementation

– Following mechanisms are necessary to implement the exception mechanism effectively:

• Throwing an exception: go back down the stack without completing any of the functions looking for a function equipped to handle the specific exception

• Catching an exception: a function that is able to deal with a specific exception uses a try … catch construct to identify the suspect code and resolve the problem;

– code block that contains the suspect code is placed between the try and catch

– After the catch statement that typically identifies the particular exception, there is a code block that should fix the problem

Page 24: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 24

Exceptions• Generic Exception Implementation

– Following mechanisms are necessary to implement the exception mechanism effectively:

• Catching the exception: – Usually offers facilities both for determining exactly where

the exception occurred and for reconstructing the activation stack with all the variable values as they were at the time of the exception

Page 25: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 25

Exceptions• Generic Exception Implementation

– General template for processing exceptions

– Does not matter how deep in the data processing code the error occurs-the user interface catches the error, reports it to the user, and prompts the user for better data

Page 26: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 26

Exceptions• Generic Exception Implementation

– MATLAB Implementation• Simplified version of the general form of exception

processing

• Try..catch … end construct is fully supported

• Does not distinguish between the kinds of exceptions that can be thrown

– All built-in functions throw exceptions when the discover error conditions

– To throw an exception manually, the program calls the ERROR(…) function that takes one parameter, a string defining the error

– To handle an exception, a code block we suspect might throw an exception is placed between try and catch statements

Page 27: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 27

Exceptions• Generic Exception Implementation

– MATLAB Implementation• To determine the cause of the exception, you can use

the LASTERROR function

• In more complex situations where this function may not be able to actually handle the error, a further exception can be thrown from the CATCH block

• Listing 9.2, on the following slide, illustrates a simple example

Page 28: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 28

Exceptions• Generic Exception Implementation

– Listing 9.2: MATLAB script using exception handling:

See line by linedescription ofrecursive functionon page 211.

Page 29: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 29

Exceptions• Generic Exception Implementation

– Listing 9.2 – object here is to have user define a triangle by entering a vector of three sides, and calculate the angle between the first two sides

– acosd(…) function computes the inverse cosine of a ratio

– If ratio is greater than 1, triangle is not valid and the function returns a complex number

– Script detects the answer as complex and throws an exception

Page 30: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 30

Exceptions• Generic Exception Implementation

– Exercise 9.2: Processing exceptions– Smith text, page 212, middle

Page 31: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 31

Exceptions• Wrapper Functions

– Smith poses question as to how you would deal with a user who accidently called for the factorial of a negative number containing a fractional part?

Page 32: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 32

Exceptions• Wrapper Functions

– Three strategies for dealing with the unexpected inputs problem

• The legalist approach ignores the bad values, lets the user’s program die, then responds to user complaints by pointing out that the documentation clearly indicates that you should not call for the factorial of a negative number

• In-line coding builds into the code a test for N less than zero (or fractional) and exits with a meaningful error message

– Test is in a bad place

– Code repeated as many times as function is called

– Poor implementation – punishes people who use the function correctly

Page 33: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 33

Exceptions• Wrapper Functions

– Three strategies for dealing with the unexpected inputs problem

• Wrapper function is best solution to this problem

– Wrapper function is called once to perform any tests of setup that recursion requires; then calls the recursive function as a helper to the main function call

Page 34: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 34

Exceptions• Template 9.3: General template for a wrapper

function

Page 35: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 35

Exceptions

• Template 9.3: General template for a wrapper function– First function named <function_name> is the

wrapper function

Page 36: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 36

Exceptions

• Listing 9.3: Wrapper implementation for the factorial function

See line by linedescription ofrecursive functionon page 214.

Page 37: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 37

Exceptions

• Observations on Listing 9.3– Wrapper function is the function that is actually

called– Even if the name of the function is not the same

name as the file, the first function in the file is always executed first

– Exercise 9.3: Writing the protected factorial– Smith text, page 214-215, bottom-top

Page 38: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 38

Tail Recursion

• Recursion methods considered can consume considerable memory resources from the activation stack

• Tail recursion executes the recursive behavior without consuming activation stack resources

• Requires a wrapper function to initialize the recursion; uses an extra parameter to carry the emerging result of the recursion

Page 39: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 39

Tail Recursion

• Main characteristic: every exit from the recursion helper function must either return a result or be a standalone call to the recursive helper with no operations to be performed on it

• Most currently used languages along with MATLAB construct executable code to operate in place of the existing stack frame when tail recursion is detected

Page 40: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 40

Tail Recursion

• Template 9.4: General template for tail recursion

Note wrapper function takes on added responsibilityOf calling the helper function with an additional parameterThat is the initial result

Page 41: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 41

Tail Recursion

• Listing 9.4: Tail recursive factorial implementation

See line by linedescription ofrecursive functionon page 216.

Page 42: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 42

Tail Recursion

• Exercise 9.4: Writing the tail recursive factorial

• Smith text, page 216, bottom

Page 43: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 43

Mutual Recursion

• Recursion cannot always be achieved by a function directly calling itself

• Mutual recursion is when a solution calls for function A to call function B, and then function B calls function A

• At least on of these functions must be moving toward the terminating condition

Page 44: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 44

Generative Recursion

• A recursive process in which there is a terminating condition, but the model of the process permits an unsuccessful attempt to achieve that condition

• Example: behavior of billiard balls rolling on a billiard table – see text, page 217

Page 45: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 45

Examples of Recursion

• Three examples of recursive programming:– The detection of palindromes– Computing the Fibonacci series of numbers– Finding zeros of a function

Page 46: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 46

Examples of Recursion

• Detecting Palindromes– Determine whether a word or phrase received as a

string is a palindrome– Criterion: is spelled the same backwards and

forwards

Page 47: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 47

Examples of Recursion

• Detecting Palindromes– Design of recursive function isPal(<string>):

• Function isPal(<string>) terminates if the <string> has zero or one character, returning true

• Terminates if the first and last characters are not equal, returning false

• Otherwise the function returns isPal(<shorter string>), where the shorter string is obtained by removing the first and last characters of the original string

• As the string is always being shortened, the recursive solution is approaching the terminating condition

Page 48: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 48

Examples of Recursion

• Detecting Palindromes: Listing 9.5– Recursive palindrome detector

See line by linedescription ofrecursive functionon page 218.

Page 49: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 49

Examples of Recursion

• Fibonacci Series– Named for the Italian mathematician Leonardo

Piasano Fibonacci– Studying the growth of rabbit populations in the

eleventh century

ComputingRabbitPopulations

Page 50: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 50

Examples of Recursion

• Fibonacci Series– Clear from diagram that the number of rabbits in

month N comprised the number in month N – 1 plus the rabbits born to the mature pairs (shown in boxes in the figure)

– The number of mature pairs that produce a new pair is the number of rabbits in the month before, N - 2

Page 51: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 51

Examples of Recursion

• Fibonacci Series– Thus, the algorithm for computing the population

of pairs after N months, fib(N) is recursive:• There is a terminating condition: when N = 1 or N = 2,

the answer is 1

• Recursive condition is: fib(N) = fib(N-1) + fib(N-2)

• Solution moves toward the terminating condition, since as long as N is a positive integer, computing N-1 and N-2 will move towards 1 or 2

Page 52: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 52

Examples of Recursion• Fibonacci Series: Listing 9.6: Fibonacci

function

Fibonacci inthe createdorder

Page 53: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 53

Examples of Recursion

• Zeros of a Function– Frequently a need to solve nonlinear equations by

seeking the values of the independent variable that produced a zero result

– Will develop a recursive approach to determining the zeros of functions

– Very helpful to have a good estimate of the locations of the crossings

Page 54: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 54

Examples of Recursion

• Zeros of a Function– Consider a function f(x):

– This function is plotted on the next slide

6 5 4 3( ) 0.0333 0.3 1.3333 16 187.2f x x x x x x

Page 55: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 55

Examples of Recursion

• Zeros of a Function– Plot of function:

Page 56: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 56

Examples of Recursion

• Zeros of a Function– Algorithm will work for any function of x– Assume the continuous line describes the exact

function– There are a number of zero crossings of this

function– Find the exact value of one of the zeros of this

function by first estimating the zero crossings, and then using a recursive technique for refining a abetter estimate to arbitrary levels of accuracy

Page 57: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 57

Examples of Recursion

• Estimating Critical Points of a Function– Need to comput an approximation to the roots of

this equation– Found by finding the x values at which adjacent

values of the function change sign– To identify these points you multiply adjacent

values of f(x) and find where that product is not positive

Page 58: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 58

Examples of Recursion• Listing 9.7: Initial zero crossings

• Function produces the following results:– Zeros occur just after– -6.3000 -4.6667 0.2333 5.9500

See line by linedescription ofrecursive functionon page 221.

Page 59: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 59

Examples of Recursion

• Recursive Refinement of the Estimate– Decide to compute the exact value of the first

positive root, occuring at the third crossing– Recursive function to find the third root works on

the principle of binary division– Three characteristics of recursion implemented:

• Terminating condition is when the two values are within an acceptable error, say 0.001

• Otherwise, we find the middle of this x range, mx, find its f(mx), and then make the recursive call either with [x(1) mx] or [mx x(2)], depending on the sign of mx

Page 60: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 60

Examples of Recursion

• Recursive Refinement of the Estimate– Three characteristics of recursion implemented:

• Will always converge because each recursive call halves the distance between the x limits

– Performance issues:• Little slower in computational speed than Newton’s

method (uses slope to do computations)

• Very strong and essentially immune from the instability suffered by Newton’s method on undulating data

Page 61: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 61

Examples of Recursion

• Recursive Refinement of the Estimate: Listing 9.8: Recursive root finding

See line by linedescription ofrecursive functionon page 222.

Page 62: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 62

Engineering Example: Robot Arm Motion

• Problem of programming the arm of a robot to move in a straight line; see figure below:

Page 63: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 63

Engineering Example: Robot Arm Motion

• Robot arm consists of two jointed limbs of lengths r1 and r2 at angles and respectively

• Objective: calculate the sequence of values of and that will guide the end of the arm along the straight line:

• We will first address a necessary component of the problem

1 2x y r r

Page 64: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 64

Engineering Example: Robot Arm Motion

• Immediate Objective– Subproblem: determine for a given value of the

value that will place the end of the arm at some place on the line

– The coordinates for the end of the arm are

2 1 2

2 1 2

cos cos

sin sin

x r r

y r r

Page 65: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 65

Engineering Example: Robot Arm Motion• Immediate Objective

– We need to solve this for F() = 0:

– If we are given the values for r1, r2 and the angle , we will use the method of Section 9.9.3 to find the value(s) of that satisfy this equation

– Inspection of the function plot of the robot arm tells us we might expect two answer, one with a small negative value and one “bending backwards” at an angle greater than 90 degrees

1 2 1 2 1 2( ) cos cos sin sinF r r r r r r

Page 66: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 66

Engineering Example: Robot Arm Motion

• Immediate Objective– Figure below gives a plot of this function for r1 = 4,

r2 = 3 and = 30 degrees

Page 67: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 67

Engineering Example: Robot Arm Motion

• Immediate Objective– Two values of that satisfy the equation for small,

positive values of one around -30 degrees and one around 110 degrees

Page 68: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 68

Engineering Example: Robot Arm Motion

• Solution to the Subproblem– No analytical solution– Find the approximate location of the zero crossings

and then use a recursive function to find the exact roots

Page 69: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 69

Engineering Example: Robot Arm Motion

• Solution to the Subproblem – Listing 9.9: Finding arm position:

Page 70: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 70

Engineering Example: Robot Arm Motion• Solution to the Subproblem-Output:

Page 71: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 71

Engineering Example: Robot Arm Motion• Solution to the Subproblem

– Observations based on Listing 9.9• Parameters of the problem are established as GLOBAL

variables to avoid overhead cost of passing them into recursive functions

• We then sample the possible range of beta values with enough values to identify the zero crossings, and compute the corresponding values of F(beta)

• Estimate the zero locations by multiplying adjacent function values and display the results

• Call the recursive function to find the zero crossing

Page 72: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 72

Engineering Example: Robot Arm Motion• Solution to the Subproblem

– Listing 9.10: Function for zeros

Page 73: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 73

Engineering Example: Robot Arm Motion• Solution to the Subproblem

– Comments on Listing 9.10: Function for zeros• First gain access to the global parameters

• Then computes the left-hand side of the required equation, equation 4 in the text

Page 74: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 74

Engineering Example: Robot Arm Motion• Solution to the Subproblem

– Listing 9.11: Recursive zero finder

Page 75: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 75

Engineering Example: Robot Arm Motion• Solution to the Subproblem

– Comments on Listing 9.11• Computes the y values corresponding to the x limits

• Checks the terminating condition and return the [x y] coordinates of the result

• Finds the x and y values of the midpoint

• If the midpoint is on the opposite side of the x axis from the lower limit, make a recursive call using these limits

• Otherwise, make the recursive call using the midpoint and the upper limit

Page 76: Covenant College November 5, 20151 Douglas R. Sizemore, Ph.D. Professor of Computer Science COS 131: Computing for Engineers Chapter 9: Recursion This.

April 21, 2023 76

Engineering Example: Robot Arm Motion• Appreciation for Engineering Students

– Note from this example that a modest amount of code is all that is required to create an elegant solution to a nontrivial problem