Introduction to Mathematica

Calculator Features of Mathematica

Mathematica  can be used as a simple calculator.  This is a bit like opening a peanut with a sledge hammer but none-the-less this is a very good place to start learning how to use Mathematica. 
     If you wish to have Mathematica add 2 and 7, then just type 2 + 7 and choose Evaluate Selection from the Action menu.  As a result you obtain from Mathematica

2 + 7

Each calculation performed is a sort of dialogue with Mathematica.  What you tell Mathematica  to do is placed in the input cell labeled In[1]:=  .  The result Mathematica  obtains is reported in the second or output cell which is labeled Out[1]= . The number in square brackets (the number 1 in this case) means this is the 1st dialogue with Mathematica  which has occured since starting this session. By the way, when you do the first calculation (of a session) with Mathematica it always takes longer then subsequent calculations as it is necessary to start the Mathematica kernel (the computational engine) and this take time.  The Mathematica "front end" is how you, the user interact with the kernel.

Subtraction is also easily performed with Mathematica ; for example, subtraction of 7 from 2 is obtained thus

2 - 7

The "spaces" in   2 - 7 can be removed and  2-7 works equally.  (You should try this and all other examples given in the introduction of each module.)  

     At the start of a session, the first calculation takes longer than subsequent calculations since Mathematica  takes time to start its computational engine, the "kernel".  Each time you begin a session, have Mathematica  perform a simple arithmetic calculation so you can verify the kernel is working.   If Mathematica  refuses to perform the simple calculation, the problem may be fixed with some hints at the end of this module.  

The multiplication of 6 and 17 is done either with a "star" (used in many computer languages)

6*17

A "space" for the multiplication operation works equally well

6 17

Combinations of operations may be grouped using pairs of parenthesis

(3+8)*4

The calculation inside the parenthesis is done first before the other calculation. If you try the calculation without parenthesis, namely 3+8/4  thenyou get a different answer.  Unless parenthesis are used, all multiplications and divisions are done first and then additions and subtractions.    Pairs of parenthesis must be used or Mathematica  gives an error message: Syntax::sntxi: Incomplete expression.  

      Division with Mathematica  is different from division on a usual hand calculator since Mathematica  keeps rational  numbers as exact without decimal approximation unless specifically asked to make a decimal approximation.  For example, ask Mathematica  to divide 2 by 5

2/5

Another way of inputing fraction is to use the BASIC INPUT pallet.  This pallet might already appear (somewhere) on your computer screen like

If not, this palett can be made to appear by going to the FILE menu at the top of the screen and selecting PALETTS followed by BASIC INPUT.  Usually this selection sequence is written compactly as
                              File >>  Paletts >> Basic Input
Once the above palett appears, select the icon in the upper right hand corner thus obtain the template

(\[Placeholder]/\[Placeholder])

which you can fill in.  Place the mouse arrow over a box and "click".  Then insert the number you wish.  For, the example before, one obtains

(2/5)

There are several ways to cause Mathematica  to make a decimal approximation.  Perhaps the easiest way to get a decimal result is to put a decimal point at the end of the 2 in the numerator (or the 5 in the denominator).  A dialogue with Mathematica  then yields

(2. /5)

Since 2. is treated as a decimal, Mathematica  treats the division by decimal approximation.

Some Symbols and Functions Contained in Mathematica

The N[ ] function

The "numerical function" N is another method of getting a decimal approximation to a number from Mathematica .  For example,

N[2/5]

The N must be a capital letter in the number function for it to work.   All Mathematica  functions begin with capital letters.  The number function N acts on the fraction 2/5 which is placed inside the square brackets (or argument) of the N function.  Round brackets ( ) or  curly brackets { }  will not work for the argument of N.   These kinds of brackets have other uses in Mathematica .

Exponentials of numbers are obtained using the "hat" symbol (use the shift and 6 key) as commonly used in other programing languages.  Thus "5 squared" (or 5 raised to the 2 power) is obtained thus

5^2

Alternatively, using the BASIC INPUT palett

select the icon in the upper left hand corner obtaining the template

(\[Placeholder]^\[Placeholder])

This can be filled in, for the same example as before

(5^2)

This notation is closer to the usual mathematical notation for exponentiation.

