STOCHASTIC PROCESSES 37363

Introduction to Mathematica

Basic operations

The basic operations do what we would all expect:

3+3
12/4 (* division*)
1.1 * 2 (* multiplication *)

However, be careful about order of operations

3+2*3

If you want the addition to be performed first, use parentheses (the curved brackets).

(3+2)*2

Powers, (n^th)-roots, factorials, exponentials and logarithms

8^2 (* (8^2)*)
Sqrt[4] (* (4^(1/2)) *)
9^(1/3) (* (9^(1/3)) *)
4!
Exp[1.2] (* (E^1.2)*)
Log[Exp[1]] (* ln(e) *)

Notice how Mathematica evaluates the following expression

π

If you would like to see a decimal approximation of π, say with 6 digit precision, you can type

N[π,6]

Variables and lists

To do anything more than trivial work in Mathematica, we will need to be able to store results. We can store a single value into a variable:

x=12
x^2+1

Notice that the first line of the above code results in an output of 12. Very often you' ll want to suppress the output, and you can do so by placing a semicolon (;) at the end of the line

x=12; (* suppress the output*)
x^2+1

We can assign any expression to a variable

y=π^2 + Sin[π/3]

Note in the output above how Mathematica simplifies the Sine term

Very often, we' ll want to be able to construct and store a list (array) of values, indexed by some parameter. A common way to do so is

Table[z[i]=5*i,{i,1,5}]

To access the individual elements of this list :

z[2]
z[5]

To get a clear view of what is 'inside' z type:

?z

Notice from our work above that the variable x still holds the value 12 :

?x

We can delete the value and definition of x by using the Clear function:

Clear[x]
?x

This is very important to do, particularly if you are doing work in multiple notebooks (an assignment to 'x' in one notebook will be visible to all other open notebooks! This can lead to really annoying bugs!)

It is possible to build multiple lists with the one Table statement.

Clear[x,y,z]

Table[
x[i]=2*i; 
y[i]=3*i; 
z[i]=5*i, {i,1,5}];

?z

Be careful, the final statement before {i,1,5} has to be a comma, but each statement before must always end with a semicolon.

Creating a nested list and extracting elements.

table=Table[i+j,{i,1,4},{j,1,5}]
table[[1]]
table[[1,1]]

Functions

Specifying and using functions in Mathematica is easy :

Clear[f]
f[x_]:= Exp[x]
f[{I π,2}]

'f' defined above isn't really a function in the mathematical sense; it is simply a rule that takes x as input (specified here by the x_) and maps it to the formula Exp[x]. You can pass all kinds of different things to f, like real numbers:

f[Log[666]]
f[1.2]
f[(Sqrt[3])]

Or complex numbers (recall that (e^(i x))=cos(x)+i sin(x)) :

f[((I π)/2)] (* here the 'capital i' symbol represents I =(Sqrt[-1]) in Mathematica*)
f[I π] (* use palette on the side to get the prettier looking I*)

You can even pass lists/vectors to f!

f[{4.5,(3/7), -I π}]

Or using the "Map" function.

Map[f,{4.5,(3/7), -I π}]

The If statement

The 'If' statement in Mathematica has the following structure: 
If[condition, TrueExpr, FalseExpr]. 
So if 'condition' evaluates to TRUE, the system will run 'TrueExpr', otherwise it will run 'FalseExpr'

Clear[x]
x=RandomInteger[{1,100}]; (* randomly choose integer between 1 and 100, store in x *)
If[x ≤ 50, Print["x = " <>ToString[x] <> " <= 50"],
                     Print["x = " <>ToString[x] <> " > 50"]]

Loops

Oftentimes you will want to repeat tasks. Many programming languages offer so-called ‘ loops’ to let you do this.

Here is some “Do” loops.

Do[Print["This is line "<> ToString[i]],{i,1,5}]

Do[
  Print[ToString[i] <> " is an "<> 
    If[Mod[i,2]==0, 
      "even number", 
      "odd number"]
  ],
  {i,1,5}
]

Here is a "For" loop.

For[i=1,i≤5,i++,
  Print[ToString[i] <> " is an "<> 
    If[Mod[i,2]==0, 
      "even number", 
      "odd number"
    ]
  ]
]

Here is a While" loop.

i=1;
While[i≤5,
  Print[ToString[i] <> " is an "<> 
    If[Mod[i,2]==0,
      "even number", 
      "odd number"]
    ]
  i++
]

