qdm intro complete

Upload: h

Post on 07-Aug-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/20/2019 QDM Intro Complete

    1/24

     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 a

    systematic introduction see, for instance, Gräbe and Kofler (2007) and Jankowski (1998) and the references cited 

    therein. For a concise summary of notation and basic calculation see the supplement (Section 7 below).

    1. First steps

    Basics 1

    We 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 + yb

    >>

    One can extract the RHS of this solution as follows

    sol@@1, 1, 2DD−a + y

    b

    Basics 2

    Here we define a function f [ x, y]

  • 8/20/2019 QDM Intro Complete

    2/24

    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, 20D16. 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

    <,

     8 b, b, b

    2   QDM_Intro_complete.nb

  • 8/20/2019 QDM Intro Complete

    3/24

    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 8x, exp

  • 8/20/2019 QDM Intro Complete

    4/24

    System of equations

    à Analytical solution

    Consider the following non-linear system a1 x1a1-1  x2

    a2 = a and a2 x1a1   x2

    a2-1 = b. Notice that this system represents the

    first-order conditions of the problem maxI x1, x2M

     9 x1a1 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 "Sol ve"

    sol =  Solve@sys, 8x1, x2>

     Mathematica  gives the solution in a somewhat unusual form. A manual derivation (see supplement below) and 

    numerical 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

    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 =  Solve

    Aα2 x1α1 x2α2−1  b, x2

    E@@1, 1, 2

    DD;

    4   QDM_Intro_complete.nb

  • 8/20/2019 QDM Intro Complete

    5/24

    Clear@α1, α2, a, bD; 8α1, α2, a, b< = 80.3, 0.4, 0.1, 0.3

  • 8/20/2019 QDM Intro Complete

    6/24

    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 f H0, 0, 1L@x, y, zD + Dt @yD f H0, 1, 0L@x, y, zD + Dt @xD f H1, 0, 0L@x, y, zD

     Note the notation: Dt [ z]  means dz and f H0, 0, 1L@x, y, zD signifies ∑ f  H.L∑ z

    .

    Some Cobb-Douglas algebra

    At 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 K 1−α L−1+α α, A K −α Lα H1 − αL=

    The production elasticity of labor and capital are defined as hYL :=dYêY dLê L

    =dYêdL

    Y ê L and hYK  :=

    dYêY dK êK 

    =dYêdK Y êK 

    : D@Y, LDY ê L ,

    D@Y, KDY ê K >

    8α, 1 − α<

    Euler's theorem

    6   QDM_Intro_complete.nb

  • 8/20/2019 QDM Intro Complete

    7/24

    w L + r K êê   Simplify

    A K 1−α 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

     Tr ue

    Euler's theorem holds, of course, also true in the general CES case.

    4. Lists, functions, and some functional programming

    Lists

    A 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

  • 8/20/2019 QDM Intro Complete

    8/24

    8a@@1DD, b@@1DD, b@@1, 1DD<

    82,   81, 2

  • 8/20/2019 QDM Intro Complete

    9/24

    sampleMean =1

    iLength  ‚

    i=1

    iLength

    listRandom @@iDD

    sampleDeviation =

    1

    iLength − 1   ‚i=1iLength

    HlistRandom @@iDD − sampleMeanL2

    1ê2

    0. 501975

    0. 313544

    The same can be done using the built-in functions "Mean" and "Standar dDevi at i on"

    8 Mean@listRandom D, StandardDeviation@listRandom D<

    80. 501975, 0. 313544<

    Functions

     Mathematica  contains a number of built-in-functions. In addition, one can easily define new functions. The general

    form 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  H xL = e x together with its first-order Taylor series approximation about x = 0

    series1 =   Series@Exp@xD, 8x, 0, 1

  • 8/20/2019 QDM Intro Complete

    10/24

    Plot@8Exp@xD, series2

  • 8/20/2019 QDM Intro Complete

    11/24

    Plot@f@xD, 8x, −6, 6

  • 8/20/2019 QDM Intro Complete

    12/24

     mean@x_D  := 1Length@xD   ‚

    i=1

    Length@xDx@@iDD

    Here we test the function

     mean@Table@Random @D, 8100 000>

    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 Pl ot  command to plot the result

    12   QDM_Intro_complete.nb

  • 8/20/2019 QDM Intro Complete

    13/24

    Clear@a, bD; a =  2; b =  0.2;Plot@toplot, 8t, 0, 30

  • 8/20/2019 QDM Intro Complete

    14/24

    list =  Table@sol@@1, 1, 2DD, 8t, 0, 20

    Clear@a, bD; a = −0.75; b =  2;ListPlot@list, PlotJoined  →  True, AxesLabel → 8t, xt

  • 8/20/2019 QDM Intro Complete

    15/24

    6. Graphics

     An isoquant plot of CES functions

    Especially for teaching it might be helpful to plot isoquants of a CES technologies, like Y = I x1s+ x2

    sM1ês. There are

    two basic possibilities to do this.

    Possibility 1

    QDM_Intro_complete.nb 15

  • 8/20/2019 QDM Intro Complete

    16/24

     ManipulateA9Plot3DAIx1σ  + x2σ M1êσ , 8x1, 0.001, 50

  • 8/20/2019 QDM Intro Complete

    17/24

    Clear@α, p1, p2D; α =  .35; p1 =

    PlotAEvaluateATableASolveAIx1α + x2αM1êα  Y, x2E@@1, 1, 2DD,8Y, 50, 200, 10

  • 8/20/2019 QDM Intro Complete

    18/24

    ListPlot@dataList, AxesLabel → 8t,   "Sin@tD"

  • 8/20/2019 QDM Intro Complete

    19/24

    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 

  • 8/20/2019 QDM Intro Complete

    20/24

    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] , Si n[ x] square brackets for functions

    (square brackets) are used with functions and commands: Sin@ xD is the sine of x. SinH xL does not  work.

    {a, b, c, 5. 4, "Hel l o" } 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, Hellois a transformation rule, rules are frequently employed to define options in functions, as in

    Pl ot [ Cos[ x] , {x, 0, 2π},  Pl ot Range- >{- 2, 2}]

    / /  is the postfix form of the expression f [ x ] , for example Si n[x]  may be written x/ / Si n

    Many Mathematica functions have associated symbolic representations. Some of the most commonly encountered

    are:

    f @@ expr  is equivalent to Repl aceAl l [ f , expr]

    20   QDM_Intro_complete.nb

  • 8/20/2019 QDM Intro Complete

    21/24

    f / @expr  is equivalent to Map[ f , expr ]

    st r i nga st r i ngb is equivalent to St r i ngJ oi n[ st r i nga, st r i ngb]  

    à 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 Si n, 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:

    Bessel J

    Legendr eP

    ChebyshevT

    Exception:

    Zet a (should have been Ri emannZ)

    è When in doubt, think long. Examples:

    Fact or I nteger

    Li near Pr ogr ammi ng

    Mat hi euChar act er i st i cExponent

    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. Hereare 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

  • 8/20/2019 QDM Intro Complete

    22/24

     N@ED

     N@π D

    1

    0 ∞

    Basic symbolic and numeric calculations

    We 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

  • 8/20/2019 QDM Intro Complete

    23/24

     M  = :: 1116

    ,1

    2>, : 1

    3, −

    11

    5>>;

     M.Inverse@ M D

     N@ M D.Inverse@ N@ M DDSome more symbolics using complex numbers.

    −4

    ExpB I π 2

    F

    :ReBExpB I π 3

    FF, Im BExpB I π 3

    FF>

    ConjugateBExpB I π 3

    FF

    ExpToTrigBExpB I π 3

    FF

    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@π DLog@10D

    Cos@xD2 + Sin@xD2 ==  1The 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: >, =,

  • 8/20/2019 QDM Intro Complete

    24/24

    à Algebra and calculus

    Two result in the preceding section did not yield the desired results. Here we will try again.

    Expand Ay2E − 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 1rad 

    sec.

    sinc =1

    2 π 

     

    ‡ −11

    Exp@I ω tD ω

    Follow with some algebraic manipulation and we get

    ExpToTrig@%DThere 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 generalform {x, xmin, xmax}.

     NIntegrate@Sin@Sin@3 xDD, 8x, 0, 1