Basic Elements of Mathematica

M. E. Mauel
[with help from The Methematica Book, by S. Wolfram, 3rd Edition and with Numerical and Analytical Methods for Scientists and Engineers Using Mathematica, by Dan Dubin (Wiley, 2003).]

Mathematica is a very prowerful (and therefore complex) programming system. It takes years to master it! The Mathematica Book is the standard reference is about 1500 pages long and weighs nearly 10 pounds when printed. Fortunately, you do not need to know all of the complexity (and power) of Mathematica to use it in your study of computational mathematics and physics.

When you work with Mathematica, you are working with: (1) notebooks, where you input expressions (using the "front end") and where resulting expressions are displayed, (2) the "kernal" which evaluates and memorizes your expressions and results, and (3) external files, packages, programs, and functions, which you can use to extend the capability of Mathematica.
When typing in Mathematica, be sure to save your work periodically!

Mathematica has a good memory…

When you start Mathematica, it begins with a knowing only the standard environment defined by your student textbook. Unless instructed to forget, Mathematica remembers every expression that you enter (using the "enter key" or "shift-return") and every expression which results from evaluating your expressions.

5^5

5^77

5

ghfjhgfgkh

5!

5 + 5^5

Multiplication uses either the * symbol or a space…

5 * 5 5

In[9]

Out[9]

In[2]

In[3]/Out[4]

$HistoryLength

Using Previous Results

77^2

% + 1

% - %%

Variables

In most cases, the best way to use previous results is to define a user-variable. These are differenent from "built-in" or system constants…

Pi

?Pi

User-defined variables…

halfPi = Pi/2

Remember, Mathematica is case sensitive and a space " " means multiplication!

half Pi

3 halfPi

?halfPi

Remove[halfPi]

?halfPi

3 halfPi

Mathematica can help…

Mathematica has several forms of built-in help.

?Factor

?Factor*

?*Factor*

?*Plot*

??Plot

Of course, the Help Browser is fantastic…!

Mathematica is a good calculator…

Mathematica deals with integers, rational numbers, irrational numbers, real (or approximate) numbers, symbolic constants, and complex numbers.

Integers are exact numbers

(1 + 5)^4

(1 + 5)^100

Short[100000!]

100000! // Short

Length[IntegerDigits[100000!]] (* The above expression is 1/2 million digits! *)

100000!; // Timing

Monitor[Table[{10^n, Length[IntegerDigits[(10^n)!]]},{n,1,6}],ProgressIndicator[n,{1,6}]]

Remove[x,q]

q = x^2 + 2 x -4 == 0;
Solve[q, x]

Rationals are ratios of integers (and they are exact)

2/4 + 24/144

2 + 12/5

?FullForm

FullForm[%%]

FullForm[22.]

Irrationals are represented as simply as possible (without losing precision)…

Sqrt[2]

Sqrt[8]

(2/3)^(1/3)

Real numbers are approximate…

Sqrt[2] // N

?N

N[Sqrt[2],100]

When you use a decimal point, Mathematica uses approximate numbers.

2.0 /Sqrt[2]

Precision[%]

Precision[2/Sqrt[2]]

Precision[2.0/Sqrt[2]]

$MachinePrecision

Complex Numbers

z = (3 + 4 I)/(2 - 5 I)

z = (3 + 4 I)/(2 - 5 I)

{Re[z], Im[z]}

Abs[z]

Sqrt[-1]

Mathematica has notational conventions…

Mathematica has many, many notational conventions that will take getting use to. (It will not be easy at first.) 
A few simple rules to help. (I strongly recommend everyone follow these notational conventions.)

Standard Symbols

