Programming in Mathematica
Programming in Mathematica
Programming in Mathematica
Lecture 0
Physics 367
Scientific Computing
1 of 15
0.1. ARITHMETIC OPERATIONS Lecture 0
on the context, there are faster (and slower) ways to generate functions. In
this class, we will bundle almost every set of comptutations into a function,
and this is to mimic good coding practice that is enforced in more traditional
languages (for a reason – the logic and readability one gains by breaking
calculations up into named constituents cannot be overvalued). Finally, we
will look at two important ideas for algorithm development: Recursion and
Function pointers. Both are supported in Mathematica, and these are also
available in almost any useful programming language.
All of the basic arithmetic operations are in Mathematica – we can add and
subtract, multiply, divide, even evaluate trigonometric functions. The only
occasional hiccup we will encounter is the distinction, made in Mathematica,
between an exact quantity and a number – in Figure 1, we can see that when
presented with 1/4, Mathematica responds by leaving the ratio alone, since
it is already reduced. What we are most interested in is the actual numerical
value. In order to force Mathematica to provide real numbers, we can wrap
expressions in the N function, as in In[5], or we can specify decimal places,
as in In[6] of Figure 1.
Mathematica is aware of most mathematical constants, like π and e, and
when necessary, I’ll tell you the name of any specific constant of interest.
Finally, all angles used in trigonometric functions (and returned by arc-trig
functions) are in radians.
2 of 15
0.2. COMPARISON OPERATIONS Lecture 0
In[1]:= 3 ! 5 In[1]:= 3 ! 5
Out[1]= 8 Out[1]= True
Figure 1: Examples of basic arithmetic input and output and logical oper-
ations.
3 of 15
0.3. VARIABLES Lecture 0
0.3 Variables
In[2]:= p Out[2]= 9
Out[2]= 5 q ! 10;
In[3]:=
In[3]:= q ! 7; In[4]:= q
x Out[5]=
Out[5]= x!!2$$
In[6]:=
y Out[7]= 3.
Out[7]= x
!1., 3., 25., 49., 81."
In[8]:=
Out[8]=
We can define tables of fixed length by specifying the appropriate values for
each entry, using {...}, as in the definition of x on the left in Figure 2.
4 of 15
0.3. VARIABLES Lecture 0
In[1]:= x ! 2;
y ! 3;
In[3]:= x " y
Out[3]= 5
Out[5]=
12., 14., 16., 18., 20., 22.$
X " Y
#2., 4.30902, 6.58779, 8.80902, 10.9511,
In[7]:=
Out[7]=
13., 14.9511, 16.809, 18.5878, 20.309, 22.$
Figure 3: Using arithmetic operations with variables, list elements, and lists.
5 of 15
0.4. CONTROL STRUCTURES Lecture 0
The most important tools for us will be the if-then-else, while and for op-
erations. These can be used with logical operations to perform instructions
based on certain variable values.
The if-then-else construction operates as you would expect – we perform
instructions if a certain logical test returns True, and other instructions
(else) if it is False. The Mathematica structure is:
"
Print!x";
If!x " 4, Out[1]= !1
In[2]:=
x ! 5;
, In[2]:= While!x # 4, !1
Print!x";
";
x ! #1; 0
"
x ! x $ 1;
1
In[3]:= x 2
!1
5 3
Out[3]= 0
4
1
2
3
4
While[test, op-if-test-true]
6 of 15
0.5. FUNCTIONS Lecture 0
encounter the i/o function Print[x], which prints the value of the variable
x.
Finally, “for loops” perform instructions repeatedly while an iterator counts
from a specified start value to a specified end value – more generally, the
iterator is given some initial value, and a logical test is performed on a func-
tion of the iterator – while the logical test is true, operations are performed.
We can construct a “for loop” from a While loop, so the two are, in a sense
complimentary. In Mathematica, the syntax is:
0.5 Functions
Examples of the Module in action are shown below, but morally, the impor-
tant thing to remember is that we now have a function that can be called
with some inputs, returns some output, and has hidden local variables that
are not accessible to the “outside world”.
7 of 15
0.5. FUNCTIONS Lecture 0
In[1]:= HelloWorld!name_" :!
Module!#localvarx, localvary$,
localvarx ! 1.0;
localvary ! name;
Print!"Hello ", localvary";
"
Return!localvarx";
In[2]:= X ! HelloWorld!"Joel""
Hello Joel
Out[2]= 1.
In[3]:= Y ! HelloWorld!33";
Hello 33
In[4]:= Y
Out[4]= 1.
In[5]:= localvarx
Out[5]= localvarx
8 of 15
0.5. FUNCTIONS Lecture 0
"
Return!outlist";
outlist ! inlist; %" Nlist now stores the length of the list "&
In[2]:= InsertionSort!inlist_" :! Module!#outlist, indexx, indexy, curelm, Nlist$,
Nlist ! Length!outlist";
For!indexx ! 2, indexx # Nlist, indexx ! indexx $ 1,
curelm ! outlist!!indexx"";
indexy ! indexx % 1;
While!indexy & 0 && outlist!!indexy"" & curelm,
outlist ! Swap!outlist, indexy, indexy $ 1";
";
indexy ! indexy % 1;
";
outlist!!indexy $ 1"" ! curelm;
"
Return!outlist"
InsertionSort!#5, 2, 4, 6, 1, 3$"
!1, 2, 3, 4, 5, 6"
In[3]:=
Out[3]=
InsertionSort!#%4, 1, 7, 2, 3, %10$"
!!10, !4, 1, 2, 3, 7"
In[4]:=
Out[4]=
The first function we define is Swap – this takes a list, and two numbers as
input, swaps the value of the elements of the list using the two numbers as
array indices, and returns an array with the two elements interchanged. For
the InsertionSort function, we go through the input array, and sequen-
tially generate a sorted list of size indexx-1, increasing indexx until it is
the size of the entire array. This is an inefficient, but straightforward way
9 of 15
0.6. INPUT AND OUTPUT Lecture 0
There are a wide variety of Mathematica functions that handle various in-
put and output. We will introduce specific ones as we go, I just want to
mention two at the start that are of interest to us. The first, we have already
seen: Print[ stuff ] prints whatever you want, and can be used within a
function to tell us what is going on inside the function.
The second output command we will make heavy use of is ListPlot, this
function takes an array and generates a plot with the array values as heights
at locations given by the array index. ListPlot can be used to visualize
arrays of data, or function values. A few examples are shown in Figure 7.
0.7 Recursion
10 of 15
0.7. RECURSION Lecture 0
In[2]:= ListPlot!X"
1.0
0.5
Out[2]=
20 40 60 80 100
!0.5
!1.0
35
30
25
20
Out[4]=
15
10
1 2 3 4 5 6 7
11 of 15
0.7. RECURSION Lecture 0
div ! inx % 2;
In[1]:= IsDivisableByTwo!inx_" :! Module!#div$,
";
Return!True";
"
";
"
Return!oput";
In[3]:= DivideByTwo!88"
88
44.
22.
11.
Out[3]= 11.
12 of 15
0.8. FUNCTION POINTERS Lecture 0
(no pun intended) the recursion in the definition of MergeSort below. The
helper function Merge takes two lists that are already sorted, and combines
them to form a sorted list.
"
Return!outlist";
";
bdex ! bdex $ 1;
";
index ! index $ 1;
";
index ! index $ 1;
,
For!adex ! adex, adex % Length!lista", adex ! adex $ 1,
outlist!!index"" ! lista!!adex"";
";
index ! index $ 1;
";
"
Return!outlist";
Out[3]=
13 of 15
0.8. FUNCTION POINTERS Lecture 0
called by “users”. The function Swap in the insertion sort example Figure 6
is such a support function – it is not meant to be called by a user of the
function InsertionSort, it is purely a matter of convenience for us, the
programmer.
But sometimes, the user must specify a set of functions for use by a program.
In this case, we don’t know or care what the names of the functions supplied
by the user are – they are user-specified, and hence should be part of the
argument of any function we write. This “variable” function is known, in
C, as a “function pointer” – a user-specifiable routine. Because of the low-
key type-checking in Mathematica, we can pass functions as arguments to
another function in the same way we pass anything. It is up to us to tell the
user what constraints their function must satisfy. As an example, suppose
we write a function that computes the time average of some user-specified
function f (t) – that is, we want to write a function that takes:
1 T
Z
TimeAverage(f ) = f (t) dt. (1)
T 0
We’ll use Mathematica’s Integrate function for now. Our function, called
TimeAverage below, takes as input the function f (t) and the period of in-
terest, T , and returns the right-hand side of (1). The code and two user test
cases is shown in Figure 10.
14 of 15
0.8. FUNCTION POINTERS Lecture 0
"
Return!tavg";
Figure 10: The function TimeAverage takes a function name as its argument,
in addition to the period over which to average.
15 of 15