23
ECM6 Computational Methods : Lecture 2 Brian G. Higgins Department of Chemical Engineering & Materials Science University of California, Davis April 2014, Hanoi, Vietnam

ECM6Lecture2Vietnam_2014

  • Upload
    duyvu

  • View
    216

  • Download
    3

Embed Size (px)

DESCRIPTION

lecture

Citation preview

  • Slide 1 of 7

    ECM6 Computational Methods :

    Lecture 2Brian G. Higgins

    Department of Chemical Engineering & Materials ScienceUniversity of California, Davis

    April 2014, Hanoi, Vietnam

  • Slide 2 of 7Topics for Lecture 2

    In this lecture we give a brief over view of the following topics

    Basic Calculus

    Defining Variables and Functions

    Lists

    Replacement Rules

    Graphics

    Clear Variable Definitions

    In this notebook the following user variables are defined. You should always evaluate the following cell before proceeding, to ensure that there are no clashes with existing variables in your Mathematica session. The following functions removes all definitions of the variables listed.

    Remove@mySeries, a, b, c, c1, c2, myfunc1, myfunc2, myfunc3, myIntegrator1,myIntegrator2, myVolume, myfunc2D, myplots, v, a, w, fruits, randomFruitsD

    2 ECM6Lecture2Vietnam_2014.nb

  • Slide 3 of 7Basic Calculus

    Differentiation

    In Mathematica the built-in function for differentiation is D. In its simplest form D takes on two argu-ments separated by a comma, i.e., D[exp,var]. The first argument is the expression (exp) to be differen-tiated, the second is the variable of differentiation (var). To find more details of this function

    ? D

    Example 1

    Suppose we want to differentiate the function x4(3x+4) with respect to x. The Mathematica statement is

    DAx4 H3 x + 4L, xEIf exp is a multivariable function, we can use D to find the partial derivative with respect to multiple variables by simply listing additional variables to the second argument:D[exp,var1,var2,var3] . Here are some more examples:

    Example 2

    DAx4 y2 + 4 x3 y5 z, x, yEOne can also use the notation xexp to find the partial derivative of exp with respect to x. For multiple derivatives the notation is x,y,zexp. Thus is the previous example we would use

    x,yx4 y2 + 4 x3 y5 z

    Example 3:To take the derivative of the expression (exp) with respect to the variable (var) n times, the format is D[exp,{var,n}]

    DAx4 y2 + 4 x3 y5 z, 8x, 3

  • Dt@f@x, y, zDDDt@zD fH0,0,1L@x, y, zD + Dt@yD fH0,1,0L@x, y, zD + Dt@xD fH1,0,0L@x, y, zDHere is a specific example, assuming y and z depend on x:

    DtAx4 y2 + 4 x3 y5 z, xE4 x3 y2 + 12 x2 y5 z + 2 x4 y Dt@y, xD + 20 x3 y4 z Dt@y, xD + 4 x3 y5 Dt@z, xDNote that in the above output above the notation Dt[y,x] represents dy

    dx

    Integration

    We can also integrate expressions symbolically using the built-in function Integrate, which has two arguments. The first argument is the expression we wish to integrate. The syntax for the second argu-ment depends on the type of integration.

    If we wish to evaluate an indefinite integral, the second argument is the variable of integration, i.e., Integrate[exp,x]. To evaluate a definite integral the second argument is a list of three elements. The first element of the list is the variable of integration, while the second and third elements correspond to the lower and upper limits of integration, respectively, i.e.,

    Integrate[exp,{x,xmin,xmax}]

    We illustrate these built-in functions in the following examples (keep in mind that the variable x has not been assigned a value, thus Mathematica is carrying out symbolic integration!):

    IntegrateAx4 y2 + 4 x3 y5 z, xEIntegrateAx4 y2 + 4 x3 y5 z, 8x, 1, a

  • Power Series

    The function Series@exp, 8x, x0, n

  • Slide 4 of 7Defining Variables and Functions

    Assignments using Set and SetDelayed Functions

    In Mathematica one can assign a value or symbol to a variable with the Set command.The shorthand version for Set is "=" For example, the following two statements set (assign) a=3 and b=3

    a = 3

    Set@b, 3D The assignment using the Set function is done immediately as opposed to a delayed assignment. A delay assignment is made with the SetDelayed function. The shorthand version of SetDelayed is ":=". When SetDelayed function is used the rhs of the expression lhs:=rhs is not evaluated. When lhs is subsequently used in an expression that is evaluated, then lhs is assigned the most recent value of rhs. We can illustrate this with the following examples. Let us assign a new value to the variable b

    b = 4 + a

    Now make the following assignments for the variables c1 and c2. Note that c1 is an immediate asign-ment, while c2 is a delayed assignment If we evaluate these expressions, the immediate assignment gives the value of c1. The expression for the delayed assignment produces no output

    c1 = 1 + b

    c2 := 1 + b

    If we now evaluate c2 we get the desired result

    c2

    Now let us change the value for b

    b = 6 + a

    When we evaluate c1 we get the old value

    c1

    whereas when we evaluate c2, the rhs is refreshed with the current value of b and we get the correct value

    c2

    Another function that sometimes gets confused with the Set function is the Equal function (==). The Equal function is used to define symbolic equations. In mathematics we use = to define symbolic equa-tions as well as variables.

    User Defined Functions: Patterns

    Users can define their own functions using the pattern matching capabilities of Mathematica. A function has the general form

    functionName@var1_, var2_, D := body

    6 ECM6Lecture2Vietnam_2014.nb

  • functionName@var1_, var2_, D := bodywhere the body is a set of Mathematica commands or program that is evaluated when functionName is evaluated. The arguments of the function are var1, var2 etc. The underscore after each arguments is to signify that var1_ is a pattern that matches any expression. In the context of a function var1_ denotes a formal argument or parameter of the function.Let us consider a simple example

    myfunc1@x_D := x3 + cx

    Now when fAy2E is evaluated every occurrence of x on the rhs is replaced with y2.myfunc1Ay2EIf we substitute a numerical value for the argument of f@xD, we obtainmyfunc1@3DIn the above example we defined our function with the SetDelayed operator. This is not necessary. If we used Set then the rhs is evaluated immediately.There are circumstances when using Set is not appropriate. Consider the following example. Suppose we want to define a function that does the following numerical integration

    NIntegrateAx3, 8x, xmin, xmax

  • myfunc2D@x_, y_D := x2 y - 3 x3y2

    + 8 y

    Our function can be differentiated

    x,ymyfunc2D@x, yDand we can use all the calculus tools available in Mathematica. Here is a Taylor series expansion about x = p

    Series@myfunc2D@x, yD, 8x, p, 3 0D := Sin@xDmyfunc2@x_ ; x 0D := ExpB 3

    10xF

    Now lets test out the function with different values for the argument

    myfunc2@3Dmyfunc2@-3DNote that functions with conditions cannot be integrated or differentiated:D@myfunc2@xD, xD, myfunc2@xD x,

    -5

    5myfunc2@xD x>

    However, a numerical integration can be done

    NB-5

    5myfunc2@xD xF

    8 ECM6Lecture2Vietnam_2014.nb

  • Slide 5 of 7Working with Lists

    Remove@v, a, b, cDDefinition of the List Function

    The List function is an ordered array of objects, separated by commas. It is a fundamental data struc-ture in Mathematica and is used frequently to handle, store, and manipulate a collection of objects (these may be numbers, variables, expressions, graphics, sound).

    The format for a list is List@obj1, obj2, obj3, D However, the shorthand version involving the braces 8< is more commonly used: 8obj1, obj2, obj3,

  • vw

    Function Attributes

    Any function that has the attribute "listable" is threaded over lists.We can use the ?? command to check whether a particular function is "listable" Here is the result for the Plus function, which we already seen is listable

    ?? Plus

    Let us examine the attributes of the Sin function:

    ?? Sin

    Since the function Sin has the attribute "listable", it will be threaded of a list:

    Sin@vDFunctions that Generate Lists

    TableThe function Table allows one to create lists by iteration.

    Table takes two arguments. The first is the expression we want to iterate, the second is a list variable and its range that is used to iterate, i.e., Table[expression,{x, xmin, xmax}]. If xmin is not specified, Mathematica takes xmin=1. Furthermore, the function Table assumes a default step size of 1. If you require a different step size, one simply augments the list, i.e., {x, xmin, xmax, xstep}. In the following examples we show how the Table function works:

    Table@Sin@xD, 8x, 1, 4

  • The default step for Range is one and its default minimum value for the list is 1. Thus

    Range@5DMulti-dimensional Lists

    The Table command can take more than one iterator. This allows one to generate nested lists. Con-sider the following

    TableASin@xD + CosAy2E, 8x, 0., 3, 1

  • How can we select a fruit form our list at random? One way is to use the Random function in conjunc-tion with the Part function. We use Random to generate a integer between 1 and 24

    fruitsPRandomInteger@81, Length@fruitsD

  • TakeThe function Take is the opposite of Drop.

    Take@fruits, 10DTake@fruits, 810

  • Manipulating List Braces

    FlattenWhen we apply a function (built-in or user-defined) to a list we need to be concerned with the actually syntax that is passed to the other function. We will illustrate the potental problems with the function Position. We can find the position of an element in our fruits list using the Position function

    Position@fruits, "Lemon"D8811

  • Slide 6 of 7Replacement Rules

    A Brief Overview

    Any part of a Mathematica expression may be replaced by some alternative expression using the ReplaceAll command. The shorthand notation for the ReplaceAll command is "/."

    Replacements are defined using rules which have the general form lhsrhs.

    For example, suppose we want to replace all occurrence of x in the expression LogAIx2 - 3 x y3M Tan@xDE with the value c . The rule then is x-> c . Here is how it is done using the ReplaceAll function

    Example 1:

    ReplaceAllBLogAIx2 - 3 Hx yL3M Tan@xDE, x -> c FIt is more convenient to use the shorthand notation "/."

    LogAIx2 - 3 Hx yL3M Tan@xDE . x -> cExample 2:The replacement operator is also used to evaluate expressions. For example, suppose we have the expression LogBx2 + 3 x

    yF which we want to evaluate at x=0.4, y=1.8 One way to do this is to first

    replace all the occurrence of x and then replace the occurrences of y

    LogBx2 + 3 xyF . x .4 . y 1.8

    Example 3:Consider the following example in which the rule is actually a list of rules8a, b, c, a< . 8b -> a, a -> b b, b -> a b, b -> a 8x, y, If@z > 0.8, 1, zD0.6 are transformed. We can also manipulate our position vector data. In this example, the x3 coordinate is set to 1 if x3>0.8. (compare this method with the earlier method that applies an If statement to the RHS

    16 ECM6Lecture2Vietnam_2014.nb

  • In the above example the elements of the list that have values >0.6 are transformed. We can also manipulate our position vector data. In this example, the x3 coordinate is set to 1 if x3>0.8. (compare this method with the earlier method that applies an If statement to the RHS

    myData . 8x1_, x2_, x3_ ; x3 > 0.8< 8x1, x2, 1 sol1, x -> sol2? Solve

    sol = SolveA6 x2 + 5 x + c 0, xEWe can use the sol to evaluate another expression, say LogAx + 4

    xE

    LogBx + 4xF . sol

    Since the variable c is not defined, Mathematica does not return a numerical result. However, if we assign a value for c using a replacement rule, and then force a numerical evaluation ( all the numbers in the expression are exact) by wrapping the expression with N, we get a numerical result.

    NBLogBx + 4xF . sol . c 2F

    ECM6Lecture2Vietnam_2014.nb 17

  • Slide 7 of 7Introduction to Graphic Functions

    A Brief Overview

    Mathematica has powerful graphics routines for studying a variety of mathematical functions. Here is the name search for all functions involving the word Plot:

    ? *Plot*

    Not all these functions are actual plotting routines. The functions PlotJoined, PlotLabel, PlotRange for example are options for plot routines, as can be determined using the ? function

    ? PlotStyle

    All plot routine commands have a common format: plotname[exp,{range}, options] . The simplest plot-ting routine is Plot, which is used for plotting a function with one independent variable. Here is an example of its use without any options specified

    In[187]:= PlotASinAx2E, 8x, 0, 2 p

  • In[188]:= Options@PlotDOut[188]= :AlignmentPoint Center, AspectRatio 1

    GoldenRatio, Axes True,

    AxesLabel None, AxesOrigin Automatic, AxesStyle 8

  • In[191]:= Plot@myfunc3@zD, 8z, 0, 2 p 0D := Sin@xDmyfunc2@x_ ; x 0D := ExpB 3

    10xF

    Let's plot this function over the range -3px3p

    In[195]:= Plot@myfunc2@xD, 8x, -5 p, 5.` p

  • In[196]:= Plot3D@BesselJ@0, 2 xD Cos@3 yD, 8x, 0, 5
  • We will explore the use of PlotPoints, ColorFunction and ContourShading

    In[198]:= ContourPlot@BesselJ@0, 2 xD Cos@3 yD, 8x, 0, 5

  • GraphicsGrid

    This final example illustrates how you can program Mathematica to display a series of plots as an array, each with a different color.

    In[200]:= myplots =Table@Plot@Cos@2 p i tD, 8t, 0, 1