Some useful irrational numbers and constants are built into Mathematica.  The ratio of the circumference to the diameter of a circle,  π       is given the symbol  Pi  in Mathematica  (note the capital P and small i).  If one just types Pi, then Mathematica  responds

Pi

since Mathematica treats Pi as exact for purposes of calculation.  The N function can be used to obtain a decimal approximation to  π

N[Pi]

The accuracy of the decimal approximation can be increased by adding a second argument to the N function.  For example, if you wish Pi  to 80  figures then

N[Pi,80]

The backslash ,  \  means the digits are continued on the next line.  The usual hand calculator cannot do calculations involving this level of precision. The level of precision is the number of digits in the decimal appoximation of a result.  Mathematica treats Pi as exact so the level of precision

Precision[Pi]

is infinite.  The "display precision" is set by the user of Mathematica but by default is it 6 digits.  For example,

N[π]

has six digits of "display precision" (even though internally, Mathematica treats π is having infinite precision).  The "display precision" can be set by the user with the menu links

                    Edit >> Preferences >> Formatting Options >> Expression Formatting >> Display Options >> Print Precision

The greek letter for Pi, namely π is also available (in the more recent versions of Mathematica starting with version 3.0).  Using the same BASIC INPUT palett

π is the icon about midway down (and to the left side-see the arrow) of the BASIC INPUT palett.

The natural number e is also available on the BASIC INPUT palett to the right of the π icon.  Clicking this icon yields e which looks like an e with a vertical bar t(o distinguish from the usual e used in English).  The decimal approximation to e  should be familiar

N[E]

Older versions of Mathematica use the capital E instead of e.

The square root function is also available in Mathematica

Sqrt[12.]

Note the capital "S" in the function "Sqrt" and the argument of the Sqrt is enclosed in square brackets just as the argument of the numerical function, N, discussed before.  Finally, note the decimal point at the end of the number 12.  If instead you use

Sqrt[12]

This is correct but not too useful for situations where you need a decimal approximation.  With Mathematica you can follow one function with another and get a result.  For example,

N[Sqrt[12]]

Alternatively, the square root function is available from the BASIC INPUT palett in the left of the 2nd row (see the arrow):

Clicking on this icon yields the template

(Sqrt[\[Placeholder]])

which for appears, when filled in for the previous example, as

(Sqrt[12.])

Note the decimal after the 12 which "forces" Mathematica to make the decimal approximation.

The other usual trigonometric functions are also available in Mathematica.  For example, the sine function applied to an angle π  (measured in radians) is

Sin[Pi]

a result which is also exact since π has not been approximated.  The sine of an angle measured in degrees (say 30 deg) is obtained by the conversion

Sin[30*Pi/180]

Notice a calculation can be performed in the argument of the sine function and also note the answer is exact, that is the fraction 1/2.  A decimal approximation to this result can be obtained by applying the N function after applying the sine function

N[Sin[30*Pi/180]]

The ability of Mathematica  to take a function of another function is quite useful and we use it often.  Reversing the order of the Sin and N functions results in the same numerical answer as before as you can easily verify by trying Sin[N[30*Pi/180]].

Assignment of a Numerical Value to a Symbol:

Numerical values can be assigned to variables by the simple procedure

b = 6

Now b (inside Mathematica ) has been assigned the numerical value 6.  You may wish to suppress the Out response of Mathematica, in which case place a semi-colon at the end of the assignment

b = 6;

This suppression is useful in a program where some kinds of output may be confusing.  
     You may at times be confused about what value Mathematica  has assigned a variable so when in doubt, just question Mathematica  using a ? (question mark) before the variable

?b

Mathematica  answers that b is defined globally (i.e. throughout Mathematica ) and that b has the value 6.   You can easily change the value assigned by Mathematica  to a variable.  For example,

b = 5

If you use ?b, then Mathematica  indicates it now assigns the value 5 to b.  Alternatively,

Print[b]

Sometimes it is useful to indicate some information about the variable printed using

Print["b = ", b]

This print statement has two arguments "b = " and the variable b separated by a comma.  The information to be printed by Mathematica  about b is enclosed in quotes (the quotes themselves are not printed).

Decimal and Integer Numbers

