+ All Categories
Home > Documents > Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors...

Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors...

Date post: 11-Mar-2018
Category:
Upload: hatu
View: 218 times
Download: 1 times
Share this document with a friend
28
Mathematica * Tutorial For Math 243 Rakesh Department of Mathematical Sciences University of Delaware October 9, 2013 Contents 1 Basic Functions 3 1.1 Differentiation, Integration, Editing ............................ 3 1.2 Saving, Destroying or Starting a Notebook ........................ 4 1.3 Substitution, Numerical Value ............................... 4 1.4 Getting Help, Interrupting Mathematica ......................... 5 1.5 Plotting Planar Curves Given Explicitly or Implicitly .................. 6 1.6 Factor, Expand, Postfix Application of a Function ................... 8 1.7 Lists, Parts of lists and expressions ............................ 8 1.8 Brackets, Names of built-in objects ............................ 9 1.9 Solving a System of Equations I - Solve, NSolve ..................... 10 1.10 Solving a System of Equations II - FindRoot ...................... 11 1.11 Time Saving Tricks ..................................... 13 1.12 Some Common Errors ................................... 14 1.13 Summary of Section 1 ................................... 15 1.14 Problems .......................................... 15 * Version 9 Please send suggestions and corrections to [email protected] 1
Transcript
Page 1: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

Mathematica∗ Tutorial For Math 243

Rakesh†

Department of Mathematical SciencesUniversity of Delaware

October 9, 2013

Contents

1 Basic Functions 3

1.1 Differentiation, Integration, Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.2 Saving, Destroying or Starting a Notebook . . . . . . . . . . . . . . . . . . . . . . . . 4

1.3 Substitution, Numerical Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.4 Getting Help, Interrupting Mathematica . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.5 Plotting Planar Curves Given Explicitly or Implicitly . . . . . . . . . . . . . . . . . . 6

1.6 Factor, Expand, Postfix Application of a Function . . . . . . . . . . . . . . . . . . . 8

1.7 Lists, Parts of lists and expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

1.8 Brackets, Names of built-in objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

1.9 Solving a System of Equations I - Solve, NSolve . . . . . . . . . . . . . . . . . . . . . 10

1.10 Solving a System of Equations II - FindRoot . . . . . . . . . . . . . . . . . . . . . . 11

1.11 Time Saving Tricks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

1.12 Some Common Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

1.13 Summary of Section 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

1.14 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15∗Version 9†Please send suggestions and corrections to [email protected]

1

Page 2: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

2 Preparing a Mathematica Report 16

3 Advanced Functions 17

3.1 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

3.2 Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

3.3 Conditional Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

3.4 Finite Sequences and Series, Taylor Polynomials . . . . . . . . . . . . . . . . . . . . 21

3.5 Plotting Planar Parametric Curves or Curves in Polar Coordinates . . . . . . . . . . 21

3.6 Summary of Sections 1 and 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

4 Vectors Operations and Multidimensional Integrals 24

4.1 Vector Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

4.2 Operations on Vector Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

4.3 Multidimensional Integrals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

5 Plotting Curves and Surfaces 25

5.1 Plotting Three Dimensional Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

5.2 Plotting Three Dimensional Surfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

5.3 Superimposing Pictures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

5.4 Plotting Regions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

5.5 Summary of Section 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

Acknowledgement: This tutorial is based partly on a Maple tutorial by the author and partlyon the single variable and multi-variable versions of CalcLabs Mathematica by Selwyn Hollis.

2

Page 3: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

1 Basic Functions

1.1 Differentiation, Integration, Editing

Start Mathematica and in the new window choose Create New Notebook. A new window/Notebooktitled Untitled opens with a + and a line. Click this window and we are ready to execute Mathe-matica commands in this notebook.

To differentiate sin(x2) type

D[Sin[x^2], x] hit Shift Return

To compute definite and indefinite integrals use

Integrate[Sin[x], {x,0,Pi}] Shift Return

Integrate[ Log[a*x^2], x] Shift Return

Note that Pi (upper case P) is the symbol used for π in Mathematica. The first command computesthe definite integral over the interval [0, π] and the second command computes the indefinite integral.In the second integral, we could have integrated with respect to a instead of x. Also note thatMathematica uses Log for the Natural Logarithm function and not Ln.

The ←, →, ↑, ↓ keys may be used to navigate in the notebook and the Backspace, Delete keysmay be used to correct typing errors. So if we wish to differentiate x sin(x3) instead of sin(x2), wecan modify our notebook as follows - using the ← ↑ → ↓, keys move the cursor to the line whichcomputes the derivative of sin(x2) and using the Backspace, Delete, and arrow keys modify thatline to read

D[x*Sin[x^3], x] Shift Return

Now move the cursor down until you see a line at end of the notebook. Sometimes it is desirableto execute several commands together. Consider

f = Sqrt[1+x] + 3*Exp[5*x] - (x+7)*Log[1+x] Enter

D[f, {x,3}] (third derivative) Shift Enter

The Enter just starts a new line and does not execute the command; the Shift Enter executes bothcommands. The first line assigns a name f to the complicated expression

√1 + x + 3e5x − (x +

7) ln(1 + x) and the second line computes the third derivative of this expression. Also note the useof the square root function and the exponential function - one can also use E^x for the exponentialfunction. The letter E is reserved for the constant e = Exp[1].

3

Page 4: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

1.2 Saving, Destroying or Starting a Notebook

To save the current notebook (perhaps for future use), from the File menu choose Save and choosea name for the file and a location to save it. To start a new notebook, from the File menu chooseNew Notebook and to destroy a notebook, choose Quit from the file menu.

1.3 Substitution, Numerical Value

Open a new Mathematica notebook if you do not have one open. Suppose we wish to substitute thevalues a = 3 and b = 5 into the expression a3 + b2. This may be accomplished with the command(below -> is generated by using the - and > keys)

a^3 + b^2 /. { a->3, b->5} Shift Enter

Here {a->3, b->5} is called a rule which says a becomes 3 and b becomes 5. The /. means applythe rule given after /. to the result of computing whatever comes before /. .

For example, we compute the third order x derivative of x2 sin(kx3) at x = 1, k = 3, accurateto 7 digits. Try

f = (x^2)*Sin[k*x^3]

fxxx = D[f, {x,3}] compute third order derivative

fxxxval = fxxx /. {x ->1, k->3} evaluate third derivative at x=1, k=3

If one wants the numerical value of the third derivative then one can take advantage of the factthat when Mathematica sees decimal inputs Mathematica returns decimal outputs so instead ofusing {x ->1, k->3} we use {x ->1, k->3.0}, that is

fxxxval = fxxx /. {x ->1, k->3.0} evaluate third derivative at x=1, k=3

