Exercises lecture 2

ClearAll["Global`*"];SetDirectory[NotebookDirectory[]]

Exercise 1 : Calculating Fibonacci Numbers

Write a Mathematica code to calculate Fibonacci numbers . The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding numbers . Your code should generate a list of Fibonacci numbers up to a specified limit . Requirements : The code should have a function that takes an integer n as input and generates a list of Fibonacci numbers up to the nth term . The code should display the list of Fibonacci numbers .

Clear[fibo,findfibo];
fibo1=1;
fibo2=1;
fibseq={1,1};findfibo[n_]:=Do[{fibo=fibo1+fibo2,fibo1=fibo2,fibo2=fibo,AppendTo[fibseq,fibo],If[i==n-2,Print[fibseq]]},{i,n-2}]
findfibo[10]

Clear[fibo];fibo[nmax_]:=RecurrenceTable[{a[n]==a[n-1]+a[n-2],a[1]==1,a[2]==1},a,{n,nmax}]
fibo[10]

fiblist[n_]:=Table[Fibonacci[i],{i,n}]
fiblist[10]

Exercise 2: plot a unit triangular region filled with random points, as in this plot

ic=0;n=10000;points={};
Do[{x=Random[Real,{-1,1}];y=Random[Real,{-1,1}];AppendTo[points,If[x>0 && y>0  && x+y<1,{x,y}]]},{i,n}]

ListPlot[points,Frame->True,AspectRatio->1,PlotRange->{{-2,2},{-2,2}}]

Exercise 3: plot N random parabolae (i.e. parabolae with random coefficients between -1 and 1)

Clear[x];n=100;parlist=Table[Random[Real,{-1,1}]*x^2+Random[Real,{-1,1}]*x+Random[Real,{-1,1}],{i,n}];
Plot[parlist,{x,-1,1},Frame->True]

Exercise 5. Define a function f[a_,prec_] that gives the numerical integral of Sin[Exp[-x^2 - y^2]] between -3 and a, both for x and y, where prec is the PrecisionGoal and also the WorkingPrecision digits. Make a ListPlot that shows how the time it takes the integral for a=3 depends on prec, with prec in the range 4-12. Show (visually) that the trend it is well approximated by an exponential. Don’t worry about warning messages!

Clear[a,f];f[a_,prec_]:=NIntegrate[Sin[Exp[-x^2-y^2]],{x,-3,a},{y,-3,a},PrecisionGoal->prec,WorkingPrecision->prec]
Timing[f[3,10]]

tab=Table[{nd,Timing[f[3,nd]][[1]]},{nd,5,10}];
ListLogPlot[tab]