Mostly you will want Mathematica  to make decimal approximations.  In these cases, it is important you include a decimal when you define a symbol (e.g, x) for the first time.  For example, x=6. instead of x=6.  This rule also applies to the number zero which should be input as 0.0 or 0. but not just 0.  
There are a few cases where n, an integer is used in some calculations to avoid roundoff errors.  So there are some cases where integer calculations will be used.

Scientific Notation

When dealing with numbers that are either very small or very large, scientific notation is preferable to simple decimal notation.  For example, the number 7.5 109  is assigned to z with (note the star * for multiplication and the caret ^ for the exponential)

z=7.5*(10^9)

Alternatively, you could use the BASIC INPUT palett and write something quite close to the usual mathematical notation

z = 7.5 (10^9)

Just make sure to be careful and place a space (or alternatively a "star", *) before the (10^9) otherwise Mathematica will not understand properly what you mean.

Another example, assigning y to 3.4 10-7 is

y=3.4*(10^-7)

Do not include comma separators (e.g. 1, 251.) as this will give an error message

1,251.

Continuation of a Line

On occasion you will have a calculation continue onto a second line.  For example,

2.35 + 4.86 + 3.95 +
    9.80 + 6.72

Notice the last character on the first line is the addition symbol +  This indicates to Mathematica  something is to follow on the next line which is considered part of the first line.  If you wrote instead

2.35 + 4.86 + 3.95
    + 9.80 + 6.72

then Mathematica  treats the two lines as separate additions with one result 11.16 and the other result 16.52  Generally end a line with punctuation (e.g. a comma + ) if you wish the next line to be a continuation of the first in Mathematica .

Capital and Small Letters

Mathematica  knows the difference between the capital letters and small letters.  For example, make the assignment

y=3.0;

Then ask Mathematica  what it knows about y.  You obtain

?y

However, ask Mathematica  about capital Y and you get

?Y

Also, be careful about typing and using the capital letter O, the small letter o, as well as the number zero 0 because Mathematica  knows the difference!

How to Define a Function in Mathematica

It is often useful to define functions (beyond those built into Mathematica ) yourself.  For example, the (straight line) function f[x] is defined using

f[x_] = 7*x + b

The bar after the x in the argument of the function is required by Mathematica  for the "type checking" feature of Mathematica  and since we will not use this feature, it will not be discussed here.  The bar is  obtained by holding down the shift key together with the minus key (at the upper right hand corner of your keyboard). Just be advised you must include the "bar" following the x or the function definition will not work with Mathematica.  To see how f[x] works, evaluate the function f[x]  at  x=2.0  and obtain

f[2.0]

Alternatively, you can evaluate f[x] at x=2.0 using

f[x=2.0]

You can ask Mathematica  for information it has about f[x]  in the usual manner

?f

If you change the value of b to say b=10, then the function f[x] does not change when you evaluated f[x] at the same point x=2.0

b = 10;
f[2.0]

You can also verify that the meaning of f[x] has not changed by doing ?f.

?f

Deleting the Definition of a Function:

You can delete or erase the definition of a function (you previously defined) using

Clear[f]

If you then ask Mathematica  about the function f[x],  Mathematica  reports it no longer has f[x] defined

?f

This is almost always a good thing to do at the beginning of a program for functions and variables you plan  to use.  The only exception is a case where you wish to keep a previous definition or assignment.

Another Way to Define a Function in Mathematica

There is another very useful way to define a function. Suppose you define a function g[x] which is almost the same as the definition of f[x] above

g[x_] := 7*x + b

The only difference is the  : or colon to the left of the equal sign.  The value of g[x] at x=2.0 is (recall b=10 now)

g[2.0]

The new definition is different however,  If you change b to the numerical value b = 15

b=15.

then the value of g[x] at x=2.0 changes as well

g[2.0]

Recall changing the numerical value of  b after f[x] was defined did NOT change the value of f[x] at x=2.0  A function like g[x] defined with a : colon  is more often than not as we will quite often want the ability to change a parameter like b in the definition of a function.

The Meaning of the Equal Sign =

