MCS 275 Spring 2024
Emily Dumas
Reminders and announcements:
Full details in the project description.
Recursive function examples:
Let's write functions that compute the same things, but using iteration (loops) instead of recursion.
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 (naive) | 1.9s | ≫ age of universe |
recursive (memoized) | <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.