Download presentation
Presentation is loading. Please wait.
Published byDominic Higgins Modified over 9 years ago
1
Covenant College November 5, 20151 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.
2
Covenant College November 5, 20152 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
3
Covenant College November 5, 20153 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?
4
Covenant College November 5, 20154 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
5
Covenant College November 5, 20155 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
6
Covenant College November 5, 20156 Concept: The Activation Stack Concept of a stack – picture representation of a simple stack: Illustration of a simple stack data structure; can only push a data item onto the stack and pop a data item off of the stack.
7
Covenant College November 5, 20157 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
8
Covenant College November 5, 20158 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
9
Covenant College November 5, 20159 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
10
Covenant College November 5, 201510 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
11
Covenant College November 5, 201511 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
12
Covenant College November 5, 201512 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
13
Covenant College November 5, 201513 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
14
Covenant College November 5, 201514 Implementing a Recursive Function in MATLAB General template for a recursive function in MATLAB:
15
Covenant College November 5, 201515 Implementing a Recursive Function in MATLAB Guidelines for implementing a recursive function: –The can be any legal variable name –The variable 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
16
Covenant College November 5, 201516 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 tests –The entries are the values(s) of the result(s) at the terminating condition(s) –Second design decision is to determine the - 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
17
Covenant College November 5, 201517 Implementing a Recursive Function in MATLAB Guidelines for implementing a recursive function: –Last design decision is to determine how to compute the of the recursive call to ensure that the process moves towards at least on of the terminating condition N> states
18
Covenant College November 5, 201518 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 line description of recursive function on page 207.
19
Covenant College November 5, 201519 Implementing a Recursive Function in MATLAB Exercise 9.1: Analyzing recursive behavior Smith text, page 208, top
20
Covenant College November 5, 201520 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
21
Covenant College November 5, 201521 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?
22
Covenant College November 5, 201522 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
23
Covenant College November 5, 201523 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
24
Covenant College November 5, 201524 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
25
Covenant College November 5, 201525 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
26
Covenant College November 5, 201526 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
27
Covenant College November 5, 201527 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
28
Covenant College November 5, 201528 Exceptions Generic Exception Implementation –Listing 9.2: MATLAB script using exception handling: See line by line description of recursive function on page 211.
29
Covenant College November 5, 201529 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
30
Covenant College November 5, 201530 Exceptions Generic Exception Implementation –Exercise 9.2: Processing exceptions –Smith text, page 212, middle
31
Covenant College November 5, 201531 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?
32
Covenant College November 5, 201532 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
33
Covenant College November 5, 201533 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
34
Covenant College November 5, 201534 Exceptions Template 9.3: General template for a wrapper function
35
Covenant College November 5, 201535 Exceptions Template 9.3: General template for a wrapper function –First function named is the wrapper function
36
Covenant College November 5, 201536 Exceptions Listing 9.3: Wrapper implementation for the factorial function See line by line description of recursive function on page 214.
37
Covenant College November 5, 201537 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
38
Covenant College November 5, 201538 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
39
Covenant College November 5, 201539 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
40
Covenant College November 5, 201540 Tail Recursion Template 9.4: General template for tail recursion Note wrapper function takes on added responsibility Of calling the helper function with an additional parameter That is the initial result
41
Covenant College November 5, 201541 Tail Recursion Listing 9.4: Tail recursive factorial implementation See line by line description of recursive function on page 216.
42
Covenant College November 5, 201542 Tail Recursion Exercise 9.4: Writing the tail recursive factorial Smith text, page 216, bottom
43
Covenant College November 5, 201543 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
44
Covenant College November 5, 201544 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
45
Covenant College November 5, 201545 Examples of Recursion Three examples of recursive programming: –The detection of palindromes –Computing the Fibonacci series of numbers –Finding zeros of a function
46
Covenant College November 5, 201546 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
47
Covenant College November 5, 201547 Examples of Recursion Detecting Palindromes –Design of recursive function isPal( ): Function isPal( ) terminates if the has zero or one character, returning true Terminates if the first and last characters are not equal, returning false Otherwise the function returns isPal( ), 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
48
Covenant College November 5, 201548 Examples of Recursion Detecting Palindromes: Listing 9.5 –Recursive palindrome detector See line by line description of recursive function on page 218.
49
Covenant College November 5, 201549 Examples of Recursion Fibonacci Series –Named for the Italian mathematician Leonardo Piasano Fibonacci –Studying the growth of rabbit populations in the eleventh century Computing Rabbit Populations
50
Covenant College November 5, 201550 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
51
Covenant College November 5, 201551 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
52
Covenant College November 5, 201552 Examples of Recursion Fibonacci Series: Listing 9.6: Fibonacci function Fibonacci in the created order
53
Covenant College November 5, 201553 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
54
Covenant College November 5, 201554 Examples of Recursion Zeros of a Function –Consider a function f(x): –This function is plotted on the next slide
55
Covenant College November 5, 201555 Examples of Recursion Zeros of a Function –Plot of function:
56
Covenant College November 5, 201556 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
57
Covenant College November 5, 201557 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
58
Covenant College November 5, 201558 Examples of Recursion Listing 9.7: Initial zero crossings Function produces the following results: –Zeros occur just after –-6.3000-4.66670.23335.9500 See line by line description of recursive function on page 221.
59
Covenant College November 5, 201559 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
60
Covenant College November 5, 201560 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
61
Covenant College November 5, 201561 Examples of Recursion Recursive Refinement of the Estimate: Listing 9.8: Recursive root finding See line by line description of recursive function on page 222.
62
Covenant College November 5, 201562 Engineering Example: Robot Arm Motion Problem of programming the arm of a robot to move in a straight line; see figure below:
63
Covenant College November 5, 201563 Engineering Example: Robot Arm Motion Robot arm consists of two jointed limbs of lengths r 1 and r 2 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
64
Covenant College November 5, 201564 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
65
Covenant College November 5, 201565 Engineering Example: Robot Arm Motion Immediate Objective –We need to solve this for F( ) = 0: –If we are given the values for r 1, r 2 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
66
Covenant College November 5, 201566 Engineering Example: Robot Arm Motion Immediate Objective –Figure below gives a plot of this function for r 1 = 4, r 2 = 3 and = 30 degrees
67
Covenant College November 5, 201567 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
68
Covenant College November 5, 201568 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
69
Covenant College November 5, 201569 Engineering Example: Robot Arm Motion Solution to the Subproblem – Listing 9.9: Finding arm position:
70
Covenant College November 5, 201570 Engineering Example: Robot Arm Motion Solution to the Subproblem-Output:
71
Covenant College November 5, 201571 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
72
Covenant College November 5, 201572 Engineering Example: Robot Arm Motion Solution to the Subproblem –Listing 9.10: Function for zeros
73
Covenant College November 5, 201573 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
74
Covenant College November 5, 201574 Engineering Example: Robot Arm Motion Solution to the Subproblem –Listing 9.11: Recursive zero finder
75
Covenant College November 5, 201575 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
76
Covenant College November 5, 201576 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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.