Getting Acquainted with Mathematica

Goal:  This is an introductory lesson which has the goal of getting you familiar with how to use Mathematica  for algebraic calculations, symbolic manipulation, graphics, and text input.

Introduction

Mathematica is a powerful software package which combines numerical computations, symbolic manipulation, graphics, and text.

Some General Rules

The first letter of all built-in Mathematica commands must be capitalized.

To have Mathematica  evaluate a command you type (such as 6+7) you must press the ENTER key on the extreme right of the keyboard or SHIFT RETURN (i.e., hold the SHIFT button down while pressing RETURN)

To get HELP in Mathematica you can go to the Help menu or if you know the command type "? Command" or for more infor
"??Command"

?Plot

?? Plot

Special Characters:

^    means exponentiation:  (3^2 denotes 3 squared)

/    means division:   (23/75 denotes 23 divided by 75)

*    means multiplication ( 14*72 denotes 14 times 72)

( )  round parentheses are used to indicate the order  of 
      evaluation; for example, (x+7)/4 represents the sum 
      of x and 7 divided by  4 whereas x+(7/4) means divide 7
      by 4 and then add the result to x.  Note that the  
      expression x+7/4 gives the same result as x+(7/4) since 
      the order of operations is the following: 
      exponentiation, multiplication/division, addition/
      subtraction starting from the left of the expression;
      calculations inside of parentheses are done first.

[ ]   square brackets are used with Mathematica functions and
      commands such as Sin[x]

{ }  curly brackets indicate lists

%    means the result of the last calculation

Arithmetic operations

Mathematica  can easily do the arithmetic calculations that you normally use your calculator to do. (Of course, it can do much more. )

Example 1.  Calculate 145+499 + 7 times 155

145+499 + 7*155