Another way is to use the operator N which when applied to any expression gives the numericalvalue of that object. So one could use

N[fxxxval]

or equivalently

fxxxval // N

The last line introduces the command // which applies the function(operator) after // to the resultof executing the expression before //. We will see more examples of this in subsection 1.6.

4

Page 5: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

1.4 Getting Help, Interrupting Mathematica

Mathematica has an excellent help tool. For example, to find a Mathematica function to solvethe system of equations x2 + 3y2 = 36, 2x + y = 3, from the Help menu choose the FunctionNavigator, then Mathematics and Algorithms and then Equation Solving. Try one of the functionsand see which one is appropriate. We will cover solving systems of equations using Mathematicain subsection 1.9.

Another way you could search for the appropriate Mathematica function is to try your luck. Soto find the function to solve a system of equations one could guess that the command is Solve andif we execute

?Solve

Mathematica gives the basic syntax for the command Solve and, if we click the >> at the end ofthe output, Mathematica gives a detailed description of the command. However, as you will see insubsection 1.9, the function Solve is useful only in some situations and other functions are moreappropriate in some situations, so sometimes it is better to use the Help menu and search for allthe possible functions appropriate for whatever you wish to do.

Sometimes a calculation takes much longer than you expected it to take and you may wishto interrupt the calculation. This can be done by choosing Abort Evaluation from the Evaluationmenu; you may need to do this several times before the evaluation stops. For example, to computesin 1 + sin 2 + · · · sin(107) use

Sum[ Sin[n^2], {n,1,10^7} ]

which takes a long time, so one should abort the calculation by choosing Abort Evaluation from theEvaluation menu. If that fails try using the Alt+ or Alt+. keys and if that fails you can alwaysQuit Mathematica and start again.

Now is a good time to do the exercises below. They are quite straightforward and will help youassimilate the ideas we have discussed so far.

Exercise 1.1 Compute the fourth derivative of cos(x + 1) + ln(x− 1) + xex2+1 with respect to x.

Also compute the integral of the original function with respect to x over the interval [2, 4] - do notretype the expression to be integrated.

Exercise 1.2 What is the numerical value of eu+v2

+ u2 sin(uv) when u=−3, v=2?

Exercise 1.3 What is the numerical value of sin 3? All trigonometric angles in Mathematica arein radians (and not degrees) by default. What is the numerical value of sine of 20 degrees ? Hint:convert degrees to radians and then apply the sine function. Answer: 0.3420201433 .

5

Page 6: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

Exercise 1.4 Determine the numerical value of the following expression when p = 3, q = 1 -∫ p

qu2 sin(p u) du − d

dq

(p q3 sin(p q) + (p q + 1) eq

)Answer: −8.73549981 .

1.5 Plotting Planar Curves Given Explicitly or Implicitly

We now describe some of Mathematica’s plotting tools. Planar curves may be given explicitlyas in y = x2 (a parabola), implicitly as in x2 + y2 = 1 (a circle), or in parametric form as inx = t + sin t, y = 1 − cos t, −6 ≤ t ≤ 6 (a cycloid). Curves may also be given in polar form as inthe three leaved rose r = sin(3θ). We draw curves given in explicit or implicit form.

To draw the graph of the explicitly given curve y = x2 + 9 sinx over the interval [−3, 3] use

Plot[ x^2 + 9*Sin[x], {x,-3,3} ]

To draw the graph of two (or more) explicitly given curves y = x − x2 and y = 1 − 2x over theinterval [0,1] in the same window, one could use

Plot[ {x-x^2, 1-2*x}, {x,0,1} ]

but one would not know which curve represents which function. So one usually specifies a color foreach of the functions as in

Plot[ {x-x^2, 1-2*x}, {x,0,1}, PlotStyle -> {Red, Blue} ]

with y = x−x2 colored red and y = 1− 2x colored blue - note Red and Blue start with upper caseletters. Plot has other options such as axes labels

Plot[ {x-x^2, 1-2*x}, {x,0,1}, PlotStyle -> {Red, Blue}, AxesLabel -> {x,y} ]

In the plot, the vertical and horizontal sizes are scaled so that the spaces devoted to the horizontalrange and the vertical range are equal. If you want to see the true shape of the curves, use theoption AspectRatio->Automatic; try

Plot[ {x-x^2, 1-2*x}, {x,0,1}, PlotStyle -> {Red, Blue}, AspectRatio->Automatic ]

To find other options available for Plot use the Help menu.

To determine the point of intersection of the two curves in the plot, click the plot and then holddown the right mouse button and choose Get Coordinates. Now as the cursor moves over the plotthe coordinates of the cursor are displayed.

6

Page 7: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

To draw curves given implicitly (i.e. they are not given in the form y = f(x), but in the formg(x, y) = c) use the ContourPlot function. To draw the ellipse x2 + 4y2 = 4 use

ContourPlot[ x^2 + 4*y^2 == 4, {x,-3,3}, {y,-3,3} ]

Note that equations are entered with two equal signs ==. Also, note that for ContourPlot, boththe x and y ranges have to be given because ContourPlot draws the plot only in the rectangledetermined by the x and y ranges. Compare this with using the Plot command used to plotexplicitly given curves such as y = x2 where only the x range is required.

Examine what happens if you increase or decrease the ranges for x and y - try several changes.For ContourPlot, it is advisable to start with a large range and then decrease the range until thegraph is satisfactory.

To draw more than one implicitly given curve, for example, the ellipse x2 + 4y2 = 4 and thecircle x2 + y2 = 2, with ellipse blue and circle colored green, use

ContourPlot[ {x^2 + 4*y^2 == 4, x^2 + y^2 == 2}, Return

{x,-3,3}, {y,-3,3}, ContourStyle -> {Blue, Green}, Axes -> True ]

Note we must use ContourStyle instead of PlotStyle to assign the color to the curves and we alsoused the option Axes -> True to display the coordinate axes. Again the approximate locations ofthe points of intersection may be read by right clicking the picture and choosing Get Coordinates.

Explicitly given curves such as y = x2 − 5x can be plotted using Plot or ContourPlot butPlot will usually give better pictures. Curves such as x2 + 4y2 = 9 can be plotted only withContourPlot.

To superimpose two plots (obtained from different commands) use the Show function. Forexample, to display the graphs of y = x2, y = 1−x2, and the circle x2 +y2 = 1 in the same picture,use

pic1 = Plot[ {1-x^2, x^2}, {x,-1,1}, PlotStyle -> {Red, Blue} ] ;

pic2 = ContourPlot[ x^2 + y^2 == 1, {x,-1,1}, {y,-1,1}, ContourStyle -> {Green} ] ;