Graphs and plots

Mathematica provides an enormous range of plotting and graphing tools. This course only requires basic plotting. The first type is ListLinePlot. It simply requires a list of numbers as input. It also 'connects the dots' between successive points

Clear[randomWalk]
randomWalk=Join[{0.},Accumulate[RandomReal[{-1,1},{100}]]];
ListLinePlot[randomWalk]

To see just the dots, we can pass the list to ListPlot :

ListPlot[randomWalk]

Using “RandomFunction”.

StTable=RandomFunction[GeometricBrownianMotionProcess[1,1,10],{0,1,0.01}];
ListPlot[StTable,Joined->True,DataRange->{0,1},AxesLabel->{"t","(Subscript[S, t])"}]

Parametric plots.
Recall that the equation of a circle of radius r centred at (a, b) has equation (((x-a))^2)+(((y-b))^2)=(r^2). This equation can be written in parametric form as
x=a+r cos(t)
y=b+r sin(t)
The following code will plot the circle.

Clear[a,b,r]
a=1;
b=3;
r=2;
ParametricPlot[{a+r Cos[t],b+r Sin[t]}, {t,0,2π}]

3D plotting.

f[x_,y_]:=(((x+y))^3)Cos[x]Sin[x];
Plot3D[f[x,y],{x,-2π,2π},{y,-2π,2π},PlotRange->All,AxesLabel->{"x","y","f(x,y)"}]

Vector and Matrix Multiplication

v={v1,v2};    (* create vector-type list *)
m={{m11,m12,m13},{m21,m22,m23}};    (* create matrix-type nested list *)
v//MatrixForm
MatrixForm[m]
v.m//MatrixForm
m.m//MatrixForm    (* matrices must have correct shapes or error results *)
Transpose[m].m//MatrixForm

Summation, Integration and Differentiation

These summations are equivalent.

Sum[i,{i,1,10}]
(∑_(i=1)^10)i

Indefinite integrals are evaluated symbolically.

Integrate[Cos[x],x]
∫Cos[x]\[DifferentialD]x

Definite integrals can be evaluated symbolically.

Integrate[Cos[x],{x,0,(π/2)}]
(∫_0^(π/2))Cos[x]\[DifferentialD]x

Definite integrals can also be evaluated numerically.

NIntegrate[Cos[x],{x,0,(π/2)}]
(∫_0.^(π/2.))Cos[x]\[DifferentialD]x    (* this is actually symbolic integration and then numerical evaluation of integration limits - note use of decimal points *)

One can differentiate symbolically.

D[Cos[x],x]
(∂_x)Cos[x]

One can differentiate symbolically at a point.

D[Cos[x],x]/.x->(π/4)    (* note use of replacement rule *)
(∂_x)Cos[x]/.x->(π/4)    (* note use of replacement rule *)

One can differentiate numerically.

Needs["NumericalCalculus`"];
ND[Cos[x],x,(π/4)]
(∂_x)Cos[x]/.x->(π/4.)    (* this is actually symbolic differentiation followed by numerical replacement rule *)

Probability Functions

Plot of probability density function of 1D normal distribution.

μ=0;  σ=1;
pdf1D[x_]:=PDF[NormalDistribution[μ,σ],x];
Plot[pdf1D[x],{x,-3,3},AxesLabel->{"x","pdf1D(x)"}]

Plot of cumulative distribution function of 1D normal distribution.

μ=0;  σ=1;
cdf1D[x_]:=CDF[NormalDistribution[μ,σ],x];
Plot[cdf1D[x],{x,-3,3},AxesLabel->{"x","cdf1D(x)"}]

Plot of probability density function of 2D normal distribution.

μ={0,1};  Σ={{1,0},{0,3}};
pdf2D[x_,y_]:=PDF[MultinormalDistribution[μ,Σ],{x,y}];
Plot3D[pdf2D[x,y],{x,-3,3},{y,-5,6},AxesLabel->{"x",{y},"pdf2D(x,y)"}]

Plot of cumulative distribution function of 2D normal distribution.

μ={0,1};  Σ={{1,0},{0,3}};
cdf2D[x_,y_]:=CDF[MultinormalDistribution[μ,Σ],{x,y}];
Plot3D[cdf2D[x,y],{x,-3,3},{y,-5,6},AxesLabel->{"x",{y},"cdf2D(x,y)"}]