I love you

Introduction

We will spend the first two weeks to go through some simple Mathematica programming basics. 

Most Important advice: CONSTANTLY CONSULT THE HELP FUNCTION IN MATHEMATICA.

As a starter, we shall  go through a series of simple exercises. During the course of the exercises, you shall pick up some simple knowledge of how to ‘speak’ in Mathematica language. After these exercises, students should have gained sufficient ‘feel’ of how to use Mathematica for more complicated situations that will in the subsequent chapters.

Print “Hello world”

str="hello world";
A=False;
Z=1;
NumericQ[A]

Z
str

NumericQ[Pi]

String and Number

str="This is a string";
number=4;
Print[str];
Print[number];

str1="I";str2="love";str3="you";
Print[str1," ",str2," ",str3];
str123=str1<>" "<>str2<>" "<>str3;
Print[str123]

str4="4";str5="5";
numeric4=ToExpression[str4];
str101=ToString[101];
Print[str101];Print[StringQ[str101]]

A simple arithmatic calculation

a=1.0;b=2.0;
c=a+b;
Print["c= ",c]

Arithmatic operations in Mathematica: Sqrt[],^,Ln[],Exp[],Sin[], etc.

Sqrt[2]
Exp[10]
Log[1]
Log[E]
Cos[Pi/2]
Sin[Pi/2]
10^2
10!
10^(1/3.0)

N[Sqrt[2]]
N[Pi]
N[E]

x=Sin[Pi/2];
ArcSin[x]

Log[10,100]

100^(1/2)

N[Sin[31Degree]]

More complicated Arithmatic operations

1.2^(1/2)Exp[-1/2]
N[Tan[45Degree]]
N[Tan[Pi/4]]

Pi*Sqrt[Sin[62Degree]*2^(-0.5)*E^(-2.5)]

1. Graph Plotting

Define a simple function f = (x - a)^2 + c.
Define a function of single variable - A Gaussian function, f(x)=(1/(σ(Sqrt[2π])))(e^(-((((x-μ))^2)/(2(σ^2))))).
Plot the function in terms of x.
Plot two functions (for two values of sigma) in a single graph

x1=-5.0;x2=5.0;

a=1.0;c=2.0;
f1[x_]:=(x-a)^2+c;

plotf1=Plot[f1[x],{x,x1,x2},
PlotRange->{{-1,2},{0,15}},
AxesLabel->{"x (time)","y (distance)"},
PlotLabel->"This is the name of the plot",
PlotStyle->{Green}
];



mu=0;
f[x_,sigma_]:=(1/(sigma*Sqrt[2 Pi]))*Exp[-0.5(x-mu)^2/sigma^2];


plotf1=Plot[{f[x,1],f[x,2]},{x,x1,x2},
PlotRange->{0,0.5},
AxesLabel->{"x (time)","y (distance)"},
PlotLabel->"This is the name of the plot",
PlotStyle->{Green,Red}
];

Print[plotf1];

list={0,4.5,7,8};
list[[1]]
list[[3]]

list2D={{1,1},{2,2},{3,3},{5,5}};
ListPlot[list2D,
PlotJoined->True,
Mesh->All
]

mu=0;sigma=1;
f[x_]:=(1/(sigma*Sqrt[2 Pi]))*Exp[-0.5(x-mu)^2/sigma^2];

NP=60;
deltax=2.0Pi/NP;
x[i_]:=i*deltax;
txf=Table[{x[i],f[x[i]]},{i,0,NP}];
lptxf=ListPlot[txf,PlotRange->All];
plotfx=Plot[f[x],{x,0,2Pi}];
Show[lptxf,plotfx]

2. ListPlot.

Creat a set of paired data points. 
Plot a set of data point in a x-y plane.
Creat another set of paired data points. 
Plot two sets of data point in a x-y plane.
Cosmetics - labelling of axes, title of graph, aspectratio, color, plotrange, framming.
Merge the function plot and data point plot in a single graph using Show.

data1={{1,0.2},{2,0.4},{3,0.9},{4,0.16}};
ListPlot[data1,PlotJoined->True];
data2={{5,0.2},{6,0.4},{7,0.9},{8,0.16}};
ListPlot[{data1,data2},PlotJoined->True,
PlotStyle->{Red,Blue},
AspectRatio->1,
(*Frame->True,*)
(*PlotRange->{{0,4},{0,10}},*)
PlotRange->All,
AxesLabel->{x,y},
Mesh->Full
]

g1=ListPlot[data1,PlotJoined->True,Mesh->Full,PlotStyle->Red];
(*f[x_]:=(1/(sigma*Sqrt[2 Pi]))*Exp[-0.5(x-mu)^2/sigma^2];*)
g2=Plot[f[x],{x,0,4},PlotStyle->Blue];
Show[{g1,g2}]

3. I/O, for loop, exporting, importing.

Generate random values in a for loop.
Generate pairs of data points into a .dat file
Create a for loop to generate two set of .dat files. Use Append for this purpose.
Read in one data set from one of the .dat files generated. List plot this data.
Use for loop to read in two data set and listplot both on the same graph.
Command to use: Random[];Append; Export;Import;StringQ;NumberQ;ToString;<>;indexed list, data[i];

a=Table[i,{i,1,10}]
Export["a.dat",a,"List"];

a=Import["a.dat","List"]

For[j=1,j≤5,j++,

(***********)
B={};
For[i=1,i≤10,i++,
A={i,Random[]};
B=Append[B,A];
];(*end for i*)
filename="data"<>ToString[j]<>".dat";
Export[filename,B,"Data"];
(***********)
];(*end for j*)

FileNames[]

Directory[]

