Math 4242 Fibonacci, Memoization lecture 13

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

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

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

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

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

Getting to places from my house...

Arithmetic Sequences

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

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

6.001 Notes: Section 4.1

Last week: Breadth-First Search

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

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

Problem solving paradigms

1 Dynamic Programming

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)

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

School of Informatics, University of Edinburgh

Introduction to Computer Science and Programming for Astronomers

Class 6: Efficiency in Scheme

10.4 Linear interpolation method Newton s method

5.1 The String reconstruction problem

Horn Formulae. CS124 Course Notes 8 Spring 2018

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

Dynamic Programming Intro

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

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

MEMOIZATION, RECURSIVE DATA, AND SETS

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

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

CS 380 ALGORITHM DESIGN AND ANALYSIS

CS 206 Introduction to Computer Science II

All about Fibonacci: A python approach

1 Dynamic Programming

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

6.00 Notes On Big-O Notation

1 Greedy algorithms and dynamic programming

CS221: Algorithms and Data Structures. Asymptotic Analysis. Alan J. Hu (Borrowing slides from Steve Wolfman)

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

Congruence Arithmetic

Lecture 6 CS2110 Spring 2013 RECURSION

INTERPRETERS AND TAIL CALLS 9

Recursion. Recursion [Bono] 1

Worksheet - Storing Data

Exact Algorithms Lecture 7: FPT Hardness and the ETH

4.1 Review - the DPLL procedure

Spring 2012 Homework 10

CIS 194: Homework 6. Due Monday, February 25. Fibonacci numbers

Algorithm classification

Algorithm Design and Recursion. Search and Sort Algorithms

Measuring Efficiency

Today. Types of graphs. Complete Graphs. Trees. Hypercubes.

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

Binary Trees

SORTING AND SEARCHING

CSC-140 Assignment 4

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

UNIT 5B Binary Search

Hanoi, Counting and Sierpinski s triangle Infinite complexity in finite area

The Beauty and Joy of Computing 1 Lab Exercise 9: Problem self-similarity and recursion - Python version

CS 4349 Lecture September 13th, 2017

Agenda. We ve done Growth of functions Asymptotic Notations (O, o,,!, ) Now Binary search as an example Recurrence relations, solving them

15-122: Principles of Imperative Computation, Fall 2015

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

6.001 Notes: Section 15.1

Lecture 6: Arithmetic and Threshold Circuits

Lecture 3: Linear Classification

MergeSort, Recurrences, Asymptotic Analysis Scribe: Michael P. Kim Date: September 28, 2016 Edited by Ofir Geri

CS1 Lecture 15 Feb. 18, 2019

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

Introduction to Algorithms / Algorithms I Lecturer: Michael Dinitz Topic: Shortest Paths Date: 10/13/15

Divide and Conquer Strategy. (Page#27)

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

CS 125 Section #4 RAMs and TMs 9/27/16

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

(Refer Slide Time: 00:51)

Section 0.3 The Order of Operations

RECURSION. Many Slides from Ken Birman, Cornell University

Week - 01 Lecture - 04 Downloading and installing Python

RECURSION, RECURSION, (TREE) RECURSION! 3

This session. Recursion. Planning the development. Software development. COM1022 Functional Programming and Reasoning

COMP4128 Programming Challenges

Lecture 3: Recursion; Structural Induction

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)

Streams. CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004

- Main approach is recursive, but holds answers to subproblems in a table so that can be used again without re-computing

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Approximation algorithms Date: 11/27/18

The following content is provided under a Creative Commons license. Your support

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

Algorithm Design and Analysis

RECURSION, RECURSION, (TREE) RECURSION! 2

Twelve Simple Algorithms to Compute Fibonacci Numbers

Memoization/Dynamic Programming. The String reconstruction problem. CS124 Lecture 11 Spring 2018

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Balanced Search Trees Date: 9/20/18

Module 05: Types of recursion

Algorithms. Ch.15 Dynamic Programming

CS302 Topic: Algorithm Analysis. Thursday, Sept. 22, 2005

The fringe of a binary tree are the values in left-to-right order. For example, the fringe of the following tree:

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 1, F 2,...) that occurs naturally in many places in nature: F 1 = 1 and F 2 = 1, and for n 3, 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: 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 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.

# 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] fibcallcounter=0 n=300 print( "Fibonnacci number ", n, " is ", fibm(n) ) print( "fibm took ",fibcallcounter, "calls." )