# track total function calls using a global variable global fibcallcounter fibcallcounter +=1

Similar documents
Math 4242 Fibonacci, Memoization lecture 13

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

Measuring Efficiency

Algorithm Design and Recursion. Search and Sort Algorithms

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

CS 173, Running Time Analysis, Counting, and Dynamic Programming. Tandy Warnow

School of Informatics, University of Edinburgh

Lecture 12: Dynamic Programming Part 1 10:00 AM, Feb 21, 2018

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

For this chapter, switch languages in DrRacket to Advanced Student Language.

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)

Module 05: Types of recursion

APCS-AB: Java. Recursion in Java December 12, week14 1

6.001 Notes: Section 4.1

1 Dynamic Programming

11 and 12 Arithmetic Sequence notes.notebook September 14, 2017

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

Last week: Breadth-First Search

CSC-140 Assignment 4

The Knapsack Problem an Introduction to Dynamic Programming. Slides based on Kevin Wayne / Pearson-Addison Wesley

Introduction to Algorithms / Algorithms I Lecturer: Michael Dinitz Topic: Dynamic Programming I Date: 10/6/16

RECURSION, RECURSION, (TREE) RECURSION! 3

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Sorting lower bound and Linear-time sorting Date: 9/19/17

RECURSION, RECURSION, (TREE) RECURSION! 2

MEMOIZATION, RECURSIVE DATA, AND SETS

Lecture 6 CS2110 Spring 2013 RECURSION

Lecture #5: Higher-Order Functions. A Simple Recursion. Avoiding Recalculation. Redundant Calculation. Tail Recursion and Repetition

Recursion. Recursion [Bono] 1

UNIT 5B Binary Search

ENVIRONMENT DIAGRAMS AND RECURSION 2

All about Fibonacci: A python approach

There are some situations in which recursion can be massively inefficient. For example, the standard Fibonacci recursion Fib(n) = Fib(n-1) + Fib(n-2)

RECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012

Problem solving paradigms

5.1 The String reconstruction problem

CS116 - Module 5 - Accumulative Recursion

RECURSION 3. 1 Recursion COMPUTER SCIENCE 61A. June 30, 2016

Unit #2: Recursion, Induction, and Loop Invariants

6.00 Notes On Big-O Notation

Recurrences and Memoization: The Fibonacci Sequence

CIS 194: Homework 6. Due Wednesday, 4 March. Fibonacci numbers. It s all about being lazy.

Getting to places from my house...

Arithmetic Sequences

recursive algorithms 1

Introduction to Computer Science and Programming for Astronomers

INTERPRETERS AND TAIL CALLS 9

Reading 8 : Recursion

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

Agenda. The worst algorithm in the history of humanity. Asymptotic notations: Big-O, Big-Omega, Theta. An iterative solution

Unit #3: Recursion, Induction, and Loop Invariants

Programming Principles

RECURSION. Many Slides from Ken Birman, Cornell University

Spring 2012 Homework 10

Algorithm Analysis CISC4080 CIS, Fordham Univ. Instructor: X. Zhang

In math, the rate of change is called the slope and is often described by the ratio rise

Racket: Macros. Advanced Functional Programming. Jean-Noël Monette. November 2013

9/16/14. Overview references to sections in text RECURSION. What does generic mean? A little about generics used in A3

10.4 Linear interpolation method Newton s method

CS1 Lecture 15 Feb. 18, 2019

Algorithm Design and Analysis

Dijkstra s algorithm for shortest paths when no edges have negative weight.

CS 206 Introduction to Computer Science II

Environment Diagrams and Recursion Fall 2017 Discussion 2: September 6, 2017 Solutions. 1 More Environment Diagrams

Dynamic Programming Intro

Recursive Definitions

ENVIRONMENT DIAGRAMS AND RECURSION 2

Horn Formulae. CS124 Course Notes 8 Spring 2018

MergeSort, Recurrences, Asymptotic Analysis Scribe: Michael P. Kim Date: April 1, 2015

1. (15 points) Solve the decanting problem for containers of sizes 199 and 179; that is find integers x and y satisfying.

CMSC 451: Lecture 10 Dynamic Programming: Weighted Interval Scheduling Tuesday, Oct 3, 2017

Lecture 7 CS2110 Fall 2014 RECURSION

Dynamic Programming. See p of the text

61A LECTURE 15 MEMOIZATION, RECURSIVE DATA, SETS

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

n! = 1 * 2 * 3 * 4 * * (n-1) * n

CS 380 ALGORITHM DESIGN AND ANALYSIS

I. Recursive Descriptions A phrase like to get the next term you add 2, which tells how to obtain

RECURSION, RECURSION, (TREE) RECURSION! 3

ITERATION AND RECURSION 3

Class 6: Efficiency in Scheme

CSI33 Data Structures

CS201 Discussion 7 MARKOV AND RECURSION

CSE : Python Programming

CSCI 121: Recursive Functions & Procedures

CS 4349 Lecture September 13th, 2017

1 Dynamic Programming

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees

Decision-Making and Repetition