Show[ pic1, pic2, PlotRange->All ]

The first and second lines define two plots named pic1 and pic2 and the third line shows the twopictures superimposed.

Note the use of the semicolons ; - Mathematica does not display the output of commands whichend in semicolons. We did not want want the individual plots pic1 and pic2 so we hid those plotsby using the semicolon. See what happens if you remove the semicolon.

Also note the use of the option PlotRange->All. When Show is used, it may happen that onlya part of the second plot is used because the window in which the plot is displayed is determined

7

Page 8: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

by the first picture. To guarantee that all parts of all the pictures are displayed we used thePlotRange->All option. See what happens if you remove that part of the Show command.

When the plot generated by ContourPlot looks jagged use the PlotPoints option.

Exercise 1.5 In the same picture show the curves y = 2x and x3 + y3 = 3xy with the first curvecolored red and the second one blue and label the axes ’x’ and ’y’. Graphically determine the pointof intersection of these two curves with as much accuracy as you can.

1.6 Factor, Expand, Postfix Application of a Function

The functions Factor, Expand, Simplify have the usual meaning - also try Collect. One canuse

Factor[ x^4 + 5*x^3 - 5*x^2 + 5*x -6 ]

Expand[ (x^2+2)*(x^3-4)*(x+2) ]

Simplify[ (x-1)*(x^3+1) + (x+2)*(x^2+4) ]

but usually one thinks of Factoring, Expanding or Simplifying a function only after we have seenthe expression so the postfix form is more convenient (and less cumbersome without the squarebrackets).

x^4 + 5*x^3 - 5*x^2 + 5*x -6 // Factor

(x^2+2)*(x^3-4)*(x+2) // Expand

(x-1)*(x^3+1) + (x+2)*(x^2+4) // Simplify

1.7 Lists, Parts of lists and expressions

Ordered lists show up in many situations in Mathematica. We have already seen lists of equationsas in {x+y==2, x-y==1}, or an ordered list of colors as in {Red, Blue, Green}, or even whengiving the range of a variable in a plot as in the ordered list {x,-2,2}. Note that lists are enclosedin curly brackets { }. For example, consider the list below some of whose elements are themselveslists.

mylist = { 3, 6, {x, x^2}, {7,8,9}, 2,7 }

Here are some operations on a list.

mylist^2 + 1/mylist

Length[mylist] number of elements in mylist

mylist[[2]] second element in mylist

8

Page 9: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

mylist[[3]] third element in mylist

mylist[[{1,2,4}]] first, second and fourth elements in mylist

mylist[[2;;4]] second to fourth elements in mylist

These commands are also useful in getting parts of expressions - try the following and think aboutthe Mathematica output.

f = x^3 + 3*x^2 - 7*x + 10

Length[f] f may be thought of as a list; how many terms in this list

f[[1]] first term of f

f[[3]] third term of f

f[[2;;4]] second to fourth terms of f

g = Sin[x]*Cos[x]*(1+x^2)/(2-x^3)

Length[g]

g[[4]]

g[[2;;4]]

Exercise 1.6 Consider the expression

(ax2 + bx sin y + c sin y)2 + (a sin2 y + bx)3

(a) Write the above as a polynomial in x and extract the coefficient of x2.Ans : b2(3a+ 1) sin2 y + 2ac sin y.

(b) Write the above as a multinomial in the variables x and sin y and extract the coefficient ofx sin2 y. Ans : 2bc.

1.8 Brackets, Names of built-in objects

Mathematica has very specific roles for the different types of “brackets”. The square brackets [ ]

are reserved exclusively to enclose the variables of a Mathematica function as seen above in thecase of D, Integrate, Sin or Log. The round brackets ( ) are used only for grouping expressions asseen in (x+7)*Log[1+x], and the curly brackets { } are used only to enclose ordered or unorderedlists, as in Integrate[ Sin[x], {x,0,Pi} ] where, in the ordered list {x,0,Pi}, the first entryis the variable of integration, the second entry is the lower limit and third entry is the upper limit.

All Mathematica built-in objects such as function names D, Integerate, Sin or constants suchas E or Pi begin with an upper case letter. If a Mathematica built-in object is made of two wordsthen the two words will begin with upper case letters as in FindRoot. So when introducing yourown objects it is highly recommended that you use names which begin with lower case letters.

9

Page 10: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

1.9 Solving a System of Equations I - Solve, NSolve

To obtain solutions of one equation in one variable or to find the solutions of a system of equations,the Solve command is useful. To find all solutions of the quadratic equation x2 − 3x+ 2 = 0, use

Solve[ x^2 - 3*x + 2 == 0, x ]

Note the double equal. The solutions are x = 1 and x = 2 but the Mathematica output is given asa list of rules { {x -> 1}, {x -> 2} } because this will make it easy to use the solutions in otherMathematica calculations.

To solve the system of equations x+ y = 1, x2 − y = 1, for the variables x, y, use

Solve[ {x + y ==1, x^2 - y == 1}, {x,y} ]

and we obtain the two sets of solutions.

To find all solutions of 3x− 2y = 5, x2 − y3 = 2 we use

Solve[ {3*x - 2*y == 5, x^2 - y^3 == 2}, {x,y} ]

and to obtain the decimal values of the solutions one uses NSolve

mysol = NSolve[ {3*x - 2*y == 5, x^2 - y^3 == 2}, {x,y} ]

We also named the list of solutions as mysol because we will use it below. We can extract thedifferent solutions in mysol, for example

mysol[[1]] first part of mysol

mysol[[3]] third part of mysol

Often, we will need to substitute the solution of a system of equations into an expression. Supposewe need to substitute the third solution x = 2.908, y = 1.862 into the expression x2 + y3 + sin(xy).We would do this using /. as seen earlier and one inefficient way of doing it is

x^2 + y^3 + Sin[x*y] /. {x->2.908, y->1.862}

This is inefficient because we retyped {x->2.908, y->1.862} which was already available as Math-ematica output. A better way would be to use the output

x^2 + y^3 + Sin[x*y] /. mysol[[3]]

10

Page 11: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

and this has the advantage of working even if the original system of equations is modified whereas the inefficient way would would have to be modified manually to enter the new solutions -think about this a little. One should never retype or Copy and Paste the results of a Mathematicacalculation. Instead, a name should be given to the output and the name should be used.

Please try the exercise below before moving to the next section.

Exercise 1.7 Find the numerical value of sin(x2 + x) where x is the positive root of the equationx3 + 3x2 = 2. Answer : 0.9544912329.

Exercise 1.8 Evaluate x3 + exy at the solution of y = x + 1, x2 + y2 = 4 which lies in the firstquadrant. Ans: 5.038878215 .

1.10 Solving a System of Equations II - FindRoot