Information[#, LongForm -> False]& /@ {"+", "/", "<","=", ":=", "!=", "==", "/@", "&", "#"};

?Map

(3 + 4 ) 10 / 2

5 < 6

5 == 6

Square Brackets for Function Arguments

?Random

RandomReal[]

RandomInteger[{1,100}]

Built-in Mathematica names begin with CAPITAL LETTERS…

Mathematica tries to use complete names for its built-in functions, and if the functions require two or more names, these names are contatenated without spaces.

?Divide

?DivideBy

{x = 2/3, x = Divide[2,3], x = 2 ~ Divide ~ 3, 3 // Divide[2,#]&}

{x /= 2, x = DivideBy[x,2]}

Curley Braces for Lists (and vectors, arrays, and matricies)…

Lists (and vectors and matricies) are used frequenctly in computational mathematics and physics in order to manipulate more than one number at a time. When typing a list, we use curly brackets, {…}.

{E, I, Sqrt[2 - x^2]}

a = {{1, 2}, {3, 4}}

a // MatrixForm

MatrixForm[a]

b = Table[i, {i, 1, 10}]/4

Length[b]

Length[a]

Dimensions[a]

{VectorQ[b], MatrixQ[b]}

{VectorQ[a], MatrixQ[a]}

Parentheses Group Expressions

{3 + 4  10 / 2,(3 + 4)  10 / 2,3 + (4  10 / 2)}

Special Symbols…

{E, Pi, I, 180 Degree}

Arbitrary precision…

?N

N[%%]

N[%%%,30]

{E, π, I, 180 °}

Typing Special Symbols

Typing the "escape" key causes Mathematica to begin to accept characters that interpreted in special ways. For example,

π

{I, Sqrt[-1], ∞, 1/0, (40^1.5), (3/4)}

(10^56)

(You may also use the floating palettes.)

Double Square Brackets for Part (index selection)…

a // MatrixForm

a[[1,1]]

a[[2,2]]

which can also be written using "escape-[[-escape" as

{a[[1,1]], a[[2,2]]}

Comments (within expressions)

a = (* this is a comment *) 5

Mathematica has nice graphics…

One of the most important parts of Mathematica is the simple calls to graphics.

Plot[(x^2)+Sin[(1/(x^2))],{x,-1,1}]

Plot[(x^2)+Sin[(1/(x^2))],{x,-1,1},Frame->True,FrameLabel->{"x","f[x]"},GridLines->Automatic]

??ParametricPlot

Plot3D[((Sin[x] Sin[y])/(x y)),{x,-2 π,2 π},{y,-2 π,2 π},PlotPoints->25]

plt=Plot3D[((Sin[x] Sin[y])/(x y)),{x,-2 π,2 π},{y,-2 π,2 π},PlotPoints->25,PlotRange->All]

g=Graphics3D[{Cuboid[{0,0,0}],Point[{2,2,1}],Line[{{1,1,1},{2,2,2}}],Text["hello",{1,2,2}]}]

Show[g,PlotRange->{{-5,5},{-2,2},{-3,3}}]

ParametricPlot[{i Cos[((π i)/180)],i Sin[((π i)/180)]},{i,0,1000},AspectRatio->Automatic]

sList =Table[{i Cos[π i/180], i Sin[π i/180]}, {i, 0, 1000}];

ListPlot[sList,AspectRatio->Automatic]

Annimation

Much of the excitement of physics is dynamics: describing how objects in our world move!

Mathematica can easily generate nice annimations.We simply make a Table (or list) of Plots.

Plot[(E^(-((x^2)/10))) Sin[π x],{x,-10,10}]

Table[Plot[Exp[-(((x-Δ))^2)/10] Sin[π x], {x, -10, 20}, PlotRange-> {-1,1}], {Δ, 0, 15, 0.5}];

%[[{1,3, -1}]]

ListAnimate[%%]

wavePlot[δ_] := Show[Plot[Exp[-(((x-δ))^2)/10] Sin[π x], {x, -10, 20}, PlotRange -> {-1,1}], Graphics[{RGBColor[0,0,1],Text["δ = " <>ToString[PaddedForm[δ,{4,2}]], {-10,0.9}, {-1,0}]}]]

wavePlot[0]

Animate[wavePlot[Δ], {Δ, 0, 15}]

Mathematica knows calculus…

Clear[x]

Integrate[x Sin[x], x]

D[%,x]

Integrate[Sin[x^2]/x^2, {x, 0, 1}]

?FresnelC

%% // N

NIntegrate[Sin[x^2]/x^2, {x, 0, 1}]

…and solves equations!

Clear[a,x]

eq1 = x^2 - 7 x + 3 a == 0

Solve[eq1, x]

% /. a -> 3 // N

Plot[(x^4)+(x/2)-1,{x,-2,2}]

FindRoot[x^4 + x/2 - 1 == 0, {x,-0.8}]
FindRoot[x^4 + x/2 - 1 == 0, {x,0.8}]

Some differential equations…

DSolve[y''[t] + w ^2 y[t] ==0, y[t], t]

Functions

Part of the power of Mathematica comes from its extensive arsenal of built-in functions. Most of the time, these built-in functions will be sufficient for your work and calculations. I find it wonderful to be able to enter an equation or a complicated expression, envoke the Plot[...] or Simplify[...] comand, and obtain an immediate display of my desired result. 
Since Mathematica has an extensive help facility and numerous reference books are available, you should find it relatively easy to explore and use the many available built-in functions.

Defining your own functions and commands

Functions are defined using the delayed assignment operator, ":=", and arguments are denoted with the blank symbol, "_". The simple example is

square[y_] := y^2

?square

Which can be called in either prefix or postfix form....

square[(a+1)]

square[8]

squareFive[x_,y_] := x^2 + 5y

cube[x_] := x^3

{cube[8 + a], cube[x]}

quad[x_Real] := x^4;
quad[x_Integer] := 1/x^4;

{quad[3], quad[3.0]}

Functions often produce results only when certain conditions are satisfied. For example, the following three functions are equivalent.

g1[x_] := If[x>0,a = 5;x^3,a=-5;-x^3]

Plot[g1[x],{x,-10,10}]

a

g2[x_ /; x >= 0] := x^3 ;
g2[x_ /; x < 0] := - x^3

Plot[g2[x],{x,-10,10}]

g3[x_] := Abs[x]^3

?g*

Local Variables

Mathematica normally assumes that all your variables are global. This means that every time you use a name like x, Mathematica normally assumes that you are referring to the same object. 
Particularly when you write programs, however, you may not want all your variables to be global. You may, for example, want to use the name x to refer to two quite different variables in two different programs. In this case, you need the x in each program to be treated as a local variable. 
You can set up local variables in Mathematica using modules. Within each module, you can give a list of variables which are to be treated as local to the module.

spiral[i_] := {i Cos[π i/180], i Sin[π i/180]}

spiralMod[i_] := Module[{deg}, (* deg is a local variable *)
deg = π i/180;
{i Cos[deg], i Sin[deg]}]

spiralMod[5] == spiral[5]

spiralList = Table[spiral[i], {i, 0, 1000}] // N;

ListPlot[spiralList]

Show[%,AspectRatio->Automatic,PlotLabel->"Spiral List"]

Summary

Mathematica is a very powerful, interpretive computer system. It evaluates your inputs as you type them. Notebooks are used to save a record of your work. They can be edited and re-executed. 
The syntax of Mathematica is compact. You will not be able to learn or use all of the features of Mathematica. Nevertheless, you will be able to make very sophisticated calculations (without alot of programming) after just a few weeks of practice. 
Remember: Always use the "Help Browser". Note that Mathematica is simply an expression evaluator. As you type, you can make definitions and rules that Mathematica uses as it evaluates what you type. 
Finally, Mathematica has wonderful and easy-to-use graphics.