Recursion and Plotting¶

Returning to the Fibonacci numbers,

$$ F_n = F_{n-1} + F_{n-2},$$

with $F_0 = 0$ and $F_1 = 1$.

Recursion refers to when something is defined in terms of itself or of its type. In math, a function would be applied in its own definition.

In [1]:
def myfib(n):
    if n == 0:
        fn = 0
    elif n == 1:
        fn = 1
    else:
        fn = myfib(n-1) + myfib(n-2)
    return fn
In [2]:
myfib(35)
Out[2]:
9227465
In [3]:
# importing packages takes following form
# import [name of package]
In [4]:
import time
In [5]:
t1 = time.time() # time is the package. the second time is the function
myfib(33)
print(time.time() - t1)
1.771052360534668
In [6]:
# let's import some other packages
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
In [7]:
x = np.linspace(0,10,100)
In [8]:
plt.plot(x, np.sin(x))
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.title("My First Plot")
Out[8]:
Text(0.5, 1.0, 'My First Plot')
In [9]:
plt.plot(x, np.sin(x),  label="sin(x)")
plt.plot(x, np.cos(x),  label="cos(x)")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.title("My First Plot")
plt.legend();

Practice!

  1. Define two functions and create a plot of those two functions (with appropriate labels)
  2. For the recursive Fibonacci function, make a plot of the Nth Fibonacci number VS. the time it takes to compute that number.