The functions Solve and Nsolve are suitable mostly for solving systems of polynomial equations.If the equations involve non-polynomials then Solve and Nsolve may not find all or even onesolution of the system of equations. One then has to appeal to numerical methods which constructsolutions of the system of equations one solution at a time. The function used to solve systems ofnon-polynomial equations is FindRoot and it will give one solution per execution.

To find all solutions of the equation 7 cosx+ x+ x2 = 15 try

Solve[ 7*Cos[x] + x + x^2 == 15, x ]

NSolve[ 7*Cos[x] + x + x^2 == 15, x ]

and neither of these two work. We now use FindRoot to find approximations of the solutions to7 cosx + x + x2 = 15. Unfortunately FindRoot is an iterative method and needs a starting guessfor the solution. One can just choose an arbitrary starting guess and try our luck - let us say wechoose our starting guess for the solution to be x = 5.0. So we try

FindRoot[ 7*Cos[x] + x + x^2 == 15, {x, 5.0} ]

and we get one solution x = 3.9701 (actually it is a very good approximation of the solution).

How do we find other solutions of this equation if there are any? One could try other startingguesses and hope for the best. However, for the given equation one can do better. The solutions of7 cosx+ x+ x2 = 15 are the solutions of 7 cosx+ x+ x2 − 15 = 0, that is points where the graphof y = 7 cosx + x + x2 − 15 cuts the x axis, so we can get good starting points by examining theplot of y = 7 cosx+ x+ x2 − 15. We plot the graph over the interval [−10, 10] and we can adjustthis interval later.

Plot[ 7*Cos[x] + x + x^2 -15, {x, -10,10} ]

11

Page 12: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

We see that there are only two solutions (in [−10, 10]) - one near x = 5 and one near x = −5. Wecan plot the graph over larger intervals (and argue theoretically - a little difficult) to see that thereare no other solutions.

We have already found the solution near x = 5, we now find the solution near x = −5.

FindRoot[ 7*Cos[x] + x + x^2 == 15, {x, -5.0} ]

Exercise 1.9 Find all the solutions of x2 + 2x + x sinx = 4. Check your answer by substitutingthese values of x into the equation.

Now consider the system of equations x2 + y2 = 4 and sin(x + y) + cosx = 1; these are notpolynomial equations so Solve and NSolve will fail - try it.

Solve[ {x^2 + y^2 == 4, Sin[x+y] + Cos[x] == 1}, {x,y} ]

NSolve[ {x^2 + y^2 == 4, Sin[x+y] + Cos[x] == 1}, {x,y} ]

So we try FindRoot and as before we need a starting guess for the solution. We can choose anarbitrary starting guess for x and y but we can do much better by plotting. The solutions of thesystem of equations are the points of intersection of the curves x2+y2 = 4 and sin(x+y)+cosx = 1.Plotting these curves over the rectangle −3 ≤ x ≤ 3, −3 ≤ y ≤ 3

ContourPlot[ {x^2 + y^2 == 4, Sin[x+y] + Cos[x] == 1}, {x,-3,3}, {y,-3,3},

ContourStyle -> {Red, Blue} ]

we observe that there are two points of intersection. Right clicking the plot and choosing GetCoordinates we see that the points of intersection are near (0.87, 1.74) and (−1.20, 1.53). So we canget these solutions with more precision by using

FindRoot[ {x^2 + y^2 == 4, Sin[x+y] + Cos[x] == 1}, {x,0.87}, {y,1.74} ]

FindRoot[ {x^2 + y^2 == 4, Sin[x+y] + Cos[x] == 1}, {x, -1.20}, {y,1.53} ]

Of course, the question remains whether there are solutions outside the rectangle −3 ≤ x ≤ 3,−3 ≤ y ≤ 3. One can plot the curves over larger rectangles but some thought will show that thereare no solutions outside this rectangle because the curve x2 + y2 = 4 lies inside this rectangle.

Of course this plotting method fails when we have three equations in three unknowns - in thatcase one tries to make educated guesses for the starting point. Try finding solutions of the systemof equations x2 + y2 + z2 = 4, x+ y + z = 0, x sin(yz) = −1.

Exercise 1.10 Find all solutions of x2 + y2 = 9, x3 + y3 − sin(xy) = 7. Why are you sure thatthere are no more? Answer: There are two solutions.

12

Page 13: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

1.11 Time Saving Tricks

• Use space between characters judiciously, not too much and not too little, to make errordetection easier. The following three lines do exactly the same thing - finding the solution ofa system of equation - but the first is preferable.

FindRoot[ {x^2 + y^2 == 4, Sin[x+y] + Cos[x] == 1}, {x,0.87}, {y,1.74} ] Good

FindRoot[{x^2+y^2==4,Sin[x+y]+Cos[x]==1},{x,0.87},{y,1.74}] terrible

FindRoot[{x^2 + y^2 == 4, Sin[x+y] +Cos[x] ==1}, {x,0.87},{y,1.74} ] can be improved

In the first line, note how the command, the equations and the initial guess are judiciouslyspaced so that the different units stand out.

• If the output of a certain calculation is to be used later, it is best to give the output ameaningful name and use the name. Never retype the output and never copy andpaste the output.

• For incorrect commands, Mathematica will highlight where errors may have occurred in thecommand. Check the highlighted characters for errors. The following attempts to find thesolution of a system of equations.

FindRoot[ {x^2 + y^2 == 4, Sin(x+y] + Cos[x] == 1}, {x,0.87}, {y,1.74} ]

Now locate the error and correct it.

• It is OK to Copy and Paste a command but a bad idea to Copy and Paste the output of acommand.

• In Mathematica, several commands may be executed together. This is particularly convenientif the desired output is the result of several commands and one is not interested in theintermediate results. For example, we will compute the numerical value of

d

dx

(x3 sin(kx)

)+

∫ 3

1t cos(t+ k) dt

when x = 2, k = 4.

a = D[ Sin[k*x]*x^3 , x ] Return (not Shift Return)

b = Integrate[ t*Cos[t+k], {t,1,3} ] Return

a+b /. {x->2, k->4} Shift Return

All the commands are executed together and the last result is the desired answer. The problemwas broken into several parts then combined to get the final result.

In the previous problem, we were not really interested in the intermediate values a, b. Onecan suppress the output of a command by placing a semicolon at the end of the command,so try

a = D[ Sin[k*x]*x^3 , x ] ; Return (not Shift Return)

b = Integrate[ t*Cos[t+k], {t,1,3} ] ; Return

a+b /. {x->2, k->4} Shift Return

13

Page 14: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

1.12 Some Common Errors

Here are some common errors when using Mathematica.

• Mathematica built-in objects start with upper case letters. So, for example, don’t useintegrate instead of Integrate, don’t use sin[x] instead of Sin[x] and don’t use red

instead of Red.

• Another common error is to use round brackets or no brackets where square brackets are tobe used. For example Sin(x) and Sin x are incorrect where as Sin[x] is correct.

• Do not use a single = for equations; you must use ==. So do not use x^2 + y^2=1 instead usex^2 + y^2 ==1.

• Do not type xy when you really want x ∗ y.

• The function Solve is useful only in finding solutions of systems of polynomial equations. Itis useless/incorrect to attempt to use Solve for simplifying expressions (use Simplify) or useit in other ways in which we use the verb solve in mathematics such as solving a particulartype of problem.

• A common error is to use a symbol as a variable even though the symbol was assigned a valueearlier. For example, suppose at some stage you used x = 4; and you forgot about it. Somecommands later you differentiate sinx expecting cosx but instead you get an error messagebecause x has the value 4. Try

x = 4

D[Sin[x], x] Error

Clear[x] Clear the value assigned to x

D[Sin[x], x] now it works as you want it to

• Since the commands in a Mathematica notebook are often modified and then rerun, it is agood idea to start every notebook with the Quit[] command which clears the values assignedto all the variables. Execute the following commands -

D[Sin[x], x]

D[Cos[y], y]

x = 4

Now reexecute each of the commands and a problem arises with the first command. That isso because Mathematica remembered that x = 4 from the third command so in the rerun thefirst command does not make sense. So try the following - move the cursor above the firstline and then type Quit[] and hit Shift Enter and then reexecute the commands and thereshould be no problem.

14

Page 15: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

1.13 Summary of Section 1

D, Integrate differentiate, integratePlot plot curves of the form y = f(x)ContourPlot plot curves of the form g(x, y) = cShow superimpose two or more picturesSolve, NSolve, FindRoot solve systems of equations/. apply a rule such as {a ->3} to the expression before /.

// apply the function given after // to the expression before //

N applied to an expression gives its numerical valueLength length of a list or number of terms in an expression,

also see how to get parts of listsFactor, Expand, Simplify obviousSqrt, Log, Sin, Exp obvious[ ], { }, ( ) specific roles of the three types of brackets

1.14 Problems

1. Graphically determine the number of solutions of the equation

x2 − x sin(3x)− x ln(x+ 2) = 1

in the interval [0,3] and the approximate values of these solutions. Then find the solutionclosest to x = 2 accurate to 6 digits. Ans : x = 1.3, 2.2, 2.8; x = 2.199377 .

2. Find the numerical value of the following sum

1

2+

1

3+

1

4+ · · ·+ 1

100.

Ans: 4.1873775.

3. Find all solutions of the system of equations

x2 + y2 = y

2x+ 2y2 + 2 cos(xy) = 3

which lie in the region −1 ≤ x ≤ 1, −2 ≤ y ≤ 2. Ans: (x = −0.2895, y = 0.9076) and(x = 0.43877, y = 0.26026).

4. Find the largest and the smallest value of the function x2 − x sin(3x) − x ln(x + 2) over theinterval [0, 3]; at which points are these values attained. Ans: max = 2.93533 at x = 3;min = −0.81567 at x = 0.6639.

5. Let f = A cosx+B sinx+ Px2 +Qx+R. Find the value of A,B, P,Q,R so that

d2f

dx2+ 3

df

dx+ 2f = 5 sinx+ 2x2 + 1

Ans : a = −3/2, b = 1/2, p = 1, q = −3, r = 4.

15

Page 16: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

6. Find all solutions of the system of equations

x2 + y2 + z2 = 9

x+ y + z = 2

x+ 2y + 3z = 5

Then compute the value of exp(xy + z) + z2 at the solution where z is the largest. Ans: twosolutions, largest z solution is (x = 1.25958, y = −1.51914, z = 2.25958), value is 6.5192.

2 Preparing a Mathematica Report

A report on the solution of a mathematical problem consists of text/comments which guides thereader and mathematical calculations and plots needed to obtain the solution. Mathematica note-books provide an excellent tool for preparing reports.

A Mathematica notebook has various types of cells. You have seen input cells where you entercommands, output cells which contain the output of a command, graphics cells. Below we use textcells for comments/description, title cells, section cells etc. We will prepare a report which presentsthe solution of the problem

Find all solutions of the equation x sinx = 5 in the interval [0, 10].

• Open a new notebook.

• We first provide a heading for our report. Click the first line of the notebook and you will seea + symbol followed by a line. From the Format menu choose, choose Style and then Title.Now type

First Report For Math 242/243/302

Your name

The date

and you can center it if you wish by choosing the appropriate item from the Format menu.

• We now state the problem. Click just below the last line and you will see a + with a line.From the Format menu choose Style amd then Section . Then type

Finding all solutions of x sin(x)=5 in [0,10]

We are now ready to solve the problem.

• Click just below the last line and from Format choose Style and Text, then type

We start by finding the approximate location of the solutions by

plotting the graph of y= x sin(x)-5 on [0,10]

16

Page 17: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

and then click below, enter the following Mathematica commands

Quit[] Shift Enter

Plot[x*Sin[x]-5, {x,0,10}] Shift Enter

The places where the plot crosses the x-axis give the approximate locations of the solutionsof x sinx = 5 in the interval [0, 10]. We see that there are two solutions, one near x = 7 andthe other near x = 9. We find these two solutions.

• Right click below the line and execute the following -

sol1 = FindRoot[x*Sin[x]==5, {x,7}] Enter

sol2 = FindRoot[x*Sin[x]==5, {x,9}] Shift Enter

and we obtain the two solutions. We now state our conclusion. Right click below the lastline, and from Format and Style choose Text and then type

The equation x sin(x) = 5 has two solutions in [0,10]. Accurate to

6 digits they are 7.06889 and 8.82222.

and our report is complete.

3 Advanced Functions

3.1 Functions

So far we have used expressions instead of functions. For example, if we want to work with thefunction x3 + sinx then we have chosen to use

p = x^2 + Sin[x] ;

However, the p defined above is an expression and not a function; because to find the value ofx2 + sin(x) at x = 2 we have to use a rule

p /. {x->2.0}

instead of p[2]. Depending on the situation, a better way may be to define a function f

f[x_] = x^2 + Sin[x]

and now try

f[2.0]

17

Page 18: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

Here is another example of a function and its uses. Please examine the output of each commandand see whether you get what you expected.

g[x_,k_] = x^k + Sin[k*x]

g[y, 3]

g[2, m]

g[2.0,5]

Plot[ g[x,5], {x,0,1} ]

D[g[x,k], x]

Note that, when defining a function, the input variables are declared with an underscore.

Functions can be defined with an = or := called Set or SetDelayed. For example

f[x_] = Sin[x^3] + Cos[x]

g[x_] := Sin[x^3] + Cos[x]

seem to behave the same - try

f[2.0]

g[2.0]

but there is a difference between using = and := which will become apparent in the examples below.When = is used in defining a function then the right hand side is evaluated before the value of x issubstituted where as when := is used then first the x value is substituted and then the right handside is evaluated. Consider the following function which returns the third derivative of sin(x2 + x)at x.

f[x_] = D[ Sin[x^2+x], {x,3} ]

f[5.0]

and everything is fine because x = 5 is substituted into the RHS of the definition of f after theRHS has been computed. However, if you try

g[x_] := D[ Sin[x^2+x], {x,3} ]

g[5.0]

then there is an error, because x = 5 is substituted in the RHS of the definition of g before theRHS is computed and its makes no sense to differentiate with respect to 5. On the other hand inthe next example you do want to delay the computation. Here

g[k_] := Plot[ Sin[kx], {x,0,Pi} ]

g[3] plot the graph of Sin[3x] over [0, 2 Pi]

18

Page 19: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

works, where as

h[k_] = Plot[ Sin[kx], {x,0,Pi} ]

h[3] plot the graph of Sin[3x] over [0, 2 Pi]

does not work because in the definition of h Mathematica attempts to plot sin(kx) for x varying in[0, 2π] without knowing k, where as in the := case the execution of the Plot is delayed until the kis known.

3.2 Animation

Consider the function sin(tx) which depends on x and another variable t (think of it as time). So attime t = 1, the function is sinx, at t = 2 the function is sin(2x), at t = 7.5 the function is sin(7.5x).We can plot the graph of sin(tx) on 0 ≤ x ≤ π for varying t using the Manipulate function.

p[t_] := Plot[ Sin[t*x], {x,0,Pi} ] p[t] gives the plot of y=sin(tx) for 0<x< Pi

p[2] plot of y=sin(2x) for 0<x<Pi

p[6.3] plot of y= sin(6.3x) for 0<x<Pi

Manipulate[ p[t], {t,0,10} ] Animate the plots as t varies over 0<t<10.

When the Manipulate command is executed a box appears with a slider associated to t. Click the+ next to the slider and various controls appear - the animation can be played by pressing the playbutton on the controls. You can slow down the animation, pause it, choose the value of t you wishand manipulate the plots in various other ways - try it.

Manipulate can also be used when discrete values of t are used. For example, one knows(a + b)2 = a2 + 2ab + b2, (a + b)3 = a3 + 3a2b + 3ab2 + b3; to see how the expansion of (a + b)n

changes as n varies from 1 to 25 with n increasing by 3 each time, try

ex[n_] := Expand[ (a+b)^n ]

Manipulate[ ex[n], {n,1,25,3} ]

Actually the increment by 3 is not very informative; change the increment to 1 and see the expansiononly for n between 1 and 10, that is modify the command to be {n,1,10,1}.

Exercise 3.1 Consider the family of curves x3+y3−3txy−x = t as t varies over [−2, 2]. Animatethe plot of this family of curves over the rectangle −4 ≤ x ≤ 4, − 4 ≤ y ≤ 4.

19

Page 20: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

3.3 Conditional Execution

Conditional statements are useful when writing Mathematica functions. For example, to define thefunction

f(x) =

{−2x, x < 0

3x, otherwise,

we would use

f[x_] := If[ x<0, -2*x, 3*x ]

f[3]

f[-5]

f[t]

So If is an if then else statement. To generate compound conditions such as x < 1 or x > 5,or the condition x3 + x > 10 and x < 7, use || for or and && for and. For example, one could have

f[x_] := If[ x<1 || x>5 , -2*x, 3*x ]

f[3]

f[-5]

f[t]

g[x_] := If[ x^3+x > 10 && x <7 , -2*x, 3*x ]

g[3]

g[2]

g[y]

Mathematica also has Which and Piecewise functions which are used when several If statementsare required.

Exercise 3.2 Define the function

f(x) =

{1− x2 x ≤ 1

x− 1 x > 1

and then plot it over the interval [−1, 3].

Exercise 3.3 Define the function

f(x) =

1− x2 x ≤ 1

x− 1 1 < x < 2

3− x x ≥ 2

and then plot it over the interval [−1, 4]. You may need to use the Which function.

20

Page 21: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

3.4 Finite Sequences and Series, Taylor Polynomials

To find the sum of the series69∑n=5

sinn

1 + 3n2

accurate to seven digits, use

NSum[ Sin[n]/(1+3*n^2), {n,5,69} ]

If one had used Sum instead of NSum the exact sum would have been given.

To generate sequences of numbers arising from one ‘formula’ try Table. Observe the result ofexecuting the following statements

Table[ n^2, {n,3,10} ] generate n^2 for n from 3 to 7, n increasing by 1

Table[ n^2, {n,3,30,5} ] generate n^2 for from 3 to 30, n increasing by 5

Table[ Sin[k*x], {k,1,7} ]

To find the Taylor series of an expression f , around x = a up to and including the power(x− a)n, use Series[f, {x,a,n}]. For example

Series[ Log[x], {x,1,7} ]

gives the Taylor expansion of lnx, around x = 1, up to and including (x− 1)7 terms. The outputis a polynomial followed by the expression O[x− 1]8 and this last expression is inconvenient whenwe wish to manipulate the polynomial. To extract just the polynomial part one uses the functionNormal; try

polyseven = Series[ Log[x], {x,1,7} ]

Normal[polyseven]

3.5 Plotting Planar Parametric Curves or Curves in Polar Coordinates

In subsection 1.5 we plotted curves of the form y = f(x) or g(x, y) = 0. We now plot curves inthe plane given either in parametric form or in polar coordinates. To plot the cycloid given in theparametric form

x = t+ sin t, y = 1− cos t, 0 ≤ t ≤ 4π

we use

ParametricPlot[ {t + Sin[t], 1 - Cos[t]}, {t,0,4*Pi} ]

21

Page 22: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

To draw the two (or more) parametric curves but with the same parameter range say the cycloid

x = t+ sin t, y = 1− cos t, 0 ≤ t ≤ 2π

x = 2 cos t, y = 2 sin t, 0 ≤ t ≤ 2π

we use

ParametricPlot[ { {t+Sin[t], 1-Cos[t]}, {2*Cos[t], 2*Sin[t]} },

{t,0,2*Pi}, PlotStyle->{Red, Blue} ]

However, to plot curves with different parametric ranges in the same plot, one must first draw thecurves separately and then use Show to display them together. For example to draw

x = t+ sin t, y = 1− cos t, 0 ≤ t ≤ 2π

x = 2 cos t, y = 2 sin t, 0 ≤ t ≤ π,

note the range for the second curve is different from the that for he first curve, we use

pic1 = ParametricPlot[ {t+Sin[t], 1-Cos[t]}, {t,0,2*Pi}, PlotStyle->Red ];

pic2 = ParametricPlot[ {2*Cos[t], 2*Sin[t]}, {t,0,Pi}, PlotStyle->Blue ];

Show[pic1, pic2]

Note the use of the semicolon ; to avoid displaying the pictures separately when generating pic1

and pic2.

To plot curves given in polar coordinates use the function PolarPlot. For example, to drawthe cardiod r = 1 + cos θ, 0 ≤ θ ≤ 2π, use

PolarPlot[ 1+Cos[t], {t,0,2*Pi} ]

and to draw curves with the same angular range, say r = 1 + cos θ and r = 1 − cos θ both with0 ≤ θ ≤ 2π we use

PolarPlot[ {1+Cos[t], 1-Cos[t]}, {t,0,2*Pi}, PlotStyle->{red,blue} ]

with r = 1+cos t colored red and r = 1−cos t colored blue. To draw two polar curves with differentranges one must plot them separately and then use Show.

We now plot four different types of curves in the same picture. To plot the curves

(a) y = x2, −1 ≤ x ≤ 1,

(b) x2 + y2 = 1,

(c) x = sec t, y = tan t, π/4 ≤ t ≤ π/4,

22

Page 23: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

(d) r = sin(3θ), 0 ≤ θ ≤ 2π.

in the same picture we use

pic1 = Plot[ x^2, {x,-1,1}, PlotStyle -> Red ] ;

pic2 = ContourPlot[ x^2 + y^2 ==1, {x,-1,1}, {y,-1,1}, PlotStyle->Green ] ;

pic3 = ParametricPlot[ {Sec[t], Tan[t]}, {t,-Pi/4,Pi/4}, PlotStyle->Blue ] ;

pic4 = PolarPlot[ Sin[3*t], {t,0,2*Pi}, PlotStyle->Brown ] ;

Show[ pic1, pic2, pic3, pic4 ]

Exercise 3.4 Generate a plot showing the three leaved rose r = sin 3θ and the circle r = 1 -coloring the rose red and the circle blue. Do the same showing only the right hand side of the roseand the full circle. Rewrite the two curves in parametric form x = .., y = .. and plot them usingthe ParametricPlot function instead of the PolarPlot function.

3.6 Summary of Sections 1 and 3

D, Integrate differentiate, integratePlot plot curves of the form y = f(x)ContourPlot plot curves of the form g(x, y) = cShow superimpose two or more picturesSolve, NSolve, FindRoot solve systems of equations/. apply a rule such as {a ->3} to the expression before /.

// apply the function given after // to the expression before //

N applied to an expression gives its numerical valueLength length of a list or number of terms in an expression,

also see how to get parts of listsFactor, Expand, Simplify obviousSqrt, Log, Sin, Exp obvious[ ], { }, ( ) specific roles of the three types of brackets

f[x_] := etc. defining a functionManipulate AnimationIf[cond true, do this, else this] conditional statement, also see Which, Piecewise

||, && Or, AndTable generate a sequenceParametricPlot plot curves given in parametric formPolarPlot plot curves given in polar form

23

Page 24: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

4 Vectors Operations and Multidimensional Integrals

4.1 Vector Operations

The following statements show some of the vector commands in Mathematica.

v = {2,3,7} define v to be the vector 2i + 3j + 7k

w = {-3,4,2} define vector w

v.w dot product of v and w

lenv:= Sqrt[ v.v ] length of v is sqrt of v.v

Cross[v,w] cross product of v and w

u := 3*v- w/2 ; compute 3v-w/2

u[[3]] the 3rd component of u

When working with the motion of a particle we have to differentiate or integrate a vectorexpression. We show some examples below.

r = {Sin[t], t+Cos[t], t*Sin[2*t]} defines a curve

v = D[r,t] the derivative of r which is the velocity of the curve

junk = Integrate[r, {t,0, Pi/2} ] component-wise integration of r for t in [0, Pi/2]

To determine the value of a vector expression (x2 − yz)i + (y2 + z2)j + xyzk when x = 1, y =3, z = −1, we use the /.; try

a = {x^2 -y*z, y^2 + z^2, x*y*z}

a/.{x->1, y-> 3, z -> -1}

4.2 Operations on Vector Fields

In Mathematica, we may compute the gradient of a function and the curl and the divergence of avector field. These functions are available in the Vector Analysis package which has to be loadedinto Mathematica. Try the following commands.

Needs["VectorAnalysis‘"] load the package

SetCoordinates[Cartesian[x,y,z]] coordinates are set to x,y,z

Grad[ x^2 + yz - y^2 ] Gradient of a function

v = {x^2 - 2*y*z, y^3 + x*z, z^2+ x*y} defines the vector field

Curl[v] curl of v

Div[v] divergence of v

In Mathematica, the default Cartesian coordinates are Xx, Yy, Zz, I presume in case the user hasassigned values to x, y, z in their calculations. In most cases you will find it convenient to reset thecoordinates to x, y, z.

24

Page 25: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

4.3 Multidimensional Integrals

To compute the double integral ∫ 2

1

∫ 3x2

2xx+ y dy dx

use

Integrate[ x+y, {x,1,2}, {y, 2*x, 3*x^2} ]

note that the outer limits are listed first and the inner limits second. So to compute∫ 1

0

∫ y2

y3x+ y dx dy

use

Integrate[ x+y, {y,0,1}, {x,y^3, y^2} ]

To compute the triple integral ∫ 2π

0

∫ 2

1

∫ 2r2

r2zr2 dz dr dθ

use

Integrate[ z*r^2, {t, 0, 2*Pi}, {r, 1, 2}, {z, r^2, 2*r^2} ]

5 Plotting Curves and Surfaces

5.1 Plotting Three Dimensional Curves

Curves in three dimensions are given in parametric form

x = f(t), y = g(t), z = h(t), a ≤ t ≤ b

which are plotted using the ParametricPlot3D. As an example, we plot the spiral

x = cos t , y = sin t , z = t, 0 ≤ t ≤ 4π

and the line segment

x = 1− t , y = t , z =5π

2t , 0 ≤ t ≤ 1

in the same picture with the spiral colored red and the line segment colored blue.

25

Page 26: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

spiral = ParametricPlot3D[ {Cos[t], Sin[t], t}, {t,0,4}, PlotStyle->Red];

line = ParametricPlot3D[ {1-t, t, 5*Pi*t/2}, {t,0,1}, PlotStyle->Blue];

Show[ {spiral, line} ]

If the curves need to be thickened then it can be done with the help of the AbsoluteThickness

specification. For example, to thicken the spiral, one could use

spiral = ParametricPlot3D[ {Cos[t], Sin[t], t}, {t,0,4},

PlotStyle->{Red, AbsoluteThickness[3]} ];

line = ParametricPlot3D[ {1-t, t, 5*Pi*t/2}, {t,0,1}, PlotStyle->Blue];

Show[ {spiral, line} ]

The orientation of the plot may be changed by dragging the box surrounding the plot.

5.2 Plotting Three Dimensional Surfaces

Surfaces may be given either in explicit form (z given in terms of x, y) such as

z = x2 + y2,

in implicit form (x, y, z connected by a single equation) such as

x2 + y2 + z2 = 1,

or in parametric form (a formula to generate all the points on the surface) such as the above spherehas the parametric form

x = sinφ cos θ, y = sinφ sin θ, z = cosφ, 0 ≤ θ ≤ 2π, 0 ≤ φ ≤ π.

To plot the explicitly given surface z = x2 + y2 use

Plot3D[ x^2 +y^2, {x,-2,2}, {y,-2,2} ]

It is usually convenient to label the axes with the AxesLabel option; also try some of these otheroptions.

Plot3D[ x^2 +y^2, {x,-2,2}, {y,-2,2}, PlotStyle->FaceForm[Red,Blue], AxesLabel->{x,y,z} ]

Rotate the picture and examine the surface from different viewing angles.

To draw two explicitly given surfaces, such as the paraboloids z = x2 + y2 and z = 6− x2 − y2with the first colored red and the second blue use

26

Page 27: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

Plot3D [ {x^2 + y^2, 6 - x^2 - y^2}, {x,-2,2}, {y,-2,2}, PlotStyle->{Red, Blue},

AxesLabel->{x,y,z} ]

While plotting surfaces some thought must be devoted to choosing the ranges for x and y - sometheoretical analysis and trying various choices usually results in good plots.

Surfaces given implicitly such as the ellipsoid x2/4 + y2/9 + z2/8 = 1 are plotted using theContourPlot3D function.

ContourPlot3D[ (x^2)/4 + (y^2)/9 + (z^2)/8 == 1, {x,-2,2}, {y,-2,2}, {z,-2,2},

AxesLabel ->{x,y,z} ]

Note that we prescribed ranges for x and y as for Plot3D but we also have to prescribe a range forz. The range is important - only the part of the surface inside the range box will be displayed. Soa blank picture will be displayed if the surface is outside the range box. Modify the command sothat the x, y, z ranges are larger -see what happens. What is a good range for x, y and z.

The various options for ContourPlot3D and Plot3D may be found through the Help facility ofMathematica. Explicitly drawn surfaces such as z = x2 + y2 should always be drawn using Plot3D

even though they may also be drawn using ContourPlot3D (using x2 + y2 − z = 0) but Plot3D

gives better pictures.

Surfaces which are in explicit form or implicit form may often be rewritten in parametric formand pictures obtained using the parametric form are usually better. In addition, many surfaces canonly be written in parametric form. Surfaces in parametric form are given as

x = f(u, v), y = g(u, v), z = h(u, v), a ≤ u ≤ b, c ≤ v ≤ d.

For example, the following parametric equation represents a torus -

x = (5 + 2 cosu) cos v, y = (5 + 2 cosu) sin v, z = 2 sin v, 0 ≤ u ≤ 2π, 0 ≤ v ≤ 2π

which may be plotted using ParametricPlot3D .

ParametricPlot3D[ { (5 + 2 * Cos[u])*Cos[v], (5 + 2 * Cos[u])*Sin[v], 2*Sin[u] },

{u,0,2*Pi}, {v,0, 2*Pi}, AxesLabel -> {x,y,z} ]

What happens if you reduce the ranges for u and v? Also, redraw the sketch with the reducedrange and option PlotStyle -> Faceform[Red, Blue] . This allows us to see the inside and theoutside of the shape.

5.3 Superimposing Pictures

Three dimensional pictures may be superimposed using the Show command. To observe the positionof the curve

x = 250t , y =t2

8+ 250t , z = 250t− 16t2

27

Page 28: Mathematica Tutorial For Math 243 - Sites.Udel.Edu Tutorial For Math 243 ... 1.12 Some Common Errors ... Exercise 1.1 Compute the fourth derivative of cos(x+ 1 ...

in relation to the planes z = (x+ y)/10 and z = 0, we use

curve = ParametricPlot3D[ { 250*t, (t^2)/8 + 250*t, 250*t - 16*t^2}, {t,0,16},

PlotStyle->{Red, AbsoluteThickness[3]} ]

planes = Plot3D[ {0, (x+y)/10}, {x,0,4000}, {y,0,4000} ]

Show[ {curve, planes} ]

The first and the second commands defined two objects named curve and planes which contain theplots of the curve and the planes respectively. The last line displays the two pictures - superimposed.If you do not want to see the curve and the plane separately then place a semicolon ; at the endof the first two commands.

5.4 Plotting Regions

When computing triple integrals it is convenient to be able to draw a sketch of the solid region overwhich the integral is to be computed. For example, we may wish to draw the solid region whichis above the x, y plane, below the plane x + y + z = 5 and bounded on the sides by the cylindersy = x2 and y = 2− x2. Some thought will show that we are plotting the solid region given by

{(x, y, z) : z > 0, x+ y + z < 5, y > x2, y < 2− x2}.

This solid may be plotted using the RegionPlot3D function.

RegionPlot3D[ z>0 && x+y+z<5 && y>x^2 && y< 2-x^2 , {x,-1,1}, {y,0,2}, {z,-1,5},

AxesLabel -> {x,y,z} ]

The sketch is not very sharp; the sharpness can be improved by using the option PlotPoints -> 100

; Mathematica will use 100 sample points along each axes. The ranges for x, y and z were chosencarefully - see what happens if you modify the ranges for x, y, z.

5.5 Summary of Section 5

ParametricPlot3d plot parametric curves and surfaces in three dimensionsPlot3D plot surfaces in the explicit form z = f(x, y)ContourPlot3D plot surfaces in the implicit form x2 + y2 = z2 + 8Show to superimpose two or more three dimensional objectsRegionPlot3D to draw three dimensional regions given by inequalities.

Exercise 5.1 Plot a solid which is a vertical circular cylinder with a conical hat on top and ahemisphere as its bottom. Take one unit to be the length of all the radii and heights.

Exercise 5.2 Write the parametric equation of a torus i.e. a doughnut and then plot it usingMaple.

28


Recommended