A few useful items for the π Project

The Range function gives a list of integers:

Range[10]

Range[4,10]

Recall that we can make a list of function values with Table:

Table[ CatalanNumber[n], {n,1,10}]

Similarly, the Map function lets us evaluate a function on a list or range:

Map[ CatalanNumber, {4,5,6} ]

Map[ CatalanNumber, Range[10]]

Map has a shorthand operator:

CatalanNumber /@ {4,5,6}

Plotting a list is easy with ListPlot:

alist=CatalanNumber/@Range[10]

ListPlot[alist]

Fibonacci Numbers

Define an indexed variable that produces Fibonacci numbers:

fib[0]=0
fib[1]=1
fib[n_]:=fib[n-1]+fib[n-2]

Try it out:

{fib[5],fib[6],fib[7]}

Map[fib, Range[10]]

fib /@Range[0,10] (* use the shorthand for Map *)

?fib

How fast is this method of computing the Fibonacci numbers?

Timing[fib[10]]

The runtime is very close to zero. Let’s try a larger index:

Timing[fib[30]]

Make a function to extract the runtime from the pair returned by Timing:

myFibTime[n_]:=Timing[fib[n]][[1]] (* double brackets selects an element from a list *)

Map this onto the list 1, 2, ..., 30:

fibTimes=myFibTime/@Range[30]

Make a plot:

ListPlot[fibTimes]

Looks like exponential growth in runtime. Let’s try a faster approach.

computeFib[n_]:=Module[{a=0,b=1,next},
Do[
next=a+b;  
a=b;               (* shift the value of b to variable a *)
b=next,          (* shift the value of next to variable b *)
{n-1}    (* run the loop n-1 times *)
];
b   (* return b, which contains the nth Fibonacci number *)
]

Try it out:

computeFib /@ Range[10]

computeFib[100]

Timing[computeFib[100]]

Your turn: Investigate the ratio of consecutive Fibonacci numbers (Subscript[F, n])/(Subscript[F, n-1]):

N[computeFib[4]/computeFib[3]]