Example 2.  Calculate (23+190)\(TraditionalForm\`\^2\)  divided by (119-(3^5))

(23+190)^2/(119-3^5)

Note that this is the exact answer to our question.  If we want a decimal approximation we use the command N[expr,n ] which gives a numerical approximation of the expression to n digits; if the number of digits is not specified, the default value is used.  Here we can use % as the argument since it denotes the output of the previous calculation.

N[%]

Alternately, you can type //N after a command to get a numerical approximation

(23 + 190)^2/(119 - 3^5)  // N

Another example would be to obtain π to a certain number of digits.

N[Pi, 50]

Example 3.  Mathematica has a built-in function for evaluating the square root of a number, Sqrt[];  use it to calculate the square root of 343 to 20 digits of accuracy

N[ Sqrt[343],20 ]

Note that if we had simply asked for Sqrt[343] Mathematica would have not given me an answer as a decimal since it  gives an exact answer and does not round the answer unless we ask it to do so.

Sqrt[343]

N[%,20]

Exercise 1.  Find the area of a circle of radius 7.5 to 10 digits of accuracy.  Mathematica  has a built-in function for π called Pi. 
To input your answer after this text, move the cursor below the text until you get a horizontal bar, click the mouse and start typing.  (You can check your answer by  double-clicking the following cell bracket which has a darkened triangle at one end.  This will display the answer.)

N[ Pi*7.5^2,10]

Symbolic Manipulations

Mathematica  is capable of manipulating algebraic expressions as well as arithmetic ones.

Example 4.  Factor the expression x6-3x4+2 using the command Factor

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

Example 5.  Multiply (or expand) the expression 
       (x-1)*(x+1)*(x4-2x2-2)

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

Example 6. Simplify the expression  (x4-2x2+10 / (x2-2x+1)

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

Mathematica  can solve some algebraic equations using  the Solve command whose format is
        Solve[ lhs ==0, x]
which solves the equation lhs=0 for the variable x. (Later we will see that the FindRoot command (which uses Newton's method) is also useful for finding roots of algebraic equations.)

Example 7.  Find the  roots of the equations  (i) x2-x=2  and (ii) x3+x-2=0

Solve[x^2-x-2==0,x]

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

In the second example note that we have found one real root and two complex roots.  Here I denotes the square root of -1.

Exercise 2   Suppose that you have forgotten the quadratic formula.  Use Mathematica to derive it; i.e., solve  ax2+bx+c=0 for x.  (Again you may check your answer by double-clicking the following cell.)

Solve[a*x^2+b*x+c==0,x]          2
Solve[a x  + b x + c == 0, x]

Trigonometric Functions

Mathematica has built in functions for the trigonometric functions.

Example 8. Calculate  sin(1.3)   (where the angle is given in radians)

Sin[1.3]

Example 9. Simplify (sin2 x + cos2 x) using the Expand command with an option to use trig identities.

Expand[ (Sin[x]^2+Cos[x]^2),Trig ->True]

Limits and Differentiation

Mathematica  can also calculate various limits and it uses the same rules you learned in first semester Calculus to evaluate derivatives.

Example 10.  Calculate (i) limitx->0  1/(x2+1) and (ii) limitx->0 1/x2  using the command Limit[expr,x->x0 ] which calculates the limit of the given expression as x approaches x0.

Limit[1/(x^2+1),x->0]

Limit[1/x^2, x->0]

The built-in command for differentiation is  D[f,x] which differentiates the function f with respect to x.

Exercise 3.  Differentiate  (x4-x2+1)5 and then  have Mathematica  rewrite the answer as a polynomial.

Integration and Differential Equations

Mathematica  can also evaluate a definite or an indefinite integral.  For the integrals which can not be evaluated analytically, we must approximate them using numerical quadrature rules.

Mathematica  uses the built-in commands Integrate and NIntegrate to perform analytic and numerical integration.

Example 11. Evaluate ∫ sin x dx and (∫_0^π) sin x dx

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

To numerically integrate the definite integral we use NIntegrate.

NIntegrate[ Sin[x],  {x, 0, Pi}]

In an ordinary differential equation we are given the derivative of a function and want to find the function itself.  For example
       y'(x) = 2 y(x)
asks us to find a function y(x) whose derivative is twice itself.  Mathematica can solve many ODEs analytically
using the command DSolve.  For those that it can't solve analytically, one can use the command NDSolve.

Exercise 4.  Use the command DSolve to find the general solution to the ODE
          y'(x) = 2 y(x)
You may first want to use the help command to find th
the general format for the command.

Then use the same command to find the solution to the Initial Value Problem
         y'(x) = 2 y(x)
         y(0)   = 4
Remember that the argument should be in square brackets, i.e., y[x] and that "==" is used for equality.

DSolve[ y'[x]  == 2*y[x], y[x],x]
DSolve[{y'[x] == 2*y[x],y[0]==4},y[x],x]

Assignments in Mathematica

You can assign a name to a result in Mathematica  in two basic ways.  The first is an immediate assignment which is of the form  lhs = rhs .  This evaluates the right-hand side before  the assignment takes place.  A second means of assignment is a delayed assignment which is denoted by lhs := rhs .  It is called a delayed assignment because every time you invoke the function it returns to the original definition. After we have defined a function  we can evaluate it at given values of its argument or manipulate it in various ways.

When defining a function (or any expression or graphics) we can use any name as long as it is not the name of a built-in Mathematica function or command.  Since every built-in Mathematica function begins with a capital letter, we should be safe if we only use names which begin with a lower-case letter.  Also, since definitions of functions are often modified, it is imperative that we use the command Clear to avoid any ambiguity when creating functions.

When you first define a function you must always enclose the argument in square brackets and place an underline after each variable in the argument on the left-hand side of the statement.

Example 12. Clear the names y, w, and a. Set to be the fixed value a=4.  Define a function y(x) to be the expression x2+a using an immediate assignment, i.e., lhs=rhs, and a function w(x) to be the same expression but using a delayed assignment, i.e., lhs := rhs . Evaluate y(2) and w(2).  Now set a=0 and again evaluate y(2) and w(2) and explain why you get different answers.

Clear[y,w,a]
a=4;
y[x_]=x^2+a
w[x_]:=x^2+a

One immediate thing we notice is that Mathematica  does not give us a response after the delayed assignment is entered.  If we ask for y[2] and w[2], we will get the same answer.

y[2]
w[2]

However, if we reset the value of a to be 0, then we get different values.   This is because y[x] was set to x2+4 since that was the value of a at the time the assignment was made; but w[x] returns to the original expression using the current value of a which is now zero.  (Note:  the semicolon after the following command a=0 suppresses the output from Mathematica .)

a=0;
y[2]
w[2]

Exercise 5.  The built-in Mathematica  function Random generates a random number between zero and one.  Define r1 to be Random[] using an immediate assignment and r2 to be Random[] using a delayed assignment.  Explain the difference.

r1=Random[];
r2:=Random[]
r1
r2

If we now ask for r1 and r2 again we will see that r1 gives the same value but r2 a different value.  This is because r1 is set to a given value for all time whereas r2 returns to the definition and calls the function Random again so it gets a new number.

r1
r2

Graphing

The Plot command is used to make an xy-plot.  Its format is
         Plot[ f, {x,xmin,xmax}  ]
where f is the function of x to be graphed from x=xmin to x=xmax.

Example 13. Plot  sin(x) from x=-π  to x=π

Plot[Sin[x] , {x, -Pi, Pi}]

Example 14. Plot  sin x and  cos x  on the same plot from x=-π to x=π .  (Note that to do this we must put the two functions in a list which is denoted by { }. )

Plot[{Sin[x],Cos[x]},{x,-Pi,Pi}]

There are many options to the Plot command which allow you to add labels, colors, etc.  The following example plots the two graphs in different colors and adds a label to the graph.

\(Plot[\ Sin[x]\ , {x, \(-Pi\), Pi}, 
	       PlotStyle -> RGBColor[1, \ 0.0800183, \ 0.110842], 

       PlotLabel -> "Graph of Sin"]\)\(Plot[\ {Sin[x], Cos[x]}\ , {x, \(-Pi\), Pi}, 
\        PlotStyle -> {RGBColor[1, \ 0.0800183, \ 0.110842], 
		
           RGBColor[0.297948, \ 0.190021, \ 1]}, 

       PlotLabel -> "Graph of Sin and Cos"]\)

Exercise 6.  Use the Plot command to graphically approximate the solutions to the nonlinear equation
             sin x  -  x^4-2  =  0
Label your plot and draw the graphs in different colors.

Plot[{Sin[x],x^4-2},{x,-Pi,Pi}, PlotStyle->{RGBColor[1, 0.0800183, 0.110842],
		RGBColor[0.297948, 0.190021, 1]},
PlotLabel->"Graph of Sin x and x^4-2"]

The command ListPlot can be used to plot a list of data.  Plot3D generates a 3-D plot; other commands for density, contour, etc. plots exist.

Exercise 7.  Use the ListPlot command to plot the discrete data given in the array below.  You must first enter the command defining the array.  Graph the data first with just the points and then again with the points connected.

data = Table[ {n, n^2}, {n, 0, 1, .1}]

ListPlot[data]
ListPlot[data,PlotJoined->True]

Text

Mathematica  consists of two parts, the Notebook front-end and the kernel which does the calculations. The front-end sees everything you type and also contains the output from Mathematica. You send a command to the kernel to evaluate when you type Enter or Shift Return. Most of what you type will be commands or expressions to be evaluated by the kernel but often we also want to add text for comments or explanations.  You must remember that text is not input to Mathematica; i.e., you don't use SHIFT RETURN or ENTER after the text since this will send it to the kernel to be evaluated. 

If you type a command Mathematica  assumes that it is input to the kernel and so you must tell it that it is text.  If you look at the Cell Style submenu under the Style menu you will see the various types of  formatting you can use for text.  For example, the heading Text for this section is the style Subsection.  In order to input text all you have to do is place the cursor & click where you want to input a new cell of text.  Before typing go to the style you want in the Cell Style submenu of the Style menu and click on the format you want.  You can change the style of an existing cell by selecting the cell and clicking the appropriate cell style from the menu.  You can also use key strokes instead of the menus.

Exercise 8.  Change the following sample text to (i) section style, (ii)  subsection style, (iii) subtitle, and (iv) title format.

Sample Text