1 Greedy algorithms and dynamic programming

Algorithmics. Some information. Programming details: Ruby desuka?

Recursion(int day){return Recursion(day += 1);} Comp Sci 1575 Data Structures. Recursive design. Convert loops to recursion

Introduction to Programming I

Fruitful Recursion (recursion that returns a value)

CMPSCI 187: Programming With Data Structures. Lecture 5: Analysis of Algorithms Overview 16 September 2011

Object-Oriented Programming and Design D0010E. Interactive lecture 2. Overview of the lecture. Writing larger classes Documentation Recursion

Twelve Simple Algorithms to Compute Fibonacci Numbers

6.001 Notes: Section 15.1

Decorators in Python

Computer Algorithms. Introduction to Algorithm

Transcription:

Math 4242 Fibonacci, Memoization lecture 13 Today we talk about a problem that sometimes occurs when using recursion, and a common way to fix it. Recall the Fibonacci sequence (F 0, F 1, F 2,...) that occurs naturally in many places in nature: F 0 = 0 and F 1 = 1, and for n > 1, F n = F n 1 + F n 2. Because the sequence is defined recursively, it is not surprising we can write a recursive function that computes the sequence: def fib(n): Computes Fibonacci sequence recursively track total function calls using a global variable global fibcallcounter fibcallcounter +=1 Check for the base cases fib(0) and fib(1) first so the recursion eventually ends, otherwhise use recursion if n==1: return 1 elif n==2: return 1 else: val = fib(n-1) + fib(n-2) print "Determined (with help) that fib(",n,") = ",val return val fib(6) see how calls to fib function grows as input n grows for i in range(1,1): print i, fib(i) print "took ", fibcallcounter, "calls to fib function" 1

It is instructive to consider a table for n = 10, 20, 30,... to get an idea of the algorithmic complexity ( cost ) of this algorithm. One sees that when n gets around 50 this function slows down quite noticably and then seems to stop working. As you will see on the assignment, using this algorithm to compute the F n requires almost 2 n calls to the fib function (in total counting calls at lower levels of the recursion hierarchy). As a rule of thumb Modern computers can do 2 64 things in a day where each thing is a very simple operation like one of the state transitions we talked about so long ago. So we could never use this algorithm to compute F 100, for example, as that would require 2 100 64 = 2 36 = 68719476736 days (188 million years). THE POINT?: Algorithms where the running time is an EXPONENTIAL function of the input can only deal with small inputs. Why is the program taking so long? Thinking about the tree of recursive function calls made by this algorithm is helpful. See the diagram of function calls. Notice how visualizing the recursion highlights the fact that the computer is solving the same subproblem over and over again. In a situation like this there are techniques that can help. It is only useful when the computer is spending most of its time solving the same subproblems over and over again. This can happen somewhat in recursive functions but also in other areas. There are many ways to solve this problem once we recognize it. The simplest is to REMEMBER the results of our previous work! For the Fibonnacci sequence, we can remember results very easily: we ll just create a global array to store the various Fibonacci numbers once we ve computed them. See attached code. This process of remembering is sometimes called Memo-ization (from memo/table ). Also called table lookup. The memo-ized version of the recursive Fibonnacci function has complexity O(n). Again visualizing the recursive call tree makes this clear the tree is still about n levels deep but it doesn t keep branching out like the first time. This keeps the total number of calls to the fib function a small constant times n. Interestingly, most people, if asked to compute the n th Fibonacci number (say n=10) will compute them starting at the smallest and working up, so computing F 0, F 1, F 2, F 3, and so on. In this case they will implicitly be remembering and using their previous work. The algorithmic version of this results in an O(n) algorithm also. So recursion is a beautiful idea and allows for slick little functions to be written (less code) but sometimes important details are hiding underneath. Recursion is essentially the mathematical induction technique. Many problems that can be solved by induction have a nice recursive method associated with it. You may know of another method for finding the n th Fibonnacci number: In particular the algorithm utilizing the closed-form expression formula for the nth Fibonacci number, namely F n = φn (1 φ) n 5, where φ = 1+ 5 2. (1) An algorithm implementing this function requires approximately 4 log 2 (n) multiplications and a small number (independent of n) of other arithmetic operations, and so is a O(log 2 (n)) algorithm and thus is much faster than the above algorithms. However this algorithm is very specific to the Fibonacci numbers and has a lot of knowledge about the numbers built-in to the formula, so not surprisingly it is the fastest. 2

3

4

Example of a recursive function (to compute fibonacci numbers) that uses the technique of memoization MemoFib = [0]*1000 MemoFib[1]=1 MemoFib[2]=1 we ll remember up to 1000 numbers def fibm(n): global fibcallcounter fibcallcounter +=1 needed to change a variable defined globally/out if MemoFib[n]!= 0 : we ve seen this before... return remembered value return MemoFib[n] MemoFib[n] = fibm(n-1) + fibm(n-2) return MemoFib[n] n=300 print( "Fibonnacci number ", n, " is ", fibm(n) ) print( "fibm took ",fibcallcounter, "calls." ) 5