an introduction to mathematica (complete)an introduction to mathematica (complete) (quantitative...
TRANSCRIPT
An Introduction to Mathematica (complete)
(Quantitative Dynamic Macroeconomics, Lecture Notes, Thomas Steger, University of Leipzig)
This chapter provides a concise introduction to Mathematica. Instead of giving a rigorous discussion or a comprehen-sive summary of commands, the basic principles are demonstrated by going through some instructive examples. For asystematic introduction see, for instance, Gräbe and Kofler (2007) and Jankowski (1998) and the references citedtherein. For a concise summary of notation and basic calculation see the supplement (Section 7 below).
1. First steps
Basics 1We set up the equation "y=a+bx" and label it "equ"
equ = y a + b x
y a + b x
Next solve this equation for x by applying the command "Solve" and label the result "sol"
sol = Solve@equ, xD
::x →−a + y
b>>
One can extract the RHS of this solution as follows
sol@@1, 1, 2DD
−a + y
b
Basics 2Here we define a function f[x,y]
f@x_, y_D := x0.3 y0.7
and then ask Mathematica for the value of f[x,y] at x=10 and y=20
f@10, 20D
16.245
Notice the two different assignments which have been used so far: "=" is an immediate assignment and ":=" denotes a delayed assignment. The difference becomes clear using an example
a = Random@D; b := Random@D;
88a, a, a<, 8b, b, b<<
880.784854, 0.784854, 0.784854<, 80.795794, 0.953583, 0.379506<<
2. Equation solving
Single equations
à Analytical solution
At first, label the LHS of the quadratic equation "x2 + a x + b=0" to read "exp"
Clear@exp, a, b, xD; exp = x2 + a x + b;
Notice the assignment "exp=x2 + a x + b"! To check this assignment, evaluate the expression "exp"
exp
b + a x + x2
Here we use the command "Solve" to solve the equation "exp==0" w.r.t. x
Solve@exp 0, xD
::x →1
2−a − a2 − 4 b >, :x →
1
2−a + a2 − 4 b >>
2 QDM_Intro_complete.nb
We visualize the solution by plotting the quadratic equation. To plot the expression x2 + a x + b over x, we must specify the parameters a and b numerically
Clear@a, bD; a = 1; b = −1;
Plot@exp, 8x, −2, 2<, AxesLabel −> 8x, exp<, PlotStyle → [email protected]
−2 −1 1 2x
−1
1
2
3
4
5
x2 + x − 1
à Numerical solution
One can also determine the solution to the quadratic equation numerically. To this end, we apply the command "FindRoot".
Clear@a, bD; a = 1; b = −1; FindRoot@exp 0, 8x, −2<D
8x → −1.61803<
Observe that FindRoot does only find one solution! If we use another starting value for FindRoot, it may detect the other solution.
Clear@a, bD; a = 1; b = −1; FindRoot@exp 0, 8x, 2<D
8x → 0.618034<
QDM_Intro_complete.nb 3
System of equations
à Analytical solution
Consider the following non-linear system a1x1a1-1
x2a2 = a and a2x1
a1 x2a2-1
= b. Notice that this system represents the
first-order conditions of the problem maxIx1,x2M
9x1a1 x2
a2 - a x1 - b x2=.
Clear@a, bD; sys = 9α1 x1α1−1 x2α2 a, α2 x1α1 x2α2−1 b=;
The system is solved by applying "Solve"
sol = Solve@sys, 8x1, x2<D êê FullSimplify
::x1 →−H−1+α2L Log@aD+α2 Log@bD+H−1+α2L Log@α1D−α2 Log@α2D
−1+α1+α2 ,
x2 →Log@bD−Log@α2D+α1 HLog@aD−Log@bD−Log@α1D+Log@α2DL
−1+α1+α2 >>
Mathematica gives the solution in a somewhat unusual form. A manual derivation (see supplement below) andnumerical evaluation indicates that the result is correct.
Here we evaluate the solution for a baseline set of parameters
8α1, α2, a, b< = 80.3, 0.4, 0.1, 0.3<;
8sol@@1, 1, 2DD, sol@@1, 2, 2DD<
813.2077, 5.87009<
Manual solution (see below) gives
:b
α2
−α2−α1−α2 +1
a
α1
H−α1−α2 +1L+α1 α2H−α1−α2 +1L Hα1−1L ,
b
α2
α1−1−α1−α2 +1
a
α1
−α1−α1−α2 +1>
813.2077, 5.87009<
Graphically, the solution is the intersection of the curves, given by the two first-order conditions, in the (x1, x2)-plane.To illustrate we plot the two curves
curve1 = SolveAα1 x1α1−1 x2α2 a, x2E@@1, 1, 2DD;
curve2 = SolveAα2 x1α1 x2α2−1 b, x2E@@1, 1, 2DD;
4 QDM_Intro_complete.nb
Clear@α1, α2, a, bD; 8α1, α2, a, b< = 80.3, 0.4, 0.1, 0.3<;Plot@8curve1, curve2<, 8x1, 0, 16<, AxesLabel → 8x1, x2<,
PlotStyle → [email protected]
5 10 15x1
2
4
6
8
x2
à Supplement: manual derivations (available upon request)
à Simulation: sequence of numerical solutions (available upon request)
3. Differentiation and integration
A simple exampleDifferentiate the expression "x2 + a x + b" with respect to x and name the result "diff"
Clear@a, bD; diff = DAx2 + a x + b, xE
a + 2 x
Next, form the (indefinite) integral of the expression "diff" with respect to x
QDM_Intro_complete.nb 5
Integrate@diff, xD
a x + x2
There are several distinct ways to form a partial derivative
8D@Sin@xD, xD, ∂x Sin@xD, Sin'@xD<
8Cos@xD, Cos@xD, Cos@xD<
The total derivative can be formed using the command "Dt"
Dt@f@x, y, zDD
Dt@zD fH0,0,1L@x, y, zD + Dt@yD fH0,1,0L@x, y, zD + Dt@xD fH1,0,0L@x, y, zD
Note the notation: Dt[z] means dz and fH0,0,1L@x, y, zD signifies ∑ f H.L∑z
.
Some Cobb-Douglas algebraAt first, we define Y to denote output according to a standard Cobb-Douglas production function
Clear@Y, A, L, K, αD; Y = A Lα K1−α;
The competitive wage and rental price of capital then is
8w = D@Y, LD, r = D@Y, KD<
9A K1−α L−1+α α, A K−α Lα H1 − αL=
The production elasticity of labor and capital are defined as hYL := dYêYdLêL = dYêdL
Y êL and hYK := dYêYdKêK = dYêdK
Y êK
:D@Y, LD
Y ê L,
D@Y, KDY ê K
>
8α, 1 − α<
Euler's theorem
6 QDM_Intro_complete.nb
w L + r K êê Simplify
A K1−α Lα
A CES example
Clear@Y, w, rD; Y = Ia Lα + H1 − aL KαM1êα;
8w = D@Y, LD, r = D@Y, KD<
:a L−1+α HH1 − aL Kα + a LαL−1+1α , H1 − aL K−1+α HH1 − aL Kα + a LαL−1+
1α >
w L + r K Y êê Simplify
True
Euler's theorem holds, of course, also true in the general CES case.
4. Lists, functions, and some functional programming
ListsA list is a collection of objects. In Mathematica, a list is the fundamental data structure used to group objects together.As a first and simple example consider
a = 82, 4, 6, 8, 10<; b = 881, 2<, 80, 4<<;
An extensive set of built-in functions is available to form and manipulate lists. For instance, to access single elements of a list we can use "Part" command
Part@a, 1D
2
A short-cut is as follows
QDM_Intro_complete.nb 7
8a@@1DD, b@@1DD, b@@1, 1DD<
82, 81, 2<, 1<
To form a list one can employ the "Table" command
Table@x + 2 y, 8x, 5<D
81 + 2 y, 2 + 2 y, 3 + 2 y, 4 + 2 y, 5 + 2 y<
Table@f@xD, 8x, 5<D
8f@1D, f@2D, f@3D, f@4D, f@5D<
Here we first produce a list of random numbers
iLength = 100; listRandom = Table@Random@D, 8i, 1, iLength<D;
use the command "ListPlot" to visualize the result of this random sampling
ListPlot@listRandom, PlotJoined → TrueD
20 40 60 80 100
0.2
0.4
0.6
0.8
1.0
and then calculate the mean and the standard deviation of this sample
8 QDM_Intro_complete.nb
sampleMean =1
iLength ‚
i=1
iLength
listRandom@@iDD
sampleDeviation =1
iLength − 1 ‚
i=1
iLength
HlistRandom@@iDD − sampleMeanL2
1ê2
0.501975
0.313544
The same can be done using the built-in functions "Mean" and "StandardDeviation"
8Mean@listRandomD, StandardDeviation@listRandomD<
80.501975, 0.313544<
FunctionsMathematica contains a number of built-in-functions. In addition, one can easily define new functions. The generalform of a function definition is f[x_] := body. Note that the function argument x is followed by an underscore.The combination x_ is called a pattern. Also note the "special" definition symbol :=.
Built-in functions. Here is a plot of f HxL = ex together with its first-order Taylor series approximation about x = 0
series1 = Series@Exp@xD, 8x, 0, 1<Dseries2 = Normal@series1D
1 + x + O@xD2
1 + x
QDM_Intro_complete.nb 9
Plot@8Exp@xD, series2<, 8x, −1.5, 1.5<, AxesLabel → 8x, ex<,PlotStyle → 88<, [email protected]<D<D
−1.5 −1.0 −0.5 0.5 1.0 1.5x
1
2
3
4
ex
Notice that, in dynamic macroeconomics, we frequently use the approximation ex > 1 + x, implying x > lnH1 + xL, for "small values" of x.
Newly-defined functions 1. Here we define a Gaussian function with unity variance and zero mean
f@x_D :=1
2 π ExpB−
x2
2F
To visualize, let us plot this function
10 QDM_Intro_complete.nb
Plot@f@xD, 8x, −6, 6<, PlotStyle → [email protected],AxesLabel → 8x, "fHxL"<D
−6 −4 −2 2 4 6x
0.1
0.2
0.3
0.4
fHxL
Our new function may now be used like any other Mathematica function.
∂x f@xD
−
−x2
2 x
2 π
‡−∞
∞
f@xD x
1
The "probability mass" between x∈[-1.96,1.96] is
‡−1.96
1.96f@xD x êê N
0.950004
Newly-defined functions 2. Here we define a function that calculates the mean of a list of numbers.
QDM_Intro_complete.nb 11
mean@x_D :=1
Length@xD ‚
i=1
Length@xDx@@iDD
Here we test the function
mean@Table@Random@D, 8100 000<DD
0.499891
Some functional programming (available upon request)
5. Differential and difference equations
Differential equationsHere is a simple linear, autonomous differential equation (DE). Since it is linear, it can be solved analytically yieldinga closed-form solution.
Clear@a, bD; dex = x'@tD a + b x@tD;
sol = DSolve@dex, x'@tD, tD
::x@tD → −a
b+ b t C@1D>>
Observe that Mathematica names the arbitrary constant of integration C[1].
We visualize the result by using an example. First, we extract the solution from the above output expression
toplot1 = sol@@1, 1, 2DD;
Here we replace the constant of integration (C[1]) by the numerical value "10"
toplot = toplot1 ê. C@1D → 10
−a
b+ 10 b t
Specifying parameters a and b numerically, we can use Plot command to plot the result
12 QDM_Intro_complete.nb
Clear@a, bD; a = 2; b = 0.2;Plot@toplot, 8t, 0, 30<, AxesLabel → 8t, x@tD<,
PlotStyle → [email protected]<D
5 10 15 20 25 30t
1000
2000
3000
4000
xHtL
Reference information: Abell and Braselton (2004) is an extremely helpful book on differential equations with Mathematica.
Difference equationsHere is a simple difference equation, which can be solved analytically by using "RSolve"
Clear@a, bD; sol = RSolve@8x@tD a x@t − 1D + b, x@1D 1<, x@tD, tD
::x@tD →−at + a1+t − a b + at b
H−1 + aL a>>
To plot the solution we first construct a list of x[t], evaluated at integer t-values, using "Table"
QDM_Intro_complete.nb 13
list = Table@sol@@1, 1, 2DD, 8t, 0, 20<D
:−1 + a + b − a b
H−1 + aL a,
−a + a2
H−1 + aL a,−a2 + a3 − a b + a2 b
H−1 + aL a,
−a3 + a4 − a b + a3 b
H−1 + aL a,−a4 + a5 − a b + a4 b
H−1 + aL a,−a5 + a6 − a b + a5 b
H−1 + aL a,
−a6 + a7 − a b + a6 b
H−1 + aL a,−a7 + a8 − a b + a7 b
H−1 + aL a,−a8 + a9 − a b + a8 b
H−1 + aL a,
−a9 + a10 − a b + a9 b
H−1 + aL a,−a10 + a11 − a b + a10 b
H−1 + aL a,−a11 + a12 − a b + a11 b
H−1 + aL a,
−a12 + a13 − a b + a12 b
H−1 + aL a,−a13 + a14 − a b + a13 b
H−1 + aL a,−a14 + a15 − a b + a14 b
H−1 + aL a,
−a15 + a16 − a b + a15 b
H−1 + aL a,−a16 + a17 − a b + a16 b
H−1 + aL a,−a17 + a18 − a b + a17 b
H−1 + aL a,
−a18 + a19 − a b + a18 b
H−1 + aL a,−a19 + a20 − a b + a19 b
H−1 + aL a,−a20 + a21 − a b + a20 b
H−1 + aL a>
Clear@a, bD; a = −0.75; b = 2;ListPlot@list, PlotJoined → True, AxesLabel → 8t, xt<D
5 10 15 20t
1.05
1.10
1.15
1.20
1.25
1.30
xt
14 QDM_Intro_complete.nb
6. Graphics
An isoquant plot of CES functions
Especially for teaching it might be helpful to plot isoquants of a CES technologies, like Y = Ix1s + x2
sM1ês. There are
two basic possibilities to do this.
Possibility 1
QDM_Intro_complete.nb 15
ManipulateA9Plot3DAIx1σ + x2σM1êσ, 8x1, 0.001, 50<, 8x2, 0.001, 50<E,
ContourPlotAIx1σ + x2σM1êσ, 8x1, 0.001, 50<, 8x2, 0.001, 50<,
ContourShading → FalseE=, 8σ, −100, 1<E
s
: ,
>
Possibility 2
16 QDM_Intro_complete.nb
Clear@α, p1, p2D; α = .35;p1 =
PlotAEvaluateATableASolveAIx1α + x2αM1êα Y, x2E@@1, 1, 2DD,
8Y, 50, 200, 10<EE, 8x1, 0.001, 50<, PlotRange → 80, 50<,
AxesLabel → 8x1, x2<E;
Clear@αD; α = 1;p2 =
PlotAEvaluateATableASolveAIx1α + x2αM1êα Y, x2E@@1, 1, 2DD,
8Y, 50, 200, 10<EE, 8x1, 0.001, 50<, PlotRange → 80, 50<,
AxesLabel → 8x1, x2<E;
Show@GraphicsArray@8p1, p2<DD
0 10 20 30 40 50x1
10
20
30
40
50x2
0 10 20 30 40 50x1
10
20
30
40
50x2
Plotting dataHere is a list of data points
dataList = Table@Sin@tD, 8t, 0, 4 π, 0.1<D;
This list can be plotted using ListPlot
QDM_Intro_complete.nb 17
ListPlot@dataList, AxesLabel → 8t, "Sin@tD"<D
20 40 60 80 100 120t
−1.0
−0.5
0.5
1.0
Sin@tD
What about empirical data series? This iscan be done by employing Import[url]. To try this, we put an excel data file at:
http://www.wifa.uni-leipzig.de/fileadmin/user_upload/itvwl-vwl/makro/Lehre/qdm/-GDP_Per_Capita_USA.xls
18 QDM_Intro_complete.nb
list =
Import@"http:êêwww.wifa.uni−leipzig.deêfileadminêuser_uploadêitvwl−vwlê
makroêLehreêqdmêGDP_Per_Capita_USA.xls"D;p1 = ListPlot@list, PlotStyle → [email protected], Black <<,
AxesLabel → 8t, "GDP per capita"<D;Clear@a, b, cD;parameterFit = FindFit@list@@1, 1 ;; 132, 2DD, a + b x + c x^2,8a, b, c<, xD;
trend = Table@a + b x + c x^2 ê. parameterFit , 8x, 132<D;gdpcTrend = Thread@8list@@1, 1 ;; 132, 1DD, trend<D;trendPlot = ListLinePlot@gdpcTrend,
PlotStyle → [email protected], Red<,AxesLabel → 8t, "GDP per capita"<D;
Show@p1, trendPlot, PlotLabel → "GDP per capita HUSAL"D
1900 1920 1940 1960 1980 2000t
5000
10 000
15 000
20 000
25 000
GDP per capitaGDP per capita HUSAL
7. Supplement: notation and basic calculationTaken from Jankowski, 1998, Lecture 3 (http://usm.maine.edu/~mjankowski/docs/ele298/index.htm)
QDM_Intro_complete.nb 19
Notation
à Arithmetic operators
^ stands for exponentiation, as in 2^4, or in StandardForm 24
/ stands for division
* stands for multiplication, however is frequently omitted since space between two operands is understood as a multiplication operation:
2 ∗ 3
2.1 π
. is the matrix multiplication operator (dot product)
à The four kinds of braces
(a+b) c parantheses are for grouping
(round parentheses) are to be used only to indicate order of evaluation: Ha + bL c is the quantity a + b multiplied by c. Note that space indicates multiplication. In other cases space means nothing at all.
f[x], Sin[x] square brackets for functions
(square brackets) are used with functions and commands: Sin@xD is the sine of x. SinHxL does not work.
{a,b,c,5.4,"Hello"} curly braces for lists
v[[i]] double brackets for indexing lists
repeated square brackets are used to refer to a specific part of a list. Given the five element list v = 8a, b, c, 5.4, Hello<, the first element of the list a is v@@1DD.Other common symbols
Here we list a few commonly encountered symbols. These are listed without any particular order and full explanations will be given later.
= is a simple assignment statement, as in a=1
:= is typically associated with function definitions, as in f @x_D := x2
-> is a transformation rule, rules are frequently employed to define options in functions, as in
Plot[Cos[x], {x,0,2π}, PlotRange->{-2,2}]
// is the postfix form of the expression f[x], for example Sin[x] may be written x//Sin
Many Mathematica functions have associated symbolic representations. Some of the most commonly encountered are:
f @@ expr is equivalent to ReplaceAll[f,expr]
20 QDM_Intro_complete.nb
f/@expr is equivalent to Map[f,expr]
stringa <> stringb is equivalent to StringJoin[stringa, stringb]
à Punctuation
As in C and other programming languages the semicolon (;) is a command terminating character. Additionally, it is used to block kernel output to screen. The comma (,) is used as a simple separator. Mathematica allows multiple statements in a cell or even a single line. The characters "(*" and "*)" denote beginning and end of comments.
à Function names
Mathematica is case sensitive.
If you know what you want to do but you don't know the name of the Mathematica function to use, some rules can help you guess. (Of course, you could always look it up in the Help Browser, but who wants to read documentation when you can guess instead?)
è All function names start with capital letters, and multi-word names use internal capitalization (the way German should but doesn't). There is an exception for widely accepted abbreviations of common functions such as Sin, Log, Exp, etc.
è Nothing is ever abbr. (except N and D). Integer is Integer not Int. Integrate is Integrate, not Int.
è Functions named after a person are the person's name plus the commonly used symbol. Examples:
BesselJ
LegendreP
ChebyshevT
Exception:
Zeta (should have been RiemannZ)
è When in doubt, think long. Examples:
FactorInteger
LinearProgramming
MathieuCharacteristicExponent
A Mathematica variable or symbol may consist of any number of contiguous letters and numbers. The name should not start with a number. Some special characters should not be used: underscore character, ampersand, period. Here are a few examples of BAD variable names:
8x_y, x.y, x & y<
à Constants
Built-in constants adhere to this convention: I, E, Pi, Infinity (or in the newer forms: Â, ‰, p, ¶ ). The Traditional-Forms are all obtained via the Escape key.
I I
QDM_Intro_complete.nb 21
N@ED
N@πD
1
∞
0 ∞
Basic symbolic and numeric calculationsWe begin with a discussion of symbolic vs. numeric calculations based on material in Glynn/Gray, Chapters 5 and 23.
à Simple calculations
Even at this early stage, you will encounter some interesting examples since most of you are familiar with numerical calculations only.
1 + π
N@%D
N@%%, 50D
1
3
N@%D
Note the difference between the following two results. You need to be aware of the fact, that when using real numbers or N, all calculations are approximate (within the precision of computers floating-point representation).
SinBπ
3F
SinBπ
3.F
The following example will give another example of the difference between Mathematica's exact and approximate number representations.
22 QDM_Intro_complete.nb
M = ::11
16,
1
2>, :
1
3, −
11
5>>;
M.Inverse@MD
[email protected]@N@MDD
Some more symbolics using complex numbers.
−4
ExpBI π
2F
:ReBExpBI π
3FF, ImBExpB
I π
3FF>
ConjugateBExpBI π
3FF
ExpToTrigBExpBI π
3FF
The value of a variable need not be a number. Here is another example.
y = 2 x + 1
y2 + 2 x
Here is a method of checking your basic math skills. The == symbol is a relational operator, it tests for equality.
Log@10, πD ==Log@πD
Log@10D
Cos@xD2 + Sin@xD2 == 1
The last example shown what happens when Mathematica does NOT understand the input - it simply returns the input unevaluated (see below for the proper way of testing this well known trigonometric identity).
TrigToExpACos@xD2 + Sin@xD2E == 1
Other relational operators are: >, <, >=, <=.
QDM_Intro_complete.nb 23
à Algebra and calculus
Two result in the preceding section did not yield the desired results. Here we will try again.
ExpandAy2E − 4 x
SimplifyACos@xD2 + Sin@xD2E == 1
Expand and Simplify are two examples of a large family of functions useful in manipulating algebraic expressions.
We move on to examples from calculus. Note that you can place comments on Mathematica input lines.
∂x xn H∗ this is a derivative ∗L
∂8x,2< xn
‡ % x H∗ % stands for the last output ∗L
Here is a "favorite" of electrical engineering students. It gives the inverse Fourier transform of the ideal lipase filter of bandwidth 1 rad
sec.
sinc =1
2 π ‡
−1
1Exp@I ω tD ω
Follow with some algebraic manipulation and we get
ExpToTrig@%D
There are however many integrals for which no explicit formula can be given. These can be solved numerically.
‡ Sin@Sin@3 xDD x
Definite integrals have the same general form. However, the second argument is now an iterator. It has the general form {x, xmin, xmax}.
NIntegrate@Sin@Sin@3 xDD, 8x, 0, 1<D
24 QDM_Intro_complete.nb