Introduction to Mathematica 7

Transcription

Introduction to Mathematica 7
A. Bunge / Fall 2009
Introduction to Mathematica 7
Getting Started
You begin by starting Mathematica. Mathematica starts with an open notebook called Untitled1.nb. A notebook in Mathematica is like a document in Microsoft Word, which starts with an
open document called Document1. A notebook file is designated with the extension .nb. In the
following discussion, menu names are designated in bold letters with the first letter capitalized
(e.g., File, Edit, Insert, Cell, etc.), and sub-menu items are designated as italicized text with the
first letter capitalized (e.g., New, Open, Close, etc. in the File menu). Mathematica responses are
also designated as italicized text with the first letter capitalized (e.g., Input, Output, and so on).
You begin your Mathematica session by typing Input into the Mathematica workbook.
Input is placed into a cell. Cells are designated with brackets on the right side of the notebook
window. Normally, a cell consists of a single mathematical Input, the Output resulting from
evaluating an Input, or Text. A single cell may consist of several lines of typing. When the
Enter key is used, Mathematica begins a new line in the same cell. To start a new cell for the
next Input, place the cursor below the current cell and then type your Input. A horizontal line
across the Notebook indicates that the cursor is at the top of a cell. It is sometime easier to move
to a new line using the up and down arrows on the keyboard.
After you have completed typing an Input, you Evaluate the Input (i.e., make
Mathematica execute the mathematical command you entered) by hitting the Shift and Enter
keys at the same time. You can evaluate an entire notebook all at once by choosing Evaluate
Notebook from the Evaluation menu. You can also evaluate one cell or a group of cells by
selecting the brackets at the right side of the window and typing Shift and Enter. Typing Enter
without the Shift key starts a new line in the current cell. If the equations or commands are too
long to fit on a single line, Mathematica automatically wraps to the next lines. You can force a
new line by typing the Enter key alone.
Normally, the default Style is Input. That is, when you begin to type information into a
cell, Mathematica assumes that you are entering Input. Input is used to enter mathematical
equations or Mathematica functions and commands. Mathematica’s response from Evaluating a
cell containing Input will be in Output Style. Once a cell has been evaluated, the Input is
designated with In[number] = and the Output response by Out[number] =. The number indicates
the sequential order of the Evaluations that Mathematica has performed (see discussion under
the heading The Mathematica Kernel below). If you want to add comments, the Style of the cell
must be designated as Text (or various types of titles or sections). Change the Style by selecting
the Style command in the Format menu and choosing one of the styles listed. All further typing
into that cell will be in the selected style. All of the text in a cell can be changed to a different
style by clicking on the cell bracket to the right of the cell (this selects the entire cell), and then
clicking on the Style command in the Format menu. To add text, choose Text. If you want to
add a title, change the format of the cell to Title. You can put comments within an Input line by
using the syntax (* put your comments here *). Note that the parentheses must be included in
the syntax. The screen appearance and size of the font in the notebook is selected in the Screen
Environment setting on the Format menu. Try out the various options (Presentation, Working,
SlideShow, Condensed, Printout) to see how they look. The Working option is often a good
choice.
Mathematica automatically groups cells (as the default setting). For example, the
Output[number] from evaluating an Input[number] is automatically grouped with its
Input[number]. This grouping is designated by right-most bracket, which surrounds the bracket
on the Input cell and the Output cell. If you double-click the right-most bracket for this InputOutput group, then only the contents of the Input cell will show. You can manually group
multiple Input-Output cells together by holding the shift-key and making a left mouse click on
the right bracket of the top and bottom cells; once selected a right-click on the mouse will bring
up a menu that has the option of Group Cells. If you double-click the left mouse button on a
group bracket at the far right of the screen, the group will condense and only the contents of the
first cell will show. Note that the right bracket of a condensed group looks different than for
cells that are not condensed. If you double-click the bracket again, all contents of all cells in the
group will reappear. An alternative way to group selected multiple Input-Output cells together is
to choose Grouping in the Cell menu and the Group Cells/Group Together. Grouped cells can
be ungrouped by selecting with a right mouse click and choosing Ungroup Cells on the menu
that appears. The Ungroup Cells/Group Normally command is also available from Grouping in
the Cell menu. By grouping cells together, you can create a notebook in which users can expand
only the parts they are interested in seeing in detail. For example, you could group all of the
steps in each of the Exercises in this assignment so that you see only the first line of each
exercise; a user can expand an exercise to see the detailed steps.
Exercise 1. Examine the Mathematica logistics just described. After starting Mathematica, type
x = 1 into the notebook. Now press Shift-Enter to force Mathematica to evaluate this input.
Mathematica should respond by adding an In[1] = to your x = 1 Input, followed by Out[1] = 1.
There will be a horizontal line across the page indicating that your cursor has moved to the top of
a new cell. Now type y = 2 and evaluate this. Next type x + y, and evaluate this. You should
2
now see In[3] = x+y and Out[3] = 3 in response. Note that this was the 3rd cell that Mathematica
evaluated. On the right hand side, you will see several brackets. Each cell will be designated by
the left-most bracket. The next bracket to the right will group the Input and Output cells.
Double-click this bracket and see the Output cell disappear. Note that the shape of the bracket
has changed indicating a collapsed group. Double-click the bracket again, and the Output cell
should reappear. Select the Input-Output cells from Input 2 and 3 by selecting their brackets and
then group them by doing a right-click on the mouse and selecting Group. Note that a new
bracket appears to indicate the new grouping. Double-click and see the response and then
double-click again. Ungroup the Input-Output cells from Input 2 and 3 by choosing Ungroup
Cells on the menu that appears with a right-mouse click on the right bracket for the group.
Repeat the grouping and ungrouping steps using the Cell menu and selecting Grouping and then
Group Cell/Group Together or the Ungroup Cells/Group Normally commands. Move the cursor
to the bottom of the cells. A horizontal line will appear below the previous Input-Output cells.
Select Style from the Format menu. Choose Text and then type in a comment. Select the right
bracket for this cell and then choose other styles and see what happens.
Mathematica is a powerful tool that can help you solve many types of math problems.
Once you have developed a method on Mathematica to solve a given problem, it is easy to
modify it for a different situation. So, just like any other computer program (e.g., Fortran, C++,
or Visual-Basic programs), you should add comments and try to make your program easy to
follow. For Mathematica calculations that will be submitted as part of homework or projects,
comments describing the Mathematica computations are essential.
The Mathematica Kernel
It is helpful to understand that the Mathematica program consists of two parts: the user interface
and the Kernel. The user interface simplifies the process of entering mathematical equations and
translates the output into easier to read symbols. The Kernel is the part of Mathematica that
performs computations. When you start a Mathematica session, only the user interface is
running. The Kernel will be launched the first time you ask Mathematica to evaluate an Input
cell. Consequently, on some slower computers, it may take some time for Mathematica to
complete the first evaluation since the Kernel must be started before the evaluation can occur.
After the Kernel is launched, all further cell evaluations will be faster since the Kernel is already
started.
The Kernel remembers each evaluation it has performed and the order in which these
were performed. This ordering is indicated by the sequential numbering that Mathematica
3
assigns to each evaluated Input and the resulting Output. This ordering can be important if you
have used the same variable names to designate different calculations. Occasionally, you may
have performed an evaluation earlier that is interfering with a subsequent evaluation. When this
happens, it is sometimes helpful to use the Quit Kernel command from the Evaluation menu and
to restart the evaluation process. You can then either use the Start Kernel command (also on the
Evaluation menu) or just select a cell to evaluate and then type Shift and Enter (which will
launch the Kernel). When you have Quit Kernel and then started again you will need to evaluate
cells as if they have not been previously evaluated.
Basic Rules of Mathematica Syntax
1. The arguments of functions are given in brackets [...]; parenthesis (...) are used for grouping
operations such as (a + 1)/x; vectors, matrices, and lists are given in curly braces {...}; and
double square brackets [[...]] are used for indexing lists and tables.
2. Mathematica is case sensitive. Thus, cos[x] is not the same as Cos[x]. Be careful!
3. Mathematica has several built-in functions (e.g., Cos[x], Sin[x], Exp[x], etc.). The first
letter of built-in functions is always capitalized, and if a name consists of two or more words,
the first letter of each word is capitalized and there will be no space between the words (e.g.,
LaplaceTransform[x] is the built-in function for determining the Laplace transform of x).
The function cos[x] will not give the cosine of the argument x. You may define your own
functions, which are called user-defined functions. Mathematica will be confused if you
define a function using a name that is the name of a Mathematic function. Since you do not
know the names of all Mathematica functions, the safest way to avoid possible conflicts with
built-in functions is to not capitalize the first letter of user-defined functions.
4. Symbols for common mathematical manipulations like integration ( ∫ ), differentiation (∂),
summation (Σ), fractions (a/b) and exponentiation (xa) are available in the Basic Math
Assistant, which can be opened from the Palette menu. Greek letters and other symbols are
on the Special Characters palette that also available on the Palette menu. To find a palette
that has disappeared although you did not close it, use the Window menu. The top of the
Window menu lists commands for organizing the window. The bottom of the Window
menu lists all notebooks that are currently active. For example, you may see Untitled_1.nb if
you have not saved and named your starting notebook. Above the list of open notebooks is a
list of open palettes and the Messages window. Note that there are other palettes available
that you may find useful. The mathematical and Greek symbols can be selected by clicking
on the chosen symbol in the Basic Math Assistant and then selecting each of the empty boxes
4
and filling them in similar to the procedures used in the equation editor of a word processor.
Mathematica understands the Greek letter π to be Pi (i.e., 3.1415 ...).
5. Mathematical manipulations can also be input through a set of standardized notation.
Multiplication is represented by either a space or *. In Mathematica, a b means a*b, but ab
means you have a new variable with the name ab. Powers are denoted by a ^ or by using the
appropriate symbol template in the Basic Math Assistant. In Mathematica x^2 = x2.
Remember that Mathematica is case sensitive. A variable named Ab is not the same variable
as a variable named ab.
6. Unless designated otherwise Mathematica assumes input is either a variable, a Mathematica
command or function, a user-defined function. To textual input to Mathematica, such as
titles for graphs or axes on graphs are designated using double quotation marks (i.e., "word").
7. If you get no response (e.g., Mathematica seems to be in an infinite loop) or an incorrect
response, you may have entered or executed the command incorrectly. You can stop
execution of a command by selecting Interrupt Evaluation or Absort Evaluation under the
Evaluation menu .
8. If you want the output from an evaluated function to be displayed as a numerical value (e.g.,
in decimal format) rather than as a symbol or fraction, use the command N[argument], where
argument is the mathematical expression. For example, N[Pi] or N[π] will return 3.14159.
N[Pi,25] will return the number Pi to 25 digits. Typing //N at the end of the input line will
achieve the same results (e.g., Pi//N returns 3.14159). Notice that if you evaluate only Pi,
Mathematica returns π. This confirms that Mathematica understands that Pi represents π.
9. If you wish to perform an operation on the last output that Mathematica produced, you can
use the symbol %. For example, N[%] will result in the decimal representation of the last
output. (For example, Input and then Evaluate Pi. Mathematica will respond with π. Now
type N[%]. Mathematical will respond with 3.14159.) You can also refer to specific output
using Out[put output number here], or %output number where output number is the
number Mathematica has assigned to the cell when it was evaluated. For example, to
generate the numerical value of the output designated as Out[17], the command is N[%17]
or N[Out[17]]. Keep in mind that a specific output number will change if you re-evaluate an
input line.
10. To delete a cell, select the right bracket designating the cell and select the Clear command
from the Edit menu. Other useful editing commands can be found in the Edit menu,
including Cut, Copy, Copy as and Paste. Alternatively, after selecting the right bracket of
the cell, push the Delete button on your keyboard. Notice that the Preferences command is
5
located in the Edit menu. You can use the Preferences command to set default preferences
for various Mathematica operations. For example, to change the default values of fonts, you
would choose formatting options/fonts after selecting Preferences. Other useful "editing"
commands are available in the Insert menu (e.g., Copy Input from Above and Copy Output
from Above, Insert Horizontal Lines, and Special Character). Selecting Special Character
from the Insert menu is another way of opening the Special Characters Palette. Various
formatting options are available from the Format menu.
Help
On-line help is available through the Help menu. For help with functions, select the Function
Navigator. Information on mathematical functions is listed under Mathematics and Algorithms,
and then Mathematical Functions. Selecting a function will open a window describing the
function and providing several examples of its use. If you are not sure what category to choose
for your question, click on any category and then option listed in the Function Navigator to open
the help window. At the top of the window is a Search space, where you can type in what you
are looking for. For example, entering Bessel functions into the search box causes several
options to be listed including BesselJ, BesselI and so on.
You can also find help by choosing Documentation Center from the Help menu. This
also opens to a Search option. At the bottom of the Documentation Center window you can
select Index of Functions (which lists in alphabetical order the built-in functions that are
available in Mathematica), and ‘How To’ Topics (which provides instructions on using common
commands like Plot and so on). To find the Screencast tutorials, open the Welcome Screen from
the Help menu and select Learn and Explore. This will connect you to the Wolfram
Mathematica Learning Center on-line, which has the ‘Watch a video screencast’ option listed at
the top. Tutorials and How-To topics also are available from the same webpage. Many of the
topics listed in the ‘How-To’ topics provide links to a video as well as other documentation. The
help options with Mathematica 7 are extensive. You should be able to find the help you need.
You can also get help from Mathematica regarding a command by entering ?Command.
You can enter Options[Command] to find out what options are available with a command and
what the default settings are. This is particularly helpful with plotting commands. To find all
the commands with the string Word in them, enter Names["*Word*"]. You can leave out the
first or second asterisk to find the commands that end or begin with the string Word in them. For
example, to find the names of all commands that start with the word Plot, type Names["Plot*"];
to find names of commands that end with the word Plot, type Names["*Plot"].
Although Mathematica 7 has extensive capabilities that are included in the standard
package, there are specialized capabilities that are available only through Add-On packages.
6
These include specialized statistics calculations such as Analysis of Variance (ANOVA). In
Mathematica 7, including error bars and legends on plots requires an Add-On package. For
more information about what functional ability is not standard but available and how to add and
use these additional capabilities, select Add-Ons & Packages from the Function Navigator
available from the Help menu or search on tutorial/MathematicaPackages from the
Documentation Center on the Help menu.
Built-in Functions
Mathematica has many built-in functions including:
Trigonometric functions: Sin[x], Cos[x], Tan[x], Cot[x], Sec[x], Csc[x]
Inverse trigonometric functions: ArcSin[x], ArcCos[x], ArcTan[x], ArcCot[x],
ArcSec[x], ArcCsc[x]
Hyperbolic functions: Sinh[x], Cosh[x], Tanh[x], Coth[x], Sech[x], Csch[x]
Inverse hyperbolic functions: ArcSinh[x], ArcCosh[x], ArcTanh[x], ArcCoth[x],
ArcSech[x], ArcCsch[x]
Error function: Erf[x]
Complimentary error function: Erfc[x]
Bessel functions: BesselJ[n,x], BesselY[n,x]
Modified Bessel Functions: BesselI[n,x], BesselK[n,x]
Values of the argument giving a zero for Bessel Functions: BesselJZero[n,k],
BesselYZero[n,k]
Gamma function: Gamma[x]
Legendre functions: LegendreP[n,x], LegendreQ[n,x]
Absolute value: Abs[x]
Natural Log: Log[x] (not the base 10 log)
Base 10 Log: Log[x,10]
Exponential: Exp[x]
Limit: Limit[x]
Laplace transform: LaplaceTransform[x]
Inverse Laplace transform: InverseLaplaceTransform[x]
7
Mathematica can also work with complex numbers. In Mathematica I =
−1 = Â.
Exercise 2. Explore the use of mathematical symbols in Mathematica by evaluating each of the
following statements on separate lines:
Pi
Pi//N
Cos[Pi]
Cos[- π]
Sqrt[-1]
I
Exp[a x]
i*i
II
cos(Pi)
This exercise illustrates that Mathematica understands Pi to be the same as the Greek
letter p and equal to 3.14159. If I evaluate Pi, Mathematica returns the symbol p. The symbol p
can be found on the Basic Math Assistant in the Palettes menu under Basic Commands Mathematical Constants. Other Mathematical Constants are also available here, such as Â
(which designates the imaginary one, which is equal to the square-root of negative 1), and ‰
(which designates the exponential function from the letter e). Note that evaluating i multiplied
by i, Mathematica responds with i2, because it does not recognize the lower case letter i as equal
to the square-root of negative 1. However, evaluating I times I gives a Mathematica response of
negative one. Mathematica does not recognize the cosine function if it is not capitalized.
Consequently, the Mathematica response to cos[Pi] is to repeat the input as output.
User-Defined Functions
When naming user-defined functions, it is a good idea to use all lower case letters to avoid
potential conflicts with names of Built-In Functions. Clear[function name] clears all definitions
of a User-Defined function. (Note however, that it does not remove the list of User-Defined
Functions. Since definitions of functions are frequently modified, perhaps several times in a
Mathematica session, it is good practice to perform the Clear command, even when you do not
think it is necessary.
8
The = sign is used to assign a functional description to the chosen function name. There
are two ways to assign a functional description to a function name. If you are defining a function
of x, you can use the commands: f[x_ ]= expression or f[x_ ]:= expression. The underscore
after the independent variable name is mandatory; this identifies for Mathematica the name of
the independent variable in the functional description. f[x_ ]:= expression should be used when
f(x) does not make any sense unless x is a specific variable. The : delays the evaluation of the
function until it is needed. In general, if the command f[x_ ]= expression produces one or more
errors, use f[x_ ]:= expression.
There are several ways to evaluate a function at a particular value of the independent
variable. The first is to type f[value]. The output will be the function evaluated at the value you
chose. The next is to enter f[x] /. x-> value. The f[x] refers to the function, /. means "replace
with", and x-> value instructs the computer to put the value in wherever there is an x in the
function. If you are replacing more than one variable, you need braces around the list (i.e., f[a,b]
/. {a->value1, b->value2, }).
Piecewise functions can be entered into Mathematica by different methods. For example,
if your function was: y(x) = 3x2 for x < 0 and y(x) = 1/2 for x ≥ 0, one way to represent the
function in Mathematica is:
y[x_ ] := 3*x^2 /; x<0
y[x_ ] := 1/2 /; x>=0
The symbol := needs to be used because the function does not make sense unless x is a particular
number. Another approach is to use the UnitStep[x-a] command. You will remember that the
UnitStep[x-a] is zero if x < a and is one if x > a. The example described above can then be
represented by the following equation:
y[x_ ] := 3*x^2 (1 - UnitStep[x]) + (1/2) UnitStep[x]
Exercise 3. Refer to Number 8 on page 5 for tips on easy reference to output. Add a + b.
Multiply your output by c. Add your first output to your second output. Divide your last output
by seven. From the last output, replace a, b, and c with 2, 6, and 7, respectively. Get the
decimal representation of the resulting fraction. (Make sure the numbers following the % signs
and used in the Out command refer to the correct output!)
a+b
%*c
%number of the a+b Output + %number of the %*c Output
%/7
9
% /. {a->2, b->6, c->7}
N[Out[number of the last Output or use %]]
Exercise 4. Clear the function g, enter the function g(x,y) = (x^2 +4 x y -3 y^3)/5, then evaluate
the function two different ways at x=2, y=7. Mathematica will output a fractional result. Force
Mathematica to provide a decimal value by adding //N to the end of the command to evaluate
g(x,y).
Exercise 5. Clear the function g, enter the function g(x) = 3x2 for x < 0 and g(x) = 0 for x ≥
0. Evaluate the function at x = -1 and at x = 1.
Plotting
The basic command to plot functions is Plot[f[x],{x,a,b}] where a,b is the range of values you
want displayed on the x-axis. Mathematica will plot symbolic functions. For this reason,
Mathematica can be used to quickly provide information on the shape of a function. (This is
very useful for quickly viewing whether the equation you derived in your homework or exam
solution is reasonable.)
It is often convenient to name plots (e.g., p1 = Plot[f[x],{x,a,b}] gives this plot the name
p1). Then, later, you can use the Show command (e.g. Show[p1,p2,p3] where plots p2 and p3
have been defined by similar commands) to show several plots on the same axis. Also, this
allows the user to redefine plotting options (e.g., the axis length, titles etc.) without re-typing the
Plot command. Several options that can be used with Plot or Show are listed here for quick
reference. See Mathematica Help for a more comprehensive list of plotting options. Enter Plot
into the search window of the Documentation Center on the Help menu. This opens a window
describing the Plot function, including many details and Options. Notice the square buttons on
the top right hand side of the window – Tutorials, See Also, More About. Clicking on the ‘See
Also’ button, shows several other plotting related functions.
10
AspectRatio->number specifies the height to width of the graph (the default is 0.618,
which is called the GoldenRatio). If number is specified as 1, the height and width will
be equal. If number is 0.5, the graph will be twice as wide as high.
AxesLabel->{"x-axis label","y-axis label"} labels the axes of a plot (the default is no
axes labels). You must have the quotation marks around the label for Mathematica to
recognize the text as the label.
Frame->True draws a box around the plot (the default is false)
FrameLabel->{"bottom (x-axis) label", "left (y-axis) label", "top label", "right
(secondary y-axis) label"} labels the frame of a plot (the default is no frame labels).
The last two can just be left out if they are not needed.
PlotLabel->{"name"} places a name above the plot (the default is no plot title)
PlotRange->{y-minimum,y-maximum} changes the range of the y-axis
PlotStyle->{{Curve 1 Style},{Curve 2 Style},etc.} changes the line styles of curves. An
example is: PlotStyle->{Thickness[0.02], GrayLevel[0.5], Dashing[{0.05,0.05}]} for a
thick, gray, dashed line. This command needs to be used with the Plot command.
RotateLabel->False changes the orientation of the FrameLabel on the ordinate (i.e., the
y-axis) from vertical to horizontal. This has no effect on AxesLabel.
Exercise 6. To see how to use the plot and show commands, enter the following example:
g[x_]=Sin[x*Pi/4]
p1=Plot[Cos[x*π/4],{x,0,4*Pi}, PlotStyle->{Thickness[0.02], GrayLevel[0.5],
Dashing[{0.07,0.02}]}]
p2=Plot[g[x],{x,0,4*Pi},PlotStyle->{Thickness[0.015]}]
Show[p1, p2, Frame->True, FrameLabel->{x,"g(x)"},PlotLabel->"Example 5"]
Note the use of the double quotes to identify a string as text for a label. If you type g(x) without
the double quotes, Mathematica will think that you are saying g multiplied by x; try it and see.
The format of the Dashing command is {line length, spacing length}. Try putting in other
values. Also, try changing the Thickness and GrayLevel.
The command /. (replace with) is useful for plotting. Suppose you want to see the
function y = 4 xb + a for several different values of a and b. The command could look like:
y[x_ ] = 4*x^b+a
11
p4=Plot[{y[x]/.{a->1,b->1},y[x]/.{a->2,b->2}},{x,-2,2}]
This would create a plot showing two curves with a = 1 and b = 1 for one and a = 2 and b = 2 for
the other. To add labels to these two curves requires the Show command. The following
statement will label the two curves generated by the above plotting command:
Show[p4, Graphics[{Text["a=1 & b=1",{x_spot1,y_spot1}]],
Text["a=2 & b=2",{x_spot2,y_spot2}]}].
The text a=1 & b=1will be centered at the location (x_spot1, y_spot1) based on the coordinates
of the graph (and text a=2 & b=2will be centered at the location (x_spot2, y_spot2)).
Exercise 7. This exercise illustrates the use of PlotRange and other useful plotting/graphic
directives. Enter and evaluate the following command.
y[x_]=1-Exp[-b x]
p1=Plot[y[x]/.{b->1},{x,0,10},AxesLabel->{"x","y"}]
Mathematica chooses the y-axis range to be approximately 0.6 to 1. To force Mathematica to
plot y from 0 to 1, add the PlotRange directive to the above statement as follows:
p1=Plot[y[x]/.{b->1},{x,0,10}, AxesLabel->{"x","y"},PlotRange->{0,1}]
Force Mathematica to create a plot that shows curves for b = 1 and b = 2 using the following:
p1=Plot[{y[x]/.{b->1}, y[x]/.{b->2}},{x,0,10}, AxesLabel->{"x","y"},
PlotRange->{0,1}]
Note that the curly brackets surrounding {y[x]/.{b->1}, y[x]/.{b->2}} indicates to Mathematica
that you have entered a list of functions to plot. Now put text labels on the two curves in this
plot by entering the following:
Show[p1,Graphics[{Text["b=2’,{0.6,0.9}],Text["b=1",{3.2,0.90}]}]]
You do not need to include the PlotRange command again since this was specified in p1. The
axis label specified in p1 should also appear. Axes labels generated by the AxesLabel directive
appear at the end of the axes. Make the labels be centered on the axes as follows:
Show[p1,Graphics[{Text["b=2",{0.6,0.9}],Text["b=1",{3.2,0.90}]}],PlotRange->
{0,1}, Frame->True,FrameLabel->{"x","y"}]
Note that {0.6,0.9} specifies the location (given in terms of x and y) of the text b=2. The
location of b=1 is at x = 3.2 and y = 0.9. See if this agrees with your output. Also note that the
original axes labels from p1 disappear. Finally, examine the use of the AspectRatio directive as
follows:
Show[p1,Graphics[{Text["b=2",{0.6,0.9}],Text["b=1",{3.2,0.90}]}],
PlotRange->{0,1}, Frame->True,FrameLabel->{"x","y"},AspectRatio->1]
12
Exercise 8: Plot the function, y = x2 for x < 0 and y = x4 - 1 for x > 0, over the interval of -1 ≤ x
≤ 1. Give the plot the title "Problem 2", name the axes x and y, and make the curve thick, gray,
and dashed. (Note: There are two ways to do this problem. You can define y as a piecewise
function, or you can instruct Mathematica to plot each function separately over different ranges
and then show the functions on the same plot. If you plot each function in separate plots
identified as p1 and p2 and combine them using the Show command (i.e., Show[p1,p2] or
Show[p2,p1]), Mathematica will only show the plot listed first (i.e., p1 if you have instructed
Mathematica to Show[p1,p2]). To see both p1 and p2 on the same graph, you will need to force
the Show command to show the entire plot range using the PlotRange directive for both the x
and y directions. Add to the Show command, PlotRange Æ {{ax,bx},{ay,by}} where the range
for x is ax to bx and the range for y is ay and by (use -1 for ax and ay and 1 for bx and by).
Exercise 9. Knowing the shape of some of these functions will be useful, so try plotting them.
Plot the zero and first-order Bessel functions of the first kind (i.e., Jo(x) and J1(x)) for 0 < x <
30).
p1=Plot[BesselJ[0,x],{x,0,30}]
p2=Plot[BesselJ[1,x],{x,0,30}]
Show[p1,p2]
The command ParametricPlot[{f(x),g(x)}, {x,a,b}] plots the function g(x) on the ordinate as a
function of f(x) on the abscissa for a < x < b.
Exercise 10: Plot y = x3 + 2 as a function of z = x2 + 1 for 0 < x < 1.
The ParametricPlot command can also be used to plot an implicit function (i.e., a function in
which the dependent variable cannot be written explicitly in terms of the independent variable).
For example, in the equation x = y3 + 2y2 - 1, the dependent variable y cannot be defined
explicitly in terms of x. Use the ParametricPlot command to plot y defined by the function x =
y3 + 2y2 - 1 in terms of x (i.e., put y on the ordinate and x on the abscissa) for 0 < y < 1. (Hint:
13
Let f(y) = y3 + 2y2 - 1 and g(y) = y.) Compare this plot to x plotted as a function of y for 0 < y <
1 (i.e., put x on the ordinate and y on the abscissa).
The command LogPlot[f(x), {x,a,b}] creates a plot in which the y-axis is logarithmic while the
x-axis is linear. LogLogPlot[f(x), {x,a,b}] creates log-log plots, while LogLinearPlot[f(x),
{x,a,b}] creates a linear y-axis with a logarithmic x-axis.
Exercise 11: Plot y = e-x for 0.001 < x < 10 as (a) a log-linear plot, (b) a log-log plot and (c) a
linear-log plot.
LogPlot[Exp[-x],{x,0.001,10}]
LogLogPlot[Exp[-x],{x,0.001,10}]
LogLinearPlot[Exp[-x],{x,0.001,10}]
Mathematica plots can be enlarged by selecting them with by clicking the left button on the
mouse, clicking and holding with the left mouse button on any corner, and then dragging the
corner until the plot is the desired size. In addition to controlling the graphic attributes through
the Options in the plotting functions (e.g., dashing, thickness, color and so on, you can also
control some of these using the Drawing Tools and the Graphics Inspector, which are available
on the Graphics menu. The Mathematica screencast tutorials provide helpful descriptions for
these operations. Several can be found at:
http://www.wolfram.com/broadcast/#Tutorials-Graphics
(I recommend the "Creating and Utilizing Graphics in Mathematica" by Cliff Hastings). Also,
the Options for Graphics tutorial provides a number of useful examples.
Exercise 12. Plot the zero and first-order Bessel functions of the first kind (i.e., Jo(x) and J1(x))
for 0 < x < 10) on the same plot.
Plot[{BesselJ[0,x],BesselJ[1,x]},{x,0,10}]
To identify which curve is Jo(x) and which is J1(x), add the function Tooltip to the Plot function
as follows:
Plot[Tooltip[{BesselJ[0,x],BesselJ[1,x]}],{x,0,10}]
When you move your mouse over each curve, you should see either BesselJ[0,x] or BesselJ[1,x].
You can add text to this graph, but you cannot edit the appearance of the curves using the 2D
Graphics Inspector when the Tooltip command has been included in the Plot command.
14
Go back to the plot generated by the Plot command without the Tooltip command. Open
the Graphics Inspector from the Graphics menu. Select the plot using a single left mouse click.
The border around the graph appears in orange. This indicates that the graph is selected.
Double-click on the plot. The border now appears as thick gray, which indicates that the graphic
is now editable. While the graphic is editable, left click the mouse on one of the curves. This
should cause the data points calculated to create the curve to appear (this is useful for checking
that enough points have been used to establish the curve shape correctly). Now point the mouse
to the other curve and right-click to select it. In the 2D Graphics Inspector , move the slider
under thickness to the right and watch the curve become thicker. Change the color by clicking
on the color you want in the color bar at the top of the 2D Graphics Inspector. Use the mouse to
select the other curve and change its thickness and color and also make it dashed by choosing
Dashed under the Dashing section of the 2D Graphics Inspector . Change the width of the
dashes by moving the slider to the right.
Add text to the graph identifying each curve as Jo and J1. To do this, open the Drawing
Tools from the Graphics menu and select the Math tool (indicated by the summation symbol with
three horizontal lines to the right). To make a subscript on Jo, open the Basic Math Assistant
palette from the Palette menu and expand the Typesetting section to find the subscript template
(second from the left in the top row of the section with a superscript on the upper tab). Doubleclick on the plot so that it is editable and the left click on the subscript template. This will cause
the subscript template to appear in the plot. Select the main part of the template and type J and
then select the subscript box and type o. To exit from text addition in the template, click the
mouse inside the plot but outside the template. Now select the entire template with a single
mouse click and then increase the font size to 16 using Size from the Format menu. Now move
Jo to the correct curve. Create J1 by selecting Jo with a single mouse click, copy it, and then
select another location in the plot and paste. Double-click on the new Jo to make it editable and
change the o to 1. Now select J1 and move it to the correct curve. Remember that the thick gray
border must be visible for elements within the graphic to be editable. If it is not visible, then
double-click on the graphic and it should appear. Objects within the editable plot will have an
orange box around them when they are selected (by a single mouse click on the object) and the
cursor will flash next to the object when the object is editable (by a double mouse click on the
object).
Add a title to the top of the plot using the Text tool in the Drawing Tools (indicated by
the A with three horizontal lines to the right). (The only difference between the Math tool and
Text tool is that the Math tool expects that you are entering mathematical symbols and then
15
properly italicizes and adds space consistent with mathematical symbols.) Make the title be
Bessel equations plotted as a function of x. Edit the title to be bold, 12 point, Arial font in blue
with an orange background, using the sub-menu options available in the Format menu. When
you are done creating the title, center it on the top of the plot.
Solving Equations
To define an equation, use two = signs, i.e. left hand side = = right hand side. Equations are
not functions. They are equations you might be interested in solving (i.e., finding the values of
one or more of the variables to satisfy the equality).
Analytical Solutions (a symbolic function is generated)
The command Solve will find exact solutions to linear systems of equations. The command is:
Solve[{equation1(x,y) = = equation2(x,y), equation3(x,y) = = equation4(x,y)},{x,y}] where
the equations are functions of x and y. Notice that the brackets are needed around the equations
to be solved, because there are more than one.
Numerical Solutions (a number value is generated)
The main commands to solve equations numerically are:
NRoots[polynomial1(x) = = polynomial2(x), x] will find the roots of a polynomial,
even if there is more than one root.
FindRoot[equation(x),{x, initial guess}] will work for all equations written in the form
that equation(x) = 0 (note, that the zero is not included in the command), provided that the
initial guess is good enough. (Good enough means that FindRoot works; not good enough
means that FindRoot does not work and you must try to make a better initial guess.) In
choosing an initial guess it is often useful to examine a plot of the function. When only one
initial guess is given, FindRoot uses Newton’s method. If you give a low and high range to the
initial guess (i.e., FindRoot[equation[x],{x, low guess, high guess}], FindRoot will use the
secant method instead of Newton’s method. Usually, the secant method is more stable than
Newton’s method (i.e., the secant method may be less sensitive to poor initial guesses).
NSolve[function1(x) = = function2(x), x] will also numerically solve an equation.
Exercise 13: Solve for the x-coordinates where the line y = 4x + 7 and the parabola y = 17 x2
- 0.5 intersect. Get both the numerical and the analytical solution and compare the two.
16
When finding roots to an equation, initial guesses are required. When equations have
multiple roots it is necessary to find multiple initial guesses. To assist in this, it is useful to plot
the two functions to identify the approximate location of the intersection.
Exercise 14. Determine roots of the equation x3 + 2 x2 - x - 2 = 0 using the Solve, Nsolve,
Roots, FindRoot, NRoots commands. Plot the function first, to get an idea of where the roots are
located.
Exercise 15. The plot created in Exercises 9 and 12 show that the Bessel function of the first
kind and order zero, Jo(x), oscillates around zero, much like a sine function. The Sin(x) is zero
when x = n π, where n is a positive integer or zero. Use the BesselJZero[order, the kth zero
larger than 0] function to find the values of x at which Jo(x) = 0. To obtain a numerical value
for the kth zero, enter:
BesselJZero[0,1]//N or N[BesselJZero[0,1]]
Obtain a list of the first 5 non-zero values of x at which Jo(x) = 0 using the Table command and
the N command as follows:
Table[N[BesselJZero[0,k]],{k,1,5}]
Find the first five non-zero values of x at which the Bessel function of the first kind and order
one, J1(x), is equal to zero as follows:
Table[N[BesselJZero[1,k]],{k,1,5}]
Notice that the first argument is now set to one indicating a Bessel function of order one.
Lists
Lists are used frequently in Mathematica, as both input and output. To manipulate a list, it is
helpful to first name the list.
Exercise 16. First, generate two lists:
list1={0,1,2,3}
list2={5,6,7,8}
17
Create a new list, list3, which contains element 1 from list1 (i.e., 0) and element 3 from list2
(i.e., 7) using the following command:
list3={list1[[1]],list2[[3]]}
Say list1 represents time and list2 represents concentration from an experiment. If you want to
pair the data (i.e., you want each time value to be paired with the concentration determined at
that time), then you need to transpose the lists:
list4 = Transpose[{list1,list2}]
should give you
{{0,5}, {1,6}, {2,7}, (3,8}}
Now plot the points in the list using the ListPlot command as follows:
ListPlot[list4,PlotStyle->PointSize[0.05]]
Note that the PointSize designates the size of the symbols designating the data.
Summations
Mathematica can evaluate infinite sums.
Exercise 17. Consider the sum:
−
2 ∞ (−1) n
π2
∑
n =1
n2
This summation has the value 1/6. This can be determined as follows:
Sum[-2/Pi^2*(-1)^n/n^2,{n,1,Infinity}]
Note that ∞ in Mathematica is also represented by the word Infinity. The summation can also
be evaluated by using the symbolic summation template, which is available in the Basic Math
Assistant (from the Palette menu). The summation template is located at the top of the palette
when the Advanced tab is selected. It is also available from the expanded Typesetting option
(with the tab showing the superscript template open). Confirm that the summation listed above
does sum to 1/6 using both the Sum function and the mathematical template for the summation.
Find the algebraic (symbolic) representation of the following sum:
∞
∑ xn
n =0
18
Exercise 18. Next, consider the sum:
∞
−
2
π
2
∑
n =1
( −1) n
n
2
exp( − n 2 π 2 t )
Enter this summation into Mathematica by using the mathematical symbols available in the
Basic Math Assistant\ or by using the following command:
g[t_] = -2/Pi^2*Sum[((-1)^n)/n^2*Exp[-n^2*Pi^2*t],{n,1,Infinity}]
Determine g(t) when t = 0.1. You may need to force Mathematica to respond with a numerical
value with either the N[ ] function or by adding //N to the end of the input text.
Next, plot g(t) for t between 0 and 1.
Plot[g[t],{t,0,1}]
Notice that Mathematica chooses what values of g(t) to plot and it may choose to plot g(t) in
such a way that the value of g at t = 0 is not plotted. If this happens, you can specify the range of
values for g(t) that you want Mathematica to plot using PlotRange->{beginning value of
dependent variable, ending value of dependent variable}. For example,
Plot[g[t],{t,0,1}, PlotRange->{0,0.2}]
Occasionally, for infinite summations that are more complicated than the function g(t) here,
Mathematica will either take a very long time or simply fail (i.e., it goes off to calculate, but
never responds) when asked to plot the infinite sum. Usually this means that Mathematica has
had difficulties with the infinite summation. If it happens to you, you will need to use the
Interrupt Evaluation or Abort Evaluation commands in the Evaluation menu. If this does not
work, then select the Quit Kernel command in the Evaluation menu. Frequently, it will be
possible to plot the infinite sum by representing it with a finite number of terms. That is, you
truncate terms that do not contribute significantly enough to change the plot. Thus, infinity is
replaced by a finite value of n that is large enough that the solution has converged. For this
example n = 20 is close enough to "infinity". Plot the resulting values. Start by entering the
function g(t) again with only 20 terms by either using the following text input for the summation,
g[t_] = -2/Pi^2*Sum[((-1)^n)/n^2*Exp[-n^2*Pi^2*t],{n,1,20}]
or using the summation palette with the upper limit of the sum set to 20. Mathematica will
respond by listing the 20 terms in the summation. This is messy and not necessary. To suppress
this output, end the input line with a semicolon (;). Try this out, by repeating the definition for
g(t) with only 20 terms but adding a semi-colon to the end of the input line. That is,
g[t_] = -2/Pi^2*Sum[((-1)^n)/n^2*Exp[-n^2*Pi^2*t],{n,1,20}]
Now plot g(t).
Plot[g[t],{t,0,1}]
19
Examine the effect of changing the number of terms in the calculation of the truncated
summation for small and large values of time (e.g., t = 0.001, 0.1, and 1). Calculate the
numerical value of the sum for the maximum number of terms set to 1, 2, 5, 10, and 20 (or until
increasing the number of terms further has no effect). To make this easier you may want to redefine g(t) as g(t,nmax) using the following command:
g[t_,nmax_] = -2/Pi^2*Sum[((-1)^n)/n^2*Exp[-n^2*Pi^2*t],{n,1,nmax}]
Then you can evaluate g(t) at t = 0.001 using 2 terms in the summation by entering:
g[0.001,2]
Algebra (Simplification of Answers)
Sometimes when you use Mathematica to check a solution you reached by hand, the answer
Mathematica comes up with looks nothing like your solution. In that case, you may need to
change the form of your solution. Some of the basic commands that come in handy to simplify
the Mathematica output are: Factor[...], Expand[...], Together[...], Apart[...], Cancel[...] and
Simplify[…]. You can also simplify the numerator and denominator of a fraction separately by
extracting just the top or bottom of a fraction. The commands for that are: Numerator[...] and
Denominator[...]. Factor[…] factors the argument. Cancel[…] is used to reduce a ratio of
functions (if possible) to a smaller number of terms. Simplifying solutions in Mathematica is a
bit of an art form. You may have to try many different ways before you find the solution form
you want!
Exercise 19. Define the variable fraction as
fraction =
x3 + 2 x 2 − x − 2
x3 + x 2 − 4 x − 4
Extract the numerator of fraction and set it equal to the variable num.
num=Numerator[fraction]
Factor the numerator. Evaluate the numerator at x = 2.
num/.x->2
Extract the denominator of fraction and set it equal to the variable den. Factor the denominator
and then evaluate the denominator at x = 2. Define newfraction as the ratio of the factored forms
of the numerator and the denominator. Confirm that the algebraic form of fraction has not
changed by evaluating the word fraction. Define a new variable, cancelfraction, as the result
from Cancel[fraction]. Next Expand[cancelfraction]. Next apply the Together[…] command
20
to the result from Expand[cancelfraction]. Finally, apply the Apart[…] command to fraction
to see how Mathematica can be used to find partial fractions.
Practicing with these commands is the only way to get a feel for how they work.
Calculus
Mathematica can do several calculus operations, including differentiation, integration, and taking
limits.
Differentiation
f’[x] computes the derivative of f(x) with respect to x
D[f[x],x] does the same
D[f[x],{x,n}] computes the nth derivative of f(x) with respect to x
D[expression, variable] computes the derivative of expression with respect to variable.
If the expression is a function of more than one variable, this command will result in the
partial derivative of the expression.
D[expression, {variable,n}] computes the nth derivative of expression with respect to
variable
∂xy (found on the Basic Math Assistant from the Palette menu) computes the first
derivative of y with respect to x.
∂x xy computes the second derivative of y with respect to x.
∂x zy computes the derivative of y with respect to x and then z.
Exercise 20. Take the derivative of the summation from Exercise 17 with respect to time.
Mathematica can take the derivative of an infinite sum like the function in Exercise 17. Plot the
derivative of the function and the function for t between [0,1]. (Note that you may need to use a
finite number of terms when plotting the function and its derivative.)
Integration
Mathematica can evaluate definite and indefinite integrals. It can also calculate numerical values
for integrals exactly or numerically. The command for symbolic evaluation of integral is
Integrate[f[x],x] for an indefinite integral, and Integrate[f[x],{x, lower bound, upper bound}]
for a definite integral. The command for numerically integration is NIntegrate[f[x],{x, lower
21
bound, upper bound}]. You can also use the integration template from the Basic Math
Assistant from the Palette menu. The integration template can be found under the Advanced tab
of the Calculator section at the top of the Basic Math Assistant or on the tab with „∫∑ of the
Basic Commands section.
Exercise 21: Integrate 1/x with respect to x.
Integrate (x Sin[x]) with respect to x. Also, integrate (x Sin[x]) for limits of x = 0 and x
= π.
Integrate Exp[-x2] with respect to x. This indefinite integral cannot be evaluated exactly
and Mathematica responds with π / 2 Erf[x] where Erf[x] is the error function, which is defined
to be this integral expression.
Integrate Exp(-x2) with respect to x over the interval from zero to infinity. This definite
integral has a finite value, which Mathematica should recognize. Also, integrate over the
interval [0,1].
Numerically integrate (2/Sqrt[PI])*Exp[-x2] with respect to x over the interval [0,1].
Determine the numerical value of this result by finding Erf[1]. (Remember that Log[e] = 1.)
Limits
Limits calculated by Mathematica can depend on the form of the input. Mathematica may tell
you a limit is zero, or does not exist, even when a finite limit does exist. Be sure to check your
answer and see if it is reliable. You may want to try several different forms for the input, and see
if they return different answers. For more information, look at Mathematica’s help (e.g., search
the Documentation Center available on the Help menu for Limit). The command syntax is
Limit[expression,x->a]. Remember, infinity is Infinity and negative infinity is –Infinity (or
you can use the infinity symbol, ∞, which can be found several places (e.g., the typesetting
section of the Basic Math Assistant or Writing Assistant, or the Special Character command on
the Insert menu. You can also use the infinite symbol from the BasicInput.nb palette.
Exercise 22. Calculate the limit of Sin[x]/x and Cos[x]/x as x approaches zero.
22
Laplace Transforms
Mathematica can take Laplace transforms and can inverse Laplace transforms of simple
functions. The general syntax is LaplaceTransform[function(t), t, s] and
InverseLaplaceTransform[Laplacefunction(s), s, t] where t is the independent variable in the
function and s is the independent parameter in the Laplace transform of function(t).
Exercise 23. Find the Laplace transform of e-t. Find the function f(t) = inverse Laplace
transform of s/(s2 + 1).
Differential Equations
Mathematica can be used to solve differential equations. Two examples/exercises are provided
below. The first example (Exercise 23) illustrates the solution to a second-order, constant
coefficient, ordinary differential equation. The second example (Exercise 24) illustrates the
simultaneous solution of two ordinary differential equations.
Exercise 24. Solve the ordinary differential equation
y’’ - y = 0
for y(1) = 1 y’(0) = 0
Use the command
newsoln=DSolve[{y’’[x]+y[x]==0,y’[0]==0,y[1]==1},y[x],x]
Extract y (that is, the functional expression for y(x) from the resulting output) using the
following command and assign it to the function y[x]:
y[x_]=y[x]/.newsoln
Create a plot of y as a function of x for x = 0 to 1.
Mathematica can find the exact solution to systems of differential equations. Here is an
example to illustrate the use of the basic command for this case. Consider a model that treats the
human body as two well-stirred tanks in series with volumes V1 and V2 as illustrated below.
Concentrations of a chemical (for example, a drug or toxic chemical) are C1 and C2 in tanks 1
and 2, respectively. This type of model called a pharmacokinetic model is used to estimate drug
concentrations as a function of time after injection or ingestion.
23
min
Comp. 1
C1, V1
k12
kel
k21
Comp. 2
C2, V2
Assume that the concentrations of chemical in both stirred tanks are initially zero. At time zero,
a mass of chemical called siv (a small amount delivered by intravenous injection) is introduced
into the first tank. From the first tank, the chemical can go into the second tank or be eliminated
by the kidneys or liver. From the second tank, the chemical can only go back to the first tank.
The second tank represents tissues that store the chemical. All of the transfers between or from
the tanks are assumed to be described by a first-order rate constants. Based on mass balance in
each tank individually, the following two differential equations and initial conditions apply:
V1
dC1
= − k elC1V1 − k12C1V1 + k 21C2V2
dt
V2
dC2
= k12C1V1 − k 21C2V2
dt
at t = 0, C1 =
siv
and C 2 = 0
V1
Exercise 25. Solve this system of ordinary differential equations using the command:
Soln1=DSolve[{v1*c1’[t] = = -1*c1[t]*(kel + k12)*v1+k21*c2[t]*v2, v2*c2’[t] = =
k12*c1[t]*v1-k21*c2[t]*v2, c1[0] = = siv/v1, c2[0] = = 0},{c1[t],c2[t]},t]
Because solutions are provided for two differential equations, the results are presented as a list.
That is, the solutions are contained between a pair of braces (i.e., {{ …. }}). The Flatten
command removes one pair of braces. Now, remove extra braces and simplify the results at the
same time.
Soln2=Simplify[Flatten[Soln1]
Extract c1 (that is, the functional expression for the concentration in tank 1) from the list and
assign it to the function representing the concentration in tank 1 called conc1[t_]. This can be
done as follows:
conc1[t_]=c1[t]/.Soln2
Do the same thing to obtain a function for concentration in tank 2 called conc2[t_] by entering
the following command:
conc2[t_]=c2[t]/.Soln2
24
Create a plot showing the concentration of tank 1 and 2 for t = 0 to 1 when the rate constants and
tank volumes are set as follows: V1 = 1, V2 = 2, kel = k12 = 1, k21 = 0.1 and siv = 1.
Plot[{conc1[t],conc2[t]}/.{v1->1,v2->2,kel->1,k12->1,k21->0.1,siv->1},{t,0,1}]
Chemical Properties and Structures
Use the ChemicalData command to ask Mathematica to provide chemical structures and
chemical properties. For a description of the various ChemicalData options, go to the
Mathematica help for the ChemicalData command. The general format for this command is
ChemicalData["name", "property"] (e.g., ChemicalData["Naphthalene", "Density"]
returns the density of naphthalene). The name of the chemical and the chosen property must
have quotation marks around them to tell Mathematica that this is a word and not a variable.
The name of the chemical needs to be capitalized. You can also specify the chemical using the
CAS registry number instead of the name (i.e., type "CAS91-20-3" instead of "Naphthalene" in
the ChemicalData command for naphthalene). If you do not include a "property" in the
ChemicalData command it will give a molecular structure diagram for the chemical.
Mathematica does not give the units on numerical properties (e.g., density and melting point).
To determine the units for the property, type ChemicalData["name", "property",
"UnitsName"].
Exercise 26. Try out some of the options available in the ChemicalData command. Find out
what properties for which Mathematica can provide information by using the command:
ChemicalData["Properties"]
For benzoic acid, use Mathematica to determine the molecular structure, a 3-D molecular plot
(i.e., "MoleculePlot"), the CAS registry number ("CASNumber"), the melting point
("MeltingPoint") and the units, the density ("Density") including the units, the octanol-water
partition coefficient (Mathematica calls this the "PartitionCoefficient"), the structure in the
SMILES string notation (i.e., "SMILES"), the number of hydrogen bonds accepted
("HBondAcceptorCount") and donated ("HBondDonorCount"), the acid dissociation constant
("AcidityConstant"). Try using both the name ("BenzoicAcid") and the CAS registry number
(65-85-0) to find the alternate names ("AlternateNames"). Notice that when your mouse is near
the 3-D molecular plot, a circular symbol with arrows appears, and you can rotate the plot. You
can zoom in or out on the 3-D molecular plot by holding the control key and moving the mouse
over the object. Try it out!
25
Using Mathematica in Assignments
There will be many times when you will find it convenient to use Mathematica to perform
operations (e.g., plotting) or to check your work (e.g., algebra, integration, differentiation, limits,
Laplace transforms or Inverse Laplace Transforms). Never turn in output that is not clearly
labeled. This can be done by entering comments describing the operation you have performed
using the appropriate text format, or you can label the operation by hand. Whichever approach
you choose to use, please include enough information so that anyone looking at the output knows
what he or she is looking at. All plots should have titles describing exactly what is plotted,
labeled axes and labeled curves. Remember that it is not always easy to follow a list of
Mathematica commands that someone else has assembled. If you have used Mathematica to
perform a mathematical operation, please include the Mathematica output as proof of the result.
Common Errors or Suggestions
1. Spend some time browsing through Mathematica’s built-in functions. Mathematica has lots
of capabilities that will be useful if you know they were available. For example, I discovered
Mathematica’s ability to find zeros of Bessel functions by browsing through the
NumericalMath add-on package.
2. One of the most common errors involve using parentheses ( ) rather than brackets [ ] for
either user-defined or built-in functions or braces { } for lists. For example, if you wanted to
show that log e = 1, the correct function is Log[Exp[1]]. If you instead entered Log[e],
Mathematica would think you wanted to take the natural log of the variable named e.
3. Did you forget the underline in the user-defined function? If you typed function[x_] = x^2
and then evaluated function[2], Mathematica will respond with 4 (try it). But if you typed
function[x] = x^2 and then evaluated function[2], Mathematica will respond with
function[2]. It does not understand that function is supposed to be equal to x2.
4. Check your spelling of both user-defined and built-in functions. Remember that
Mathematica is case sensitive. Cos[x] ≠ cos[x] unless you have defined cos[x] to equal
Cos[x] (i.e., with the input cos[x_] = Cos[x]).
5. Check your syntax. If Mathematica repeats back what you have typed and does not perform
the operation you thought you asked it to do, it is likely that you have a syntax error or that
the command requires an add-on package that has not been added. The syntax error I make
most frequently is I fail to include the underscore after the name of the independent variable
when I am defining a function. For example, I input f[x] = x^2 when I should have input
f[x_] = x^2. Then when I ask Mathematica to evaluate f[2], Mathematica just repeats back
26
f[2] because it did not recognize f[x] as a function.) The next most common error I make is
to forget to capitalize the first letter of built-in functions. For example, I input log[x] instead
of Log[x] to evaluate the natural logarithm of x.
I would like to add to this list. Please send a description of errors you discover or additional
information that might help future users to [email protected]. Thanks!
27

Documents pareils