For[j=1,j≤5,j++,
filename="data"<>ToString[j]<>".dat";
importlist=Import[filename,"Data"];
Print[ListPlot[importlist]]
];(*end for j*)

If loop

For[
i=1,i≤10,i++,
If[
i<5,Print["i < 5"]
,(*else *)
Print["i>5"];
];(*end if*)
];(*end for *)

ran=Random[];
Print[ran];
If[
ran < 0.5,Print["I love you"];
,
Print["I love you not"];
];

i=0;
While[i<10,
i = i -1;
];(*end while*)
Print[i];

ran=0.0;
While[ran<0.9999,
ran=Random[];
Print[ran];
];
Print["after exiting the while loop, ran = ",ran];

3.1 While loop.Random[],Random[Real,Range,n]

ran=Random[];
If[ran>0.5,Print["ran is > 0.5"];,(*else*)Print["ran is ≤ 0.5"];];
Print[ran]

ranR=Random[Real,{-1,5},2];
Print[ranR]

ran=0.0;
While[ran<0.5,ran=Random[];
Print["ran is still < 0.5 "];];(*end while*)Print[ran]

i=0;
While[i<160,i=i+1;];(*end while*)Print["when exited from while loop, i = ",i];

f3[x_]:=2 x^2+x-3.0;
xtrial=100;
While[Abs[f3[xtrial]]>0.0001,xtrial=Random[Real,{0,5},2];];
Print["xtrial, f3[xtrial] = ",{xtrial,f3[xtrial]}];


3.2 Append

A={1,2,3};
B=Append[A,4];
Append[B,89];
F={a,b,c,d,e};
F=Append[F,q]

{a,b,c,d,e,q}

container={};
For[i=1,i≤10,i++,ran=Random[];
container=Append[container,ran];];(*end for*)Print[container]

{0.285997,0.774739,0.861657,0.117736,0.2755,0.756804,0.106742,0.14408,0.826582,0.0754129}

In the following example,we generate two sets of data,and export them as.dat files,named sequentially as “data1.dat”,
“data2.dat”.

appended={};
For[i=1,i≤10,i++,ran=Random[];
dat={i,ran};
(*Print[appended];*)appended=Append[appended,dat];](*end for*)
Export["data1.dat",appended];

For[i=1,i≤10,i++,ran=Random[];
dat={i,ran};
(*Print[appended];*)appended=Append[appended,dat];](*end for*)
Export["data2.dat",appended];

Now we write a loop to import these.dat files,data1.dat,data2.dat.The names of the,dat files are generated using ToString in the for loop.For[i=1,i≤2,i++,istr=ToString[i];
filename="data"<>istr<>".dat";
(*Print[istr," ",StringQ[istr]," ",NumberQ[istr]];*)Print[filename];
data[i]=Import[filename];];(*end for i*)Print[data[1]]
Print[data[2]]

4. Further exercises.

Abstract descrete data points from the gaussian by appending the data points into a list. ListPlot the list in the same graph with the funciton. Take the range of x from [-1,1]. Number of descrete points = 5;

(*x[1]=-1.0;x[2]=-0.5;x[3]=0;x[4]=0.5;x[5]=1.0;
Table[x[i],{i,0,5}];*)
sigma=1;mu=0;
f[x_]:=(1/(sigma*Sqrt[2 Pi]))*Exp[-0.5(x-mu)^2/sigma^2];

xini=-1.0;xlast=1.0;NP=20;
deltax=(xlast-xini)/NP;
x[i_]:=xini+i*deltax;
tx=Table[x[i],{i,0,NP}];
txfx=Table[{x[i],f[x[i]]},{i,0,NP}];
g1=ListPlot[txfx(*,PlotJoined->True*),Mesh->Full,PlotStyle->{Red,PointSize->0.02}];
g2=Plot[f[x],{x,-1,1},PlotStyle->Blue];
Show[g1,g2]

Example: The graph as shown is produced using Show[] and ListPlot. The equation for a circle with unit radius is (x^2)+(y^2)=1. Produce the graph.

a=Show[ListPlot[Table[{x,Sqrt[1-x^2]},{x,-1,1,0.05}],PlotRange->{{-1.05,1.05},{-1.05,1.05}},AspectRatio->1,Frame->True],AxesLabel->{y,x}];
b=Show[ListPlot[Table[{x,-Sqrt[1-x^2]},{x,-1,1,0.05}],AspectRatio->1,Frame->True]];
Show[{a,b}]

5. Bisection method

Find the root of a simple function, xtan x = x. Purpose - to familiarlise student with logical structure of a program. 
Command to use: While loop;

h[x_]:=x*Tan[x]-x;
Plot[h[x],{x,0,Pi/2}]

xinil=0.5;
xinir=1.0;
xl=xinil;xr=xinir;

xmid=(xl+xr)/2.0;

While[
Abs[h[xmid]]>0.001,

If[h[xmid]*h[xl]<0,
xr=xmid;
,(*else*)
xl=xmid;
];(*end if*)

xmid=(xl+xr)/2.0;
Print[Abs[h[xmid]]];
];(*end while*)
Print["the solution is: xsol = ",xmid];
Print["h[xsol] = ",h[xmid]];

6. Integrate with stochasitc method.

Use stochastic method to integrate the area under the curve of a all positive function, say, f = x^2 for x in [-1,1] as example.

Excercise: The graph as shown is produced using Show[],Plot and ListPlot. The equation for a circle with unit radius is (x^2)+(y^2)=1. Produce the graph.

Excercise: Use the stochastic method to evaluate the area of a gaussian with mu = 0, sigma = 1, for x in [-0.5,0.5].

Excercise: Find the root of (e^x)=-x+2 using the bisection method.

Excercise: There are three roots in x sin =-1.5x+3. Write a programme to find all of them.