A few useful items for the π Project

How to plot a list. First, make a list:

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

Plotting is easy with ListPlot:

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

ListPlot[{{3,6,2,4},{1,2,1,2}}]

The Range function returns a list of integers:

Range[10]

Range[4,10]

The Map function lets evaluate your function on a specified list:

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

Map also has a shorthand operator:

CatalanNumber /@ {4,5,6}

Fibonacci Numbers

The following is a recursive formula for the Fibonacci numbers:

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

Try it:

f[5]

Map[f,Range[10]]

Use the shorthand:

f /@ Range[10]

Timing[f[20]]

Timing[f[21]]

Timing[f[22]]

Write a function to get the runtime:

fruntime[n_]:=Timing[f[n]][[1]]

Try it out:

fruntime[22]

Now make a plot of runtimes:

ListPlot[fruntime/@Range[30]]

This is not going to allow us to compute big Fibonacci numbers!

Fibonacci : Iterative Approach

Write a Module that computes Fibonacci numbers using a loop and two accumulators (to store the previous two Fibonacci numbers).

goal : computeFib[n] will return the nth Fibonacci number

computeFib[n_]:=Module[{acc0=0, acc1=1, next},
Do[
next=acc0+acc1;    (* compute the next Fibonacci number *)
acc0=acc1;                  (* shift the values in *)
acc1=next,                  (*     the accumulators *)
{k,2,n}
];
acc1
]

Try it out:

computeFib[5]

computeFib /@ {1,2,3,4}

computeFib /@ Range[20]

computeFib[100]

Ratios of Fibonacci Numbers

Make a big list of Fibonacci numbers:

fibs=computeFib/@Range[100]

I want to compute 99 ratios all at once. First I will “slice” the big list. I want the first 99 entries, and also the last 99 entries.

fibA=fibs[[1;;99]];
fibB=fibs[[2;;100]];

Compute 99 ratios :

ratios=fibB/fibA;
N[ratios]

ListPlot[ratios]

ratios[[99]]

N[%,100]