Mathematica  (and other programming languages) use the equal sign for the following operation:  Take the numerical value of what is on the right side (of the equal sign) and assign it to the symbol on the left side (of the equal sign).  This is also how the equal sign is used to define a function.  The arrow key  ←  might be more appropriate in programming languages than = but the arrow keys have another use (i.e. to move the cursor around on the screen).  
     The equal sign as used in programming is different from the meaning of the equal sign in algebra.  The equal sign in algebra is a sort of symbolic pivot on a balance.   What is on the right of the equal sign is the same as what is on the left and what is on the left is the same as what is on the right.  A two headed arrow ↔ would perhaps be a more appropriate symbol for the algebra equal sign in programming.  Instead Mathematica  uses two equal signs together == .  
     If the above discussion of the equal sign seems a bit esoteric, then please ignore it for now.  However, please keep in mind this will be important in some applications and there is a special key for == in the BASIC INPUT palett (see by the arror in the figure below):

Two-dimensional Graphs with Mathematica

It is simple to plot either a built-in function or a user defined function.  For example, a plot of Sin[x] over the range 0 < x <  2π  is done

Plot[ Sin[x], { x, 0, 2 Pi}]

The Plot function has two arguments separated by a comma.  The first argument is the function f[x] to be plotted while the second argument is the range of values of x. In the future,  if you forget the proper syntex, just ask Mathematica  for help using

?Plot

Plot is a function, so following Mathematica  convention the first letter is a capital P.  The option GridLines->Automatic  (notice the capitals G and L as well as A) makes the function appear as drawn on graph paper

Plot[ Sin[x], { x, 0, 2 Pi}, GridLines->Automatic]

Having the grid is useful when you wish to estimate numerical values of the graphed function.

A Mathematica  graph may be assigned a label so it may be referred to later.  For example, one can assign the label "plot1" to a graph via

plot1 = Plot[ 3*x + 7, {x, -3, 5 },
                    GridLines->Automatic]

So plot1 now refers to the graph of a straight line of slope 3 and intercept 7.  Recall that the function g[x] defined above is a straight line of slope 7 and intercept b=15  (if you followed example above).  Mathematica  can be used to graph g[x] using

plot2 = Plot[ g[x], {x, -3, 5 }, 
              PlotStyle->Dashing[{0.05}],
              GridLines->Automatic]

The graph of the function g[x] is associated with the label plot2.  Also g[x] has been plotted as a dashed line using the PlotStyle->Dashing[{0.05}] option.  The 0.05 indicates the dash length is 5% of the width of the plot.  This usage of Plot has three arguments, each of which is separated from the others by a comma.  
      Both plot1 and plot2 can be displayed at the same time using the function Show

Show[plot1,plot2]

Exercises You Can Do with Mathematica

You should quit and restart Mathematica  before beginning these exercises.  This procedure will clear any previous definitions of functions and assignments you have made previously if you have worked through the examples in this text.  If you have a question about how a particular Mathematica  function works, just try a simple example where you know the answer.  You should do this even before consulting Mathematica 's help.

 1. Use Mathematica  to do the multiplication 25.25 * 89.2  and 
       to do the addition 32.2 + 75.1

2. Calculate Sin[2 Pi] .  Calculate Cos[2 Pi] .  Calculate Tan[Pi/2] .  Get numerical values for these functions using for example, N[Sin[2 Pi]].

3. Calculate the sine of the angle 35 degrees.  Make sure you convert degrees to radians in the argument of  Sin using Sin[35.*Pi/180.]    Do you need any parenthesis, for example, Sin[(35.*Pi)/180.], for Mathematica  to do the calculation correctly?

4. Obtain the numerical approximation of Sqrt[15].

5. Obtain the six figure numerical approximation of the natural number, e which is available in Mathematica  as the symbol, e or  E. 
      
6. Plot the function Tan[x] for the range of values 0 < x < 2π.

7. Plot the natural logarithm function Log[x] for the range of values 0 < x < 10.  What kind of error message (or warning) does Mathematica  give at x=0?

8. Plot the function g[x_] := 1/x  for the range of values 0 < x < 5.  What is the meaning of the warning message at x=0?

9. Define a function f[x_] := 2*Sin[x] and plot the function using a dashed line. Assign the label name trigplot1 to this graph.  Plot the Sin[x] function using a solid line and assign this graph the label name trigplot2.  Use Show to plot both of these functions on the same graph.
     
10. Ask Mathematica  for the information it has on the definition of the function f[x].