|
and Information Systems Chapter 13 Mathematica: An Interpreter for Mathematical and Numarical Level Prepared by Introduction The computer scientific term interpreter is
used for the programs which can work mostly in interactive mode. That is, the
program creates an environment for the user such that each instruction given by the
user through the interaction is immediately pro- cessed without waiting for the next entries.
The interactive mode can be avoided by using straightforward processing of a bundle of
commands included in a file prepared by the user. This processing fashion is called
batch mode.
There are various interpreters for symbolic and numeric operations. The
history of their development finds its roots at the
years of 1970s. The first important development toward this target was the creation of
the LISP programming language which was
designed for mostly artificial intelligence. LISP
was an interpreter and its born stimulated the development of some well-known symbolic
and numeric interpreters like REDUCE,Macsyma , and Maple. The main purpose in these
programs was chosen as giving the capability of dealing with mathematical operations at
high level as much as possible. Since the conventional programming languages are
designed normally at a very limited numerical precision these interpreters were tried to
be equipped with highest obtainable numerical precision in according to the demand of
the user.
The program which was developed by the researchers in Princeton
University at the years of 1980s was designed in these
directions. However, this language which was named Mathematica later is not a LISP based program. It is constructed by
using C programming language. Its executable binaries for the
interpreter are obtained from the compilation of the source files written in C programming
language. For this reason, the procedures like linking to existing libraries, creating
new libraries are all dominated by the C programming language logic. The purpose of the
utilization of the C based structure is to avoid the slowness of LISP interpreter.
A lot of symbolic and numeric interpreter including Mathematica are
licensed and needs payment which can not be considered
inexpensive for moderate organizations al- though their academic versions may be
reasonable for the budgets of some Turkish orga- nizations like universities . Therefore,
especially in the last decade there have been various important attemptes to produce publicly
available softwares for numeric and symbolic cal- culations. Amongst these we can
recall Scilab and rlab (which are designed to do alo important and even advanced tasks which
can be done by commercial softwares like
Matlab and Maple), octave which is a powerful
program to do everything can be done by
Matlab and more, MuPAD which can do most of the
things can be done by Mathematica. Our university has the campus license for
Mathematica for the moment . The licence expires at the beginning of March 2001. Hence we have
the capability of using this powerful software at least for this semester of BIL101 and
there are hopes for extending the licence to some period of time in future. If something
happens and the licence can not be extended then we can easily switch to the public
software MuPAD. Syntax is almost same
and what we try to give here is easily applicable to
MuPAD programs. Hence we do not worry for the expiration of the licence for Mathematica
.
In these notes we assume that the students have someinformations about
the back- ground of mathematical operations to be
concerned here and we give some mathematics sections whenever it is necessary. The
students will be responsible for all informations given in this and next chapters of the
notes.
Now we can start to focus our attention on Mathematica more intensely.
We can itemize some important capabilities of Mathematica as follows 1. Mathematica can be used
as a pocket calculator. Calculations can be done either symbolic or numeric level. The default is
symbolic for Mathematica. This utilization can be realized through an interactive
way. To activate an inretactive session under Linux the user should give the
command math at the prompt of Linux
shell. This produces the following display.
Mathematica 4.0 for Linux
Copyright 1988-1999 Wolfram Research, Inc.
-- Terminal graphics initialized --
In[1]:=
where In[1]:= is the prompt of
Mathematica where the user command is waited
for. Each entry given by the user is numbered started from 1. Therefore,
the user
must type its first command at this prompt. The command will be enterbed
when
the user presses Enter or Return key. When done this leads to urge
Mathematica
for the execution of the command. Mathematica checks the syntax of the
entered
command and returns an error message if there is any error or incompatibility. If the
entered command has nothing wrong in syntax then it is processed . The
output of
the execution is displayed as the content (that is, the right hand side) of the label
Out[n]:= where n stands for the
number of the step. Generally, each input label or
prompt, In[n]:=, corresponds to
an output label, Out[n]:=, with the
same n value.
The n value starts from one at the beginning of the Mathematica session
and increases
by one as the demands of the user follow each other during the session. 2. It is possible to plot the relations between two or three entities
by using a quite ad-
vanced graphics utility coming with Mathematica. The relations between
the entities
can be given by either functions or data tables. The displaying can be
realized in
either text (by some symbols like dots, letters) or graphics display
medium (by pix-
els). The graphic display medium under Unix or Linux operating system is
generally
X Window. The pixel by pixel displaying under DOS is not possible but
you can use
graphical display facilities by passing into the Windows medium. 3. Mathematica can be used as a high level programming language. You
can construct
programs composed of Mathematica commands and combine them into quite
advanced
structures. The high level
statement here implies the great support of the structure
of the program to the user. That is, it is designed to simplify the
utilization of the
program by the user as much as possible. 4. It is possible to make data structural analysis and modelling via
Mathematica. It is
equipped by a lot of facilities to enable us to use Mathematica toward
this end. 5. It is possible to get scientific and technical knowledge by using
Mathematica. Its
programming structure provides this. 6. The software design of Mathematica permits us to call some
external facilities which
are provided by some other programming languages or tools and use them
on Math-
ematica background . 7. It is possible to interactively design and create certain
documents like web pages.
Animations and various voice applications can be constructed by using
Mathematica. 8. It is possible to use and control system facilities within a
Mathematica session. That
is, you can use some system commands during a Mathematica session
without exiting. 9. Mathematica can be used as an embedded systems. In other words,
it can be used as
a macro or subroutine by the other programs . Interactive
Usage of Mathematica
As we mentioned above a Mathematica session is started by giving
the math command under Linux text console. If you use a
term window under X Windows you can do the same thing and proceed as if you work
through the text terminal. However it is possible to use a different interaction between the
user and Mathematica. It is called notebook.
To start this interaction you can double
click on Mathematica icon appering on your X Window. If Mathematica is installed into
your system and this icon is missing then you should report to the system administration
for urging it to check the settings of X Window. Even when Mathematica icon is missing you
are still able to start a noteboo session. All you have to do for this purpose is just to
enter the command mathematica at the prompt of the terminal window appering in the X
display. When done this causes the creation of a window with horizontal and vertical
scrollbars. You can write the mathematica commands on this window and enter them by pressing
the Shift and Enter or Return keys at the same time. When done a prepending
label In[n]:= is prepended to what you
have typed on the window and the command is processed
and the result is given after a prepending label
Out[n]:= where the n parameter
is a counter variable which starts from 1 when the session begins and increases one by
one as the commands are given consecutively . The notebook sessions, the inputs and data
files can be stored under some files. The format of the files are called notebook and this is implied in the suffix of
the filenames. The suffix is .nb. Notebook format files
can be processed through notebook sessions of Mathematica. Since the X Window system is
not widely accessible in the campuses of . Istanbul Technical University
unfortunately we do not emphasize on notebooksessions and rather focus on textual display
terminal usage of Mathematica, that is, the sessions invoked by math command. However, what we
are going to say here are applicable through the notebook sessions. Since the notebook
interaction of Mathematica is a menu driven system its utilization is not difficult
then the text based sessions. There are some file management and palette like utilities
which facilitate the employment of Mathematica. The NT version of Mathematica uses the
notebook interface mostly. You can even use the text based interaction under X Window
system. Then you can do everything you are able to do in the textual interface and
furthermore the graphical display becomes available.
The commands of Mathematica can be given separately, that is, one
command at each single attempt or collectively, that is,
more than one commands at each single attempts. In the case of more than one commands, the
commands must be separated by using a semicolon character between the commands.
However there is a pitfall here. According the Mathematica syntax the commands need
not to be terminated by semicolon and if a command is followed by a semicolon then
Mathematica gives up to display the result of the action defined by that command
otherwise it is displayed. This means that it is better not to use more than one command
entries and not to append a semicolon after each command when all displays are desired
to be seen.
It is possible to recall a previously given command and execute it one
more time through the Mathematica sessions. For this
purpose you can use % symbol to enter the command given as the (n-1). entry through
the prompt In[n]:= If % symbol is
inserted. into a command then the result of the
previous command (not itself) is used at the place where % is given.
There are a few possibilities to exit Mathematica. The most generally
used one is the
Quit command. You can also use the keystrokes Ctrl C for breaking the
procedure and
Ctrl Z for hanging the process and rebooting the system. The selection
from these possibilites depends on the user's
preference and the situation.
Batch Operations Under
Mathematica
You can write a bundle of Mathematica commands into a file and construct
a program and then you can call this program within
an interactive Mathematica session. For this purpose, you can enter the command
<< filename or the command
get["filename"] where filename denotes the name of the
file under consideration. The first one of these commands is similar to the redirectioning
feature of the UNIX systems. The only difference is the utilization of double less than
symbols.
It is possible to display the content of a file by giving the
command !!myfile where myfile is the name of the file whose
content is to be displayed.
You can save a statement or a command into a specified file at any
instant of an interactive session of Mathematica. What
you are going to do for this purpose is to give either the command mycommand >> myfile or the command
Put[mycommand,"myfile"]. When done a file with the name myfile is
opened the command mycommand is written
into this file and then it is closed and saved.
If there was a file with the name
myfile in the present working directory then the content
of this file would be erased and the command
mycommand would be written into the file.
If you want to append the command to an existing file you can use either the
command mycommand >>> myfile
or the command Put Append[mycommand,"myfile"]. In
this case the existing file myfile is
opened and the term mycommand is appended to the content.
If the file to be appended does not exist then a new file under that name is opened and
the statement to be appended is written into this file. Of course the names mycommand and
myfile can be anything under freedom given by the operating system.
It is possible to save a Mathematica session into an executable binary
file. For this purpose you can use the command
DumpSave["dumpfile.mx"] where
dumpfile can be any name given by the user according to
the regulations of the operating system under consideration. The extension .mx is
peculiar to Mathematica for recalling the dump feature of the file. This facility is available
rather under Unix or Linux systems. The storage file dumpfile.mx contains all definitions and
information to regenerate all actions of that session from beginning to that moment. To
run and revitalize the session it is sufficient to give the command Get["dumpfile.mx"] at the desired moment of a
Mathematica session.
It is possible to execute the commands of the operating systems from an
interactive session of Mathematica. For this purpose
the command Run["command"] where
command can be anything under the limitation of
the operating system can be used . The display of the command is directed to the stream
which is used by Mathematica and the correspond- ing output value displayed as zero
(Out[n]:=0).
We can take the commands which will be executed by Mathematica during a
session from a file. We can write the commands
into a file such that each line corresponds to a separate entry. It is better to terminate
the file by the command Quit although
the End- OfFile character is interpreted as a quit
demand by Mathematica unless it is prevented by some Mathematica environmental variables.
The usage of the Quit command is
preferable because it can be used to make Mathematica
temporarily ignoring some portion of the file. We can exemplify the batchwise utilization
of Mathematica by considering the following program file. 1 /2 2*3 Quit where the name of the Mathematica program
file can be anything within the regulations of the operating system under
consideration. However it is better to use
.m extension to distinguish Mathematica files from the
other files although some other programs like Modula may use this suffix. If we name
this file {\tt sample1.m} then we can use the command math < sample1.m which is
redirectioning of the input stream from Standard Input STDIN to the file sapmle1.m. When this command is given the following display
appears on the screen. Mathematica 4.0 for Linux Copyright 1988-1999 Wolfram Research, Inc. --Terminal graphics initialized In[1]:= 1 Out[1]= -
2 In[2]:=11 In[3]:= where the command inputs which are taken
from the file sample1.m are not shown. The display contains the output lines and also
input labels. It is also possible to redirect the output stream from standard output STDOUT to a file whose name is, say, sample1.ses by revising the above command to math < sample1.m > sample1.ses. The
name of the output file here is quite arbitrary under
the limitation of the operating system. However it is better to some specific structures
like .ses to recall some features. For
example, here,
.ses is used to recall the word session since it contains all reactions
coming from Mathematica during that session. Mathematical Operations Via Mathematica Arithmetic Operations
The arithmetical operations under Mathematica are done byu using the
operators which are denoted by the symbols +,-,/.
You can insert one of these symbols between two symbolic or numeric value to get the
corresponding actions. It is generally preferred to leave spaces before and after each
symbol. There is no need to use a specific symbol for the multiplication although the star * symbol can also be used for this purpose.
To leave a space between two consecutive entity is
interpreted as multiplication by Mathematica. The power operator is the caret character
^. The left side of this operator is the base while its right entity is the exponent. The
level of the evaluation depends on the arguments of this operator. If the entries are symbolic
things then the calculation is at symbolic level otherwise it is numeric.
The results obtained from the arithmetic operations on integers are
displayed in such a way that all digits of the result is
shown in the display. There is no finite limitations due to memory allocations of the other
structural programming languages like C, Fortran . This means that it is possible to produce
integer results as large as we want under the memory limitations of the operating system
and the hardware.
You can evaluate the numerical value of any symbolic quantity which has
numerical value. For this purpose the command N[entity] where entity denotes the entity
whose value will be evaluated by Mathematica.
The precision is approximately within 5 or 6 decimal digits. To increase the precision
of the output you can use the same command in a slightly different way, that is, N[entity,precision]} where entity is same as
before while
precision is an integer which corresponds to the desired precision as
the number of the correct digits.
Mathematica can deal with the complex numbers also. For this purpose it
is necessary to use the imaginary numbers unit √-1 which denoted by I in Mathematica. Mathematica percepts that the calculations will be
done at complex numbers level when it encounters I inside a statement.
Archive Constants
The values of some widely used mathematical constants are known by
Mathematica. In other words there are some reserved
constants under Mathematica to use for well known values of universal Mathematical
constants. Amongst these we can mention
I which is the unit of imaginary numbers, that is,
√-1, Infinity (¥) , Pi (3.1415926..), Degree (The conversion factor from degree to radian),
GoldenRatio((1+Ö5)/2), E (e=2.71828..), EulerGamma (g=0.577216..),
Catalan (C=0.915966..). Some Mathematica Commands
Built-in Mathematica commands are named with the concatenated words
which start by capital letters. This form is like
DumpSave as we mentioned above. The commands are responsible for some actions including the
function value evaluation . Hence they generally have one or more than one arguments.
arguments are enclosed between brackets in a comma separated format. Certain important
Mathematica commands are given below with some brief explanations. ·Abs[z]
gives the absolute value of the real value of {\tt z} or the modulus of the
complex value of
z. ·
ArcCos[z] gives the arc cosine of z. ·ArcCosh[z]
gives the hyperbolic arc cosine of z. ·ArcCot[z]
gives the arc cotangent of
z. ·ArcCoth[z]
gives the hyperbolic arc cotangent of z. ·ArcCsc[z]
gives the arc cosecant of z. ·ArcCsch[z]
gives the hyperbolic arc cosecant of z. ·ArcSec[z]
gives the arcsecant of z. ·ArcSech[z]
gives the hyperbolic arc secant of z. ·ArcSin[z]
gives the arc sine of z. ·ArcSinh[z]
gives the hyperbolic arc sine of z. ·ArcTan[z]
gives the arc tangent of z. ·ArcTan[x,y]
gives the arc tangent of y/x, taking into account which quadrant the point (x,y) is in. ·ArcTanh[z]
gives the hyperbolic arc tangent of z .·Arg[z]
gives the argument of the complex value
z. ·Cancel[expr]
cancels out common factors in the numerator and the denominator of expr. ·Cos[z]
gives the cosine of z. ·Cosh[z]
gives the hyperbolic cosine of z. ·Cot[z]
gives the cotangent of z. ·Coth[z]
gives the hyperbolic cotangent of z. ·Csc[z]
gives the cosecant of z. ·Csch[z]
gives the hyperbolic cosecant of z. ·D[func,{var,
ord}] represents the ord order derivative of the function func with respect to the variable var. If the curly
braced argument is not given then the function func itself is returned as result since this
case corresponds to zeroth order different iation. ·Det[m]
gives the determinant of the square matrix
m. ·DiagonalMatrix[list]
gives a matrix with the elements of list on the main diagonal , and 0 elsewhere. ·x/y
or Divide[x,y] is equivalent to x y^-1. ·x /= c divides x by c and returns the new value of x ·Exp[z]
is the exponential function. ·Expand[expr]
expands out products and positive powers in
expr. ·ExpandAll[expr]
expands out all products and powers in any part of expr . ·ExpandDenominator[expr]
expands out and powers that appear asdenom inator in expe ·ExpandNumerator[expr]
expands out products and powers that appear in the nu- merator of expr. ·Factor[poly]
factors a polynomial over the integers.
Factor[poly,Modulus->p] factors a polynomial modulo a prime p. ·FactorComplete
is an option for FactorInteger which specifies whether complete fac torization is to be performed. ·n!
gives the factorial of n. ·FindMinimum[f,{x,
x0}]} searches for a local minimum in
f, starting from the point x=x0. ·FindRoot[lhs==rhs,
{x,x0}]} searches for a numerical solution to the equation lhs==rhs where lhs (left hand side)
and rhs (right hand side) are the
expressions in terms of x variable,
starting with x=x0. ·First[expr]
gives the first element in expr. ·Insert[mylist,myelem,n]
inserts myelem at position n in the list mylist. If n is negative, the position is counted from the
end. ·Integrate[f,x]
gives the indefinite integral of f
which is assumed to be dependent on x with respect to x.
Integrate[f,{x,xmin,xmax}] gives the definite integral. Integrate[f,{x,xmin,xmax},{y,ymin,ymax}]
performs a multiple (double) integrat ion. ·Join[list1,list2,...]
concatenates lists together. ·Length[expr]
gives the number of elements in expr .·Limit[expr,x->x0]
finds the limiting value of expr
when x approaches x0. ·Log[z]
gives the natural logarithm of z (logarithm to base E}. Log[b,z] produces the logarithm to base b. ·Max[x1,x2,...]
yields the numerically largest of the xi elements. Max[{x1,x2,...}, {y1,...},...] yields the largest element
of the union of the two given lists. ·Min[x1,x2,...]
yields the numerically smallest of the xi elements. Min[{x1,x2,..}, {y1,...},...]} yields the smallest element
of the union of the two given lists. ·Minors[m,k]}
gives a matrix consisting of the determinants of all k ´k submatrices of m. ·-x is
the arithmetic negation of x. ·Mod[m,n] gives the remainder on division of. m by n ·N[expr] gives the numerical value of expr. N[expr,n] does
computations to n-digit precision. ·--x decreases the value of
x by 1, returning the new value of
x. ·++x
increasing the value of x by1, returning the new value of x . ·Prime[n]
gives the nth prime number. ·Print[expr1,expr2,...]}prints
the expri, followed by a newline character. ·Quotient[n,m]
gives the integer quotient of n
and m. ·Re[z]
gives the real part of the complex number
z. ·Round[x]
gives the integer closest to x. ·Sec[z]
gives the secant of z. ·Sech[z]
gives the hyperbolic secant of z. ·Sign[x]
gives -1, 0 or 1 depending on whether the real number x is negative, zero, or positive. ·Sin[z]
gives the sine of z. ·Sinh[z]
gives the hyperbolic sine of z. ·Solve[eqns,vars] attempts to solve an equation or set of
equations eqns for the
variables vars.Solve[eqns,vars,elims] attempts to solve the
equations eqns for vars, eliminating the variables elims. ·Sort[list]
sorts the elements of the list list
into canonical order. Sort[list,p] sorts the list list by using the ordering function p. ·Sqrt[z]
gives the square root of z. ·Sum[f,{i,imax}]
evaluates the sum of f with i running from 1 to imax Sum[f,{i, .imin,imax}] starts with i = imin. Sum[f,{i,imin,imax,di}] uses
steps di. Sum[ f,{i, imin,imax},{j,jmin,jmax},...]
evaluates a multiple sum. ·Tan[z]
gives the tangent of z. ·Tanh[z]
gives the hyperbolic tangent of z. ·TeXForm[expr] prints as a TeX language version of expr. Some Sample Mathematica Pragrams
In this section we present 35 differentMathematica prorgramsto explain
the capabili- Ties of Mathematica.The programs are
named as progn.m where n denotes the
number Of the program.The can be run by using the
command math <
progn,m> progn.ses to store The screen outputs of the session in the
file progn.ses. The content of the fileprog1.m |