MCS 275 Spring 2023
Emily Dumas
Reminders and announcements:
Let's write iterative versions of factorial, Fibonacci, and paper folding. (Or as many as time allows.)
Let's compare the running time of the iterative and recursive solutions.
Why is recursive fact()
somewhat competitive, but fib()
is dreadfully slow?
Let's track the number of function calls.
fib
computes the same terms over and over again.
Instead, let's store all previously computed results, and use the stored ones whenever possible.
This is called memoization. It only works for pure functions, i.e. those which always produce the same return value for any given argument values.
math.sin(...)
is pure; random.random()
is not.
n=35 | n=450 | |
---|---|---|
recursive | 1.9s | > age of universe |
memoized recursive | <0.001s | 0.003s |
iterative | <0.001s | 0.001s |
Measured on my old office PC (2015, Intel i7-6700K) with Python 3.8.5
Recursive pure functions with multiple self-calls often benefit from memoization.
Memoization does not alleviate recursion depth limits.
Memoization trades running time for memory consumption.