Math 431.7 • 4 March 1999

Getting started with Mathematica—part 2

Your name(s):

Simplifying expressions

Mathematica has only a limited number of rules automatically applied to expressions you evaluate.  For example:

Log[2 Exp[5]]

You can undoubtedly see another, possibly simpler form for this.  (Of course simplicity is in the eye of the beholder.)  By using the Simplify function, you can often obtain something that more closely resembles the "simple" form you expected.

Simplify[Log[2 Exp[5]]]

Here's another example begging for simplification:

Sqrt[(x^2  -  9)/(x - 3)]

Here are two approaches for simplifying a result after you have already obtained it.
•  Approach 1.  Edit the input cell so as to apply Simplify.  Try it now—here is the Sqrt input cell again:

Sqrt[(x^2  -  9)/(x - 3)]

•  Approach 2.  Apply Simplify to the preceding-result variable ( % ), which holds the output of the most recently evaluated input cell.  Try it now—here is the original Sqrt input cell to evaluate again, and then a separate cell to simplify that:

Sqrt[(x^2  -  9)/(x - 3)]

Simplify[%]

The preceding-result variable ( % ) can be used in any expression and not just with Simplify.  For example:

(25/3) (9/100)

%  +  (1/4)

Derivatives

The derivative of a function may be denoted by a prime, for example:

Cos'[x]

Clear[f]f[x_]  :=  0.75  Cos[2  x] Exp[-(x/10)]f'[x]

Lists

Several objects may be grouped together into a list, which is denoted with braces.  For example:

{ (15/30),  Pi,  "Hello, world!",  
      Plot[Sin[θ],  {θ,  0,  2  π}] }

Notice the inclusion of the string "Hello world!" as an entry in the preceding list.

{ (((2  +  3))^3),  (((a  +  b))^3),  
      Expand[(((a  +  b))^3)]}

Vectors

A list consisting of several number represents a vector, and the usual vector operations then apply:

{1,  2}  +  {5,  -8}

4 {1,  2}

Selection from a list

Individual entries in a list can be extracted by indexing, as follows:

\(vec\  = \ {4, \ 8}; 
vec[\([2]\)]\)

For indexing, you may prefer to type Esc[[Esc and  Esc]]Esc  to get more distinctive double brackets:

vec[[2]]

There are many ways to extract parts of lists.  Here is just one:

mylist  =  {π,  abc,  2  +  3,  {8,  9,  10},  (Sqrt[2])};

First[mylist]

Lists in plotting and solving

To plot several functions on a single graph, form a list of the function expressions:

Clear[f]f[t_]  :=  Cos[t]Plot[{f[t],  f'[t]},  {t,  0,  2 π}];

Suppose you didn't know what the graphs of sin and cos look like.  How can you tell from the plot which graph is which?  Apply distinctive styles, such as different colors, to them by using the option PlotStyle, as in the following example.  (The arrow -> may be typed as Esc->Esc for a nice-looking arrow, or you can use the two keystrokes -> by themselves.)

Plot[{f[t],  f'[t]},  {t,  0,  2  π},  
      PlotStyle  ->  {RGBColor[1, 0, 0],  RGBColor[0, 1, 0]}];

To label the axes in a plot, include also the AxesLabel option.  Try it now:  Include the option AxesLabel -> {t, y} for the plot of the cosine and sine functions.

Equations and solving

⚠  Equations are formed with two equal signs!

2  +  2  ==  4

x (x  +  x)  ==  2 (x^2)

To solve an equation, use the Solve function:

Solve[3 x  -  7  ==  (89/5),  x]

Surprised at the output?  It does not directly give you the solution, but rather a replacement rule for the solve variable.  (Moreover, the rule is in the form of a brace-enclosed list; more about that later.)

To convert such a replacement rule into an actual value, use the form expr /. rule.

x  /. %

Better yet, anticipate having to do this and assign the replacement rule result of the Solve to a name:

mysoln  =  Solve[3 x  -  7  ==  (89/5),  x]

x   /.  mysoln

There is still one nasty thing about the answer—it's a list, albeit with a single entry.  And that's because the result of Solve was a one-entry list, and that entry is itself a list.  To get rid of the outer list braces, you can index or, in this case, use the equivalent function First:

mysoln  =  First[ Solve[3 x  -  7  ==  (89/5),  x] ]x  /.  mysoln

To solve several equations simultaneously, put them into a list and use a list of the variables for which to solve:

Solve[{2 x  -  3 y  ==  7,  5 x  +  6 y  ==  4}, 
       {x,  y}]

Solve[{2 x  -  3 y  ==  7,  a x  +  6 y  ==  c}, 
       {x,  y}]

Try this:  Solve the system of equations in the preceding input cell for a and x.

Numerical values

As you have already seen, Mathematica can work with exact rational and irrational quantities such as (Sqrt[2]) and π.  To convert such an exact quantity into its approximate equivalent, use the function N.

{ (Sqrt[2]),  N[(Sqrt[2])] }

By default, Mathematica displays only 6 significant digits, but you can ask for more if you start with exact numbers:

N[(Sqrt[2]),  16]

High precision arithmetic is possible with Mathematica:

N[π,  100]

50!

⚠ However, if the input includes an approximate number—a floating-point (machine) number with a decimal point—then Mathematica will only give meaningful results to machine precision:

N[(Sqrt[2.0])]N[(Sqrt[2.0]),  40]

After getting an exact value of an expression, you may want to use N with the preceding-result variable (%) to get an approximate numerical value:

Expand[((((Sqrt[2])  +  (1/3) x))^6)]

N[%]

Getting built-in help

There are two basic ways—evaluating an information expression and using the help browser.

Information

To get a brief summary of the syntax and meaning of a built-in object, evaluate a cell with an information expression like the following:

?DSolve

Try this now:  Use the information you just obtained about DSolve to solve analytically with Mathematica the ODE:
	y '  =  y (1  -  y)
Hints:
•  You have to use y[t] and not just y in the expression of the ODE.
•  You need to use the double equal sign == instead of = in the differential equation.
•  Arguments to Mathematica functions are enclosed in square brackets, not parentheses!

Stuck?  If so, peek at the seemingly blank, "scrunched down" cell immediately below this one.  That cell is closed to hide its contents.  To open it and thereby reveal the hint, select its cell bracket.  Then from the Cell menu select Cell Properties and then Cell Open.

DSolve[y'[t]  ==  y[t] (1  -  y[t]),  y[t],  t]

Asking for information about a name that you have defined will display its definition:

?f

If you know just part of the name of an object, you can use wild cards in the information request.  For example:

Try it now: Find out what objects have names ending in Solve.  (That's what you might do if you didn't know the exact function that solves ODEs.)

Options

Many Mathematica allow options—optional arguments of the form optname -> val that you can use to modify the way the function works..

To find out about options that are available for a function and what the default values for those options are, use the function Options:

Options[Plot]

Here's just one example of adding an option to a Plot expression.  The option is AxesLabel, used to label the axes with the corresponding variables.  (By default the value of the option is None, meaning that no labels are displayed.)

Plot[Cos[t],  {t,  0,  2  π}];

Plot[Cos[t],  {t,  0,  2  π},  
      AxesLabel  ->  {t,  y}];

Try this:  In the input cell below, experiment with one or more of the options Frame, Axes, and GridLines.  (There is a hint in the seemingly blank, "scrunched down" cell immediately below this one.  That cell is closed to hide its contents.  To open it and thereby reveal the hint, select its cell bracket.  Then from the Cell menu select Cell Properties and then Cell Open.

Hint:  Frame and Axes can take values True and False; GridLines can take values Automatic and None, among other possibilities.

Plot[Cos[t],  {t,  0,  2  π}];

Attributes

Functions may have attributes that specify how they should be handled when evaluated.  Consider, for example, the built-in function PrimeQ, which tells whether a positive integer is a prime number:

PrimeQ[23]PrimeQ[42]

Examine the attributes of PrimeQ:

Attributes[PrimeQ]

What does the attribute Listable mean?

?Listable

Simply put, this means that PrimeQ automatically is evaluated individually at each entry in a list used as its argument and then the values are assembled back into a list, as in:

PrimeQ[ {23,  42} ]

(There's more about lists below.)

Try this:  Find out what attributes the built-in function Cos has and then what these attributes mean.

The help browser ( very important! )

The Help Browser provides (nearly) complete documentation about Mathematica.

To open the Help Browser, from the Help menu select Help.  Then navigate to find the topic you want.

The Help Browser window has the following four main parts.

The text field at the top, next to the Go To button.   The text field is where you can type an item to look up.  Clicking on the Go To button takes you to the item.  But what document the Help Browser searches is determined by which "radio button" is pushed.  By default, this document is the Built-in Functions list.  (If what you're looking for doesn't show up in the Built-in Functions, try the Master Index.)

Just below the blank field is a bank of "radio buttons" exactly one of which will be selected at a given time to indicate where item searches take place and what is shown in the

Try it now:  With the default radio-button selection of Built-in Functions, go to help about NDSolve (not DSolve).

The four index panels below the radio buttons show the various levels of indices of the selected document, with the topmost level in the leftmost panel.  By clicking on an item in one panel, you activate the next-lower level of index, if any, in the next panel to the right.

Try this:  Navigate to the help about DSolve by selecting Algebraic Computation in the first index column, then an appropriate entry  from the second column, and finally the entry DSolve in the third.

The large help window at the bottom of the Help Browser contains the help about the item you select.

Often the help window includes blue, underlined hyperlinks to other Help Browser documentation entries.

Try it now:  In the help window about DSolve, follow the hyperlink to the first of the two entries in the Mathematica book (you'll probably have to scroll down in the help window to find the hyperlink).

Try this now:  Use the additional help you just obtained to solve analytically with Mathematica the initial value problem:
	y '  =  y (1  -  y), 
                  y(0)  =  -2  .

Next, click the Back button at the top of the Help Browser to return to the main DSolve help.

Like many Help Browser entries, the one for DSolve ends with a Further examples part that looks like the following:

Further Examples

(If this were the help window in the Help Browser, you would see examples here.)

To see the examples in such a specially formatted closed group, click on the little triangle to open the group.  Try it now to see Further Examples for DSolve.

The display in the large window at the bottom of the Help Browser is, in fact, just another Mathematica notebook, albeit one with a specialized style.  So you can copy examples from the Help Browser window and paste them into your own notebook.

Try it now:  Copy below into this notebook one of the "Further Examples" input cells that you found in the help about Solve.  Then evaluate the input cell—perhaps after modifying the example.

What's next?

Cleaning up