You are on page 1of 63

Introduction to

Mathematical Modeling
in Mathematica
Bruce E. Shapiro
Department of Biomathematics
UCLA School of Medicine
and
Jet Propulsion Laboratory
California Institute of Technology
bshapiro@ucla.edu
3 June 1998
Presented as part of
Medical Informatics: A Course for Health Professionals
Sponsored by the
National Library of Medicine
and
Marine Biology Laboratory
Water Street
Woods Hole, MA 02543

1998, Bruce E. Shapiro

Medical Informations: A Course for Health Professionals

Introduction............................................3
Features of Mathematica........................4
Commercially Available Applications.........8
System Requirements.............................10
Front End vs.Kernel...............................11

Starting Mathematica............................12
Arithmetic and Algebra...........................15
Exact and Approximate Results................16
Special Constants..................................17
Vectors, Matrices and Lists.....................17
Function..............................................19
Loops.................................................21
Local Variables.....................................22

An Example Population Biology...........23


Mathematica Reference Outline............24
Numerical Computation.........................24
Numerical Evaluation.........................24
Equation Solving..............................24
Sums and Products............................24
Integration.......................................25
Optimization....................................25
Data Manipulation.............................25
Curve Fitting...............................25
Fourier Transform.........................26
Selection of special elements...........26
Set Manipulation..........................26
Matrices and Vectors..........................27
Matrix Operations.........................27
Systems of Linear Equations...........27
Matrix Decompositions..................27
Complex Numbers............................28
Number Representation......................28
Heads..........................................28
Digits, Exponents, and Mantissas.....28
Change of Representation...............29
Infinity........................................29
Numerical Precision...........................29
Evaluation Accuracy and Precision....29
Intervals......................................29
Machine Accuracy and Precision.......30
Options...........................................30
Algebraic Computation..........................30
Basic Algebra...................................30
Formula Manipulation.......................31
Simplification..............................31
Expansion....................................31
Rearrangement..............................31
Parts of an Expression....................32
Numerators and Denominators.........32
Trigonometric Function Manipulation
..................................................32
Root and Radical Manipulation........32
Other Manipulations......................32
Bruce E. Shapiro
Woods Hole, 1998

Mathematical Modeling

Equation Solving..............................33
Calculus..........................................33
Derivatives...................................33
Integration...................................34
Limits, Residues, and Series............34
Polynomial Manipulation...............35
Mathematical Functions.........................37
Basic Arithmetic...............................37
Mathematical Constants.....................37
Numerical Functions..........................37
Random Numbers..............................38
Elementary Functions........................38
Factorial-Based Functions...................38
Combinatorial Functions....................39
Functions from Number Theory...........40
Zeta Function...................................40
Hypergeometric and Related Functions..41
Orthogonal Polynomials.....................42
Elliptic Functions.............................42
Elliptic Integrals...............................43
Mathieu Functions............................43
Lists...................................................44
Construction....................................44
Element Extraction............................44
List Testing.....................................45
List Operations.................................46
Structure Manipulations.....................47
Graphics and Sound...............................48
Data Plots........................................48
Function Plots..................................48
Parametric Plots................................48
Sound Generation..............................48
Combinations of Plots.......................48
Options...........................................49
Primitives........................................50
Programming.......................................53
Assignment......................................53
Testing............................................53
Flow of Control................................54
Compound Expressions..................54
Logical Testings: If, Which, Switch.55
Looping: Do, While, For................55
Transfer of Control........................55
Functions........................................56
Pattern Matching...............................56
Rules..............................................58
Strings............................................58

References............................................59
Appendices
Lotka Volterra Notebook (On Disk) .........64
Wolfram Tutorials (On Disk)...................71
Tour of Mathematica (On Disk) ......91

Page 2

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Introduction to Modeling in
Mathematica: Goal
To develop a basic understanding of what
Mathematica is and how it can be used to do
Modeling through
examples and hands-on experience.

What is Mathematica?
Mathematica is literally A system for doing
mathematics on the computer. [Wolfram
Research, Inc.]
Mathematica is essentially a chalkboard for
doing mathematical computations on the
computer.
It is also a computer language - but you dont
have to learn the language to use Mathematica.
It was developed in the late 1980s by Steven
Wolfram and first released in 1988.
Version 3.0 was released in 1996.

Bruce E. Shapiro
Woods Hole, 1998

Page 3

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Features of Mathematica
It can be used as a calculator
Solves complicated numerical equations
Solves complicated algebraic equations
Two and three dimensional plotting
No limit on numerical precision
WYSIWYG interface available (on version 3.0)
A powerful programming language
A word processor which can also handle
complicated Mathematical expressions
Import/Export data, text, and graphics in standard
formats
Data manipulation - not just numbers
No limit on the complexity of diagrams or
equations
Simple palettes and/or pull down menus for
functions, special characters, and math symbols.
Direct interfaces with Excel and Word (must be
purchased separately)
Standardized ASCII file format to make
Mathematica Notebooks transportable between
platforms.
Standardized ASCII format requires long learning
curve if something happens to your raw data file.
Specialized Reader Program MathReader is
available for free to read Mathematica Files.
Bruce E. Shapiro
Woods Hole, 1998

Page 4

Medical Informations: A Course for Health Professionals

Mathematical Modeling

A specialized program, Mathreader, is required to


understand the ASCII file.
Front end and Kernel can be run on separate
computers.
Can be run directly off of CD-ROM.
Takes a lot of hard disk space (doesnt everything
these days?)
Easy to get simple problems programmed quickly
but takes a long time to learn the whole language
Language is list based (like LISP and SAS)
Expensive (Windows Full Version: $1495;
Educational Price at UCLA store $919; Student
Edition: $139).
The reference manual is over 1400 pages (is this
good or bad?)
Need a password to get it started the first time.
Will randomly ask for password at subsequent
sessions; this may be a virus, because it only
seems to happen to me.
Kernel/Front End Separation means long wait to
execute first command while Kernel is Loading.

Bruce E. Shapiro
Woods Hole, 1998

Page 5

Medical Informations: A Course for Health Professionals

Mathematical Modeling

An Example: Write a Function to Solve a


Quadratic Equation.
What you enter (Version 3.0 Front End):

What you enter (Version 2.2 Front End or


Version 3.0 Front End or Kernel):
quadraticRoot[a_,b_, c_] :=
{(-b+Sqrt[b^2-4 a c])/2,
(-b - Sqrt[b^2-4 a c])/2};

What gets stored in the notebook file:


\!\(\(quadraticRoot[a_, b_, c_]\ :=
\ {\(\(-b\) + \@\(b\^2 - 4\ a\
c\)\)\/\(2 a\), \
\(\(-b\) - \@\(b\^2 - 4\ a\
c\)\)\/\(2 a\)}; \)\)

Bruce E. Shapiro
Woods Hole, 1998

Page 6

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Screen Session for Quadratic

Bruce E. Shapiro
Woods Hole, 1998

Page 7

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Commercially Available Applications


Application

Company

Conix
3D Explorer
Calculus & Bill Davis, Addison
Wesley
Mathematica
K. D. Stroyan,
Calculus Using
Academic
Press
Mathematica
Wolfram
Control System
Professional
Thomas Cool
Cool Economics Pack
Innova
Derivatives Expert
Wolfram
Electrical Engr.
Examples
Wolfram
Experimental Data
Analyst
Wolfram
Financial Essentials
Wolfram
Fuzzy Logic
Wolfram
Geometrica
Loehle
Global Optimization
Industrial Thermics Visual Analysis
Wolfram
Interactive Calculus
Analytica
InterCall
Joe Gregg
Leibniz
MathTensor
Math Tensor
Wolfram &
Mathematica Labs for
Houghton
Mifflin
Calculus Instruction
Wolfram
Mathlink for MS Excel
Wolfram
Mathlink for MS Word
Wolfram
Mechanical Systems

Bruce E. Shapiro
Woods Hole, 1998

Description
OpenGL Graphics
Undergraduate Calculus Course
Three semester undergraduate
calculus course; includes separate
scientific applications volume.
Comprehensive Simulation
Environment
Econometrics and Statistics
Securities and Financial Analysis
Circuits, Antennas, Transmission
Lines
Data fitting, error analysis,
visualization
Design of Financial Systems
Fuzzy logic systems design
Precise Geometric Design
Nonlinear optimization
Thermal analysis
Learn calculus at your own pace
IMSL & NAG direct access
Alternative Front End
Tensor Analysis
Lab notebooks and text for calculus
instruction.
Put notebooks in Excel documents
Put notebooks in Word documents
Rigid body motion analysis

Page 8

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Commercially Available Applications


(continued)
Application

Company

Macallan
Nodal
Wolfram
Optica
Wolfram
Scientific Astronomer
Wolfram
Signals and Systems
Wolfram
Technical Trader
Tensors in Physics Scandinavian Univ.

The Joy of Mathematica


Time Series
TSiControsl
TSiDynamics
Wavelet Explorer

Press
Alan Shuchat and
Fred Shultz,
Addison Wesley
Wolfram

Description
Linear Circuit Analysis
Optical systems design & analysis
General Astronomy System
Signal processing
Trading
CARTAN tensor package
Mathematica Tutorial

Time dependent data analysis

Techno-Sciences

Control Systems Design

Techno-Sciences

Dynamical Systems

Wolfram

Signal and image analysis

Source: http://www.wolfram.com

Bruce E. Shapiro
Woods Hole, 1998

Page 9

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Mathematica System Requirements


Platform

Ver.

Hard
Disk

RAM

MB: Rec./Min.
Microsoft Windows
Windows 95
Windows NT 3.51
Front End Only

3.0.1

116/30

16/8

3.0.1

75

16/8

Macintosh 680x0, OS 7.1


Power PC OS 7.1
Front End Only

3.0.1
3.0.1
3.0.1

118/30
122/32
75

12/9
12/9
5/5

Linux

3.0.2

125

32/16

Unix SPARC
SunOS 4.1.2
Solaris 2.4
DEC AXP Digital Unix
OSF/1.3.0 or higher
HP PA-RISC HP-UX 10.10
IBM RS/6000 AIX 4.1
Silicon Graphics IRIX 5.3
Front End Only

3.0.2

115

32/16

3.0.2

110

32/16

3.0.2
3.0.2
3.0.2
3.0.2

115
100
115
75

32/16
32/16
32/16
32/16

NEXTSTEP 3.0 Motorola


x86
HP PA-RISC
Sparc

3.0.2
3.0.2
3.0.2
3.0.2

100
100
100
100

32/16
32/16
32/16
32/16

IBM OS/2 2.0

2.2.3

10

16/8

DEC OpenVMS 7.0

2.2.3

21

32/16

x86
x86 a.out 1.2
ELF 2.0 or higher

Source: http://www.wolfram.com
Bruce E. Shapiro
Woods Hole, 1998

Page 10

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Front End Kernel


Front End
Platform
Dependent
GUI

Platform Indepenent
Ascii Interface

Kernel
Ascii Notebook Files

Bruce E. Shapiro
Woods Hole, 1998

Identical on all computers


Can be on a different
computer
Computational Engine

Page 11

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Starting Mathematica in Windows 95

Bruce E. Shapiro
Woods Hole, 1998

Page 12

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Using Mathematica
Type 3+3 and then [Shift][Enter]
The kernel will take a while to load.

Things to notice:
The cell brackets
The line indicating the current cell - anything you enter at
the keyboard will go immediately beneath this line.
To create a new cell, move cursor to the end of a cell and
press [Enter] (Windows)
press [Return] (Macintosh)
To evaluate the current cell
press [Shift][Enter] (Windows)
press [Enter] Macintosh
To enter multiple lines within a cell, place cursor within the
cell and press [Return].

Bruce E. Shapiro
Woods Hole, 1998

Page 13

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Text will automatically wrap-around to the next line.

The text will unwrap if you make the window wider:

Bruce E. Shapiro
Woods Hole, 1998

Page 14

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Arithmetic

Multiplication
Variable Assignment

Implied Multiplication
Minus
Addition

Subtraction
Power

Bruce E. Shapiro
Woods Hole, 1998

Page 15

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Square Root

ex

Natural Logarithm
loge(x)
logb(x)
Trig Functions
Pi,

Exact and Approximate


Results
Bruce E. Shapiro
Woods Hole, 1998

Page 16

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Special Constants

First 743 Digits


of

First 743 Digits of e

First 20 Digits of
Golden Ratio

Catalans Constant to 6 digits


/180
Vectors, Matrices and Lists
Bruce E. Shapiro
Woods Hole, 1998

Page 17

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Vector Dot Product


Element by Element
Multiplication
Multiplication by a
Constant
Apply Square Root to
Every Element of a List

Matrices as a list of Lists

Bruce E. Shapiro
Woods Hole, 1998

Page 18

Medical Informations: A Course for Health Professionals

Mathematical Modeling

List Multiplication vs Matrix Multiplication

Definition of a Function

Bruce E. Shapiro
Woods Hole, 1998

Page 19

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Application of a Function to a Matrix

Bruce E. Shapiro
Woods Hole, 1998

Page 20

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Loops

Simple Do Loop

Do Loop with multiple


statements.

Bruce E. Shapiro
Woods Hole, 1998

Page 21

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Local Variables
sum is a Global Variable

Function to
Compute
x,x2, x3
sum is a Local Variable
Function Evaluation
value of sum is unchanged
Function Return
Value is a list of 3
numbers

Bruce E. Shapiro
Woods Hole, 1998

Page 22

Medical Informations: A Course for Health Professionals

Mathematical Modeling

An Example from Population Biology

Source: J. D. Murray, Mathematical Biology, Springer-Verlag, 1989, page 67. Reproduced


for classroom use only.

Bruce E. Shapiro
Woods Hole, 1998

Page 23

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Mathematica Reference Outline


I. Numerical Computation
A. Numerical Evaluation
N[expr] gives the numerical value of expr.
N[expr, n] attempts to give a result with n-digit precision.

B.Equation Solving
DSolve[eqn, y, x] solves a differential equation for the function y, with
independent variable x.
FindRoot[lhs==rhs, {x, a}] searches for a numerical solution to the equation
lhs==rhs, starting with x=a.
NDSolve[eqns, y, {x, xmin, xmax}] finds a numerical solution to the ordinary
differential equations eqns for the function y with the independent variable x in the
range xmin to xmax.
NDSolve[eqns, y, {x, xmin, xmax}, {t, tmin, tmax}] finds a numerical
solution to the partial differential equations eqns.
NDSolve[eqns, {y1, y2, ...}, {x, xmin, xmax}] finds numerical solutions for the
functions yi.
NSolve[lhs==rhs, var] gives a list of numerical approximations to the roots of a
polynomial equation.
Solve[eqns, vars] attempts to solve an equation or set of equations for the
variables vars.
Solve[eqns, vars, elims] attempts to solve the equations for vars, eliminating
the variables elims.

C. Sums and Products


Sum[f, ai, imaxa] evaluates a sum
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
NSum[f, {i, imin, imax}] gives a numerical approximation to a sum.
NSum[f, {i, imin, imax, di}] uses a step di in the sum.

imax
Product[f, {i, imax}] evaluates the product i=1 f
Product[f, {i, imin, imax}] starts with i = imin.
Product[f, {i, imin, imax, di}] uses steps di.
Product[f, {i, imin, imax}, {j, jmin, jmax}, ] evaluates the multiple
jmax
imax
product i=imin j= jmin ... f

Bruce E. Shapiro
Woods Hole, 1998

Page 24

Medical Informations: A Course for Health Professionals

Mathematical Modeling

NProduct[f, {i, imin, imax}] gives a numerical approximation to a product.


NProduct[f, {i, imin, imax, di}] uses a step di in a product.

D. Integration
Integrate[f, x] gives the indefinite integral f (x)dx
Integrate[f, {x, xmin, xmax}] gives the definite integral.
Integrate[f, {x, xmin, xmax}, {y, ymin, ymaxa] gives the multiple definite
integral.
NIntegrate[f, {x, xmin, xmax}] gives a numerical approximation to the
integral
InterpolatingFunction[domain, table] represents an approximate
function whose values are found by interpolation.
See also NDSolve (I B. Equation Solving).

E. Optimization
FindMinimum[f, {x, x0}] searches for a local minimum in f, starting from the
point x=x0.
ConstrainedMin[f, {inequalities}, {x, y, }]] finds the global minimum
of f in the domain specified by the inequalities. The variables x, y, are all
assumed to be non-negative.
ConstrainedMax[f, {inequalities}, {x, y, }] finds the global maximum
of f in the domain specified by the inequalities. The variables x, y, are all
assumed to be non-negative.
LinearProgramming[c, m, b] finds the vector x which minimizes the quantity
c.x subject to the constraints m.xb and x 0.
LatticeReduce[{a1, a2, ...}] gives a reduced basis for the set of vectors a.

F. Data Manipulation
1. Curve Fitting
Fit[data, funs, vars] finds a least-squares fit to a list of data as a linear
combination of the functions funs of variables vars.
Interpolation[data] constructs an InterpolatingFunction object
which represents an approximate function that interpolates the data.
ListInterpolation[array] constructs an InterpolatingFunction
object which represents an approximate function that interpolates the array of
values given.
ListInterpolation[array, {{xmin, xmax}, {ymin, ymax}, }]
specifies the domain of the grid from which the values in array are assumed to
come.
Bruce E. Shapiro
Woods Hole, 1998

Page 25

Medical Informations: A Course for Health Professionals

Mathematical Modeling

FunctionInterpolation[expr, {x, xmin, xmax}] evaluates expr with x


running from xmin to xmax and constructs an InterpolatingFunction
object which represents an approximate function corresponding to the result.
FunctionInterpolation[expr, {x, xmin, xmax}, {y, ymin, ymax},
] constructs an InterpolatingFunction object with several
arguments.

2. Fourier Transform
Fourier[list] finds the discrete Fourier transform of a list of complex
numbers.
InverseFourier[list] finds the discrete inverse Fourier transform of a list
of complex numbers.

3. Selection of special elements


Max[a1, a2, ] yields the numerically largest of the a.
Max[{a1, a2, ...}, {b1, b2, ...}, ... ] yields the largest element of any of the lists.
Min[a1, a2, ] yields the numerically smallest of the a.
Min[{a1, a2, ...}, {b1, b2, ...}, ...] yields the smallest element of any of the lists.
Select[list, crit] picks out all elements a of list for which crit[a] is True.
Select[list, crit, n] picks out the first n elements for which crit[a] is
True.
Take[list, n] gives the first n elements of list.
Take[list, -n] gives the last n elements of list.
Take[list, am, na] gives elements m through n of list.
Count[list, pattern] gives the number of elements in list that match pattern.
Count[expr, pattern, levelspec] gives the total number of subexpressions
matching pattern that appear at the levels in expr s
Sort[list] sorts the elements of list into canonical order.
Sort[list, p] sorts using the ordering function p.

4. Set Manipulation
Union[l1, l2, ] gives a sorted list of all the distinct elements that
appear in any of the li.
Union[list] gives a sorted version of a list, in which all duplicated elements
have been dropped.
Intersection[list1, list2, ] gives a sorted list of the elements common
to all the listi.
Complement[eall, list1, list2, ] gives the elements in eall which are not
in any of the listi

Bruce E. Shapiro
Woods Hole, 1998

Page 26

Medical Informations: A Course for Health Professionals

Mathematical Modeling

G. Matrices and Vectors


1. Matrix Operations
a.b.c or Dot[a, b, c] gives products of vectors, matrices and tensors
Inverse[m] gives the inverse of a square matrix m.
Transpose[list] transposes the first two levels in list.
Det[m] gives the determinant of the square matrix m.
DiagonalMatrix[list] gives a matrix with the elements of list on the leading
diagonal, and 0 elsewhere.
Eigenvalues[m] gives a list of the eigenvalues of the square matrix m.
Eigenvectors[m] gives a list of the eigenvectors of the square matrix m.
Eigensystem[m] gives a list avalues, vectorsa of the eigenvalues and
eigenvectors of the square matrix m.
IdentityMatrix[n] gives the n n identity matrix.
MatrixPower[mat, n] gives the na matrix power of mat.
MatrixExp[mat] gives the matrix exponential of mat.
Outer[f, list1, list2, ] gives the generalized outer product of the listi,
forming all possible combinations of the lowest-level elements in each of them.
Outer[f, list1, list2, , n] treats as separate elements only sublists at level
n in the a.
Outer[f, list1, list2, ..., n1, n2, ] treats as separate elements only sublists
at level ni in the corresponding listi

2. Systems of Linear Equations


LinearSolve[m, b] finds an x which solves the matrix equation m.x==b.
NullSpace[m] gives a list of vectors that forms a basis for the null space of
the matrix m.
RowReduce[m] gives the row-reduced form of the matrix m.
Minors[m, k] gives a matrix consisting of the determinants of all a
submatrices of m.

3. Matrix Decompositions
SingularValues[m] gives the singular value decomposition for a
numerical matrix m. The result is a list au, w, va, where w is the list of singular
values, and m can be written as
Conjugate[Transpose[u]].DiagonalMatrix[w].v.
PseudoInverse[m] finds the pseudoinverse of a rectangular matrix.
QRDecomposition[m] yields the QR decomposition for a numerical matrix
m. The result is a list aq, ra, where q is an orthogonal matrix and r is an upper
triangular matrix.
SchurDecomposition[m] yields the Schur decomposition for a numerical
matrix m. The result is a list aq, ta where q is an orthogonal matrix and t is a
block upper triangular matrix.
Bruce E. Shapiro
Woods Hole, 1998

Page 27

Medical Informations: A Course for Health Professionals

Mathematical Modeling

LUDecomposition[m] generates a representation of the LU decomposition


of a matrix m.
LUBackSubstitution[data, b] takes the data generated by
LUDecomposition[m] and yields the solution to the matrix equation a.
LinearProgramming[c, m, b] (See Optimization)

H. Complex Numbers
I represents the imaginary unit i.
Complex is the head used for complex numbers.
Re[z] gives the real part of the complex number z.
Im[z] gives the imaginary part of the complex number z.
Abs[z] gives the absolute value of the real or complex number z.
Arg[z] gives the argument of the complex number z.
Conjugate[z] gives the complex conjugate a of the complex number z.

I. Number Representation
1. Heads (Beginning of the List)
Integer is the head used for integers.
Rational is the head used for rational numbers.
Real is the head used for real (floating-point) numbers.
Complex is the head used for complex numbers.
Root[f, k] represents the ka root of the polynomial equation f[x] == 0.

2. Parts of Numbers Digits, Exponents, and Mantissas


IntegerDigits[n] gives a list of the decimal digits in the integer n.
IntegerDigits[n, b] gives a list of the base-b digits in the integer n.
IntegerDigits[n, b, len] pads the list on the left with zeros to give a list
of length len. RealDigits[x] gives a list of the digits in the approximate real
number x, together with the number of digits that are to the left of the decimal
point.
RealDigits[x, b] gives a list of base-b digits in x.
RealDigits[x, b, len] gives a list of len digits.
RealDigits[x, b, len, n] gives len digits starting with the coefficient of a.
FromDigits[list] constructs an integer from the list of its decimal digits.
FromDigits[list, b] takes the digits to be given in base b.
MantissaExponent[x] gives a list containing the mantissa and exponent of
an approximate real number x.
Numerator[expr] gives the numerator of expr.
Denominator[expr] gives the denominator of expr.
Bruce E. Shapiro
Woods Hole, 1998

Page 28

Medical Informations: A Course for Health Professionals

Mathematical Modeling

3. Change of Representation
Rationalize[x] takes Real numbers in x that are close to rationals, and
converts them to exact Rational numbers.
Rationalize[x, dx] performs the conversion whenever the error made is
smaller in magnitude than dx.
IntegerPart[x] gives the integer part of x.
Chop[expr] replaces approximate real numbers in expr that are close to zero
by the exact integer 0.
Chop[expr, delta] replaces numbers smaller in absolute magnitude than delta
by 0.

4. Infinity
Infinity or is a symbol that represents a positive infinite quantity.
Indeterminate is a symbol that represents a numerical quantity whose
magnitude cannot be determined.
ComplexInfinity represents a quantity with infinite magnitude, but
undetermined complex phase.
DirectedInfinity[ ] represents an infinite numerical quantity whose
direction in the complex plane is unknown.
DirectedInfinity[z] represents an infinite numerical quantity that is a
positive real multiple of the complex number z.

J. Numerical Precision.
1. Evaluation Accuracy and Precision
N (see IA, Numerical Evaluation).
Accuracy[x] gives the number of digits to the right of the decimal point in
the number x.
Precision[x] gives the number of digits of precision in the number x.
SetAccuracy[expr, n] yields a version of expr in which all numbers have
been set to have an accuracy of n digits.
SetPrecision[expr, n] yields a version of expr in which all numbers have
been set to have a precision of n digits.
$MaxPrecision gives the maximum number of digits of precision to be
allowed in arbitrary-precision numbers.
$MinPrecision gives the minimum number of digits of precision to be
allowed in arbitrary-precision numbers.
$MaxExtraPrecision gives the maximum number of extra digits of
precision to be used in functions such as N.

2. Intervals
Interval[{min, max}] represents the range of values between min and
max. Interval[{min1, max1}, {min2, max2},... ] represents the union of the
ranges {min1, max1}, {min2, max2}, ...

Bruce E. Shapiro
Woods Hole, 1998

Page 29

Medical Informations: A Course for Health Professionals

Mathematical Modeling

IntervalMemberQ[interval, x] gives True if the number x lies within the


specified interval, and False otherwise.
IntervalMemberQ[interval 1, interval 2] gives True if interval2 is
completely contained within interval1
IntervalUnion[interval1, interval2, ] gives the interval representing the
set of all points in any of the intervali.
IntervalIntersection[a interval1, interval2, ] gives the interval
representing all points common to each of the intervali.

3. Machine Accuracy and Precision


MachineNumberQ[expr] returns True if expr is a machine-precision real or
complex number, and returns False otherwise.
$MachinePrecision gives the number of decimal digits of precision used
for machine-precision numbers.
$MachineEpsilon gives the smallest machine-precision number which can
be added to 1.0 to give a result that is distinguishable from 1.0.
$MaxMachineNumber is the largest machine-precision number that can be
used on a particular computer system.
$MinMachineNumber is the smallest positive machine-precision number that
can be used on a particular computer system.
$MaxNumber gives the magnitude of the maximum arbitrary-precision number
that can be represented on a particular computer system.
$MinNumber gives the magnitude of the minimum positive arbitrary-precision
number that can be represented on a particular computer.

K. Options
Compiled is an option for various numerical and plotting functions which
specifies whether the expressions they work with should automatically be compiled.
AccuracyGoal is an option for various numerical operations (e.g. NIntegrate,
NDSolve and FindRoot) which specifies how many digits of accuracy should be
sought in the final result.
PrecisionGoal is an option for various numerical operations (e.g.
NIntegrate and NDSolve) which specifies how many digits of precision
should be sought in the final result.
WorkingPrecision is an option for various numerical operations (e.g.
NIntegrate and FindRoot) which specifies how many digits of precision
should be maintained in internal computations.

II. Algebraic Computation


A. Basic Algebra
Expand[expr] expands out products and positive integer powers in expr.
Expand[expr, patt] leaves unexpanded any parts of expr that are free of the
pattern patt.

Bruce E. Shapiro
Woods Hole, 1998

Page 30

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Factor[poly] factors a polynomial over the integers. Factor[poly,


Modulus->p] factors a polynomial modulo a prime p.
Factor[poly, Extension->{a1, a2, ...}] factors a polynomial allowing
coefficients that are rational combinations of the algebraic numbers ai.
Simplify[expr] performs a sequence of algebraic transformations on expr, and
returns the simplest form it finds.
expr /. rules applies a rule or list of rules in an attempt to transform each subpart
of an expression expr.

B. Formula Manipulation
1. Simplification
Simplify (see Above, IIA, Basic Algebra)
FullSimplify[expr] tries a wide range of transformations on expr
involving elementary and special functions, and returns the simplest form it
finds.

2. Expansion
PowerExpand[expr] expands all powers of products and powers.
ComplexExpand[expr] expands expr assuming that all variables are real.
ComplexExpand[expr, {x1, x2, ..}] expands expr assuming that variables
matching any of the xi are complex.
FunctionExpand[expr] tries to expand out special functions in expr, when
possible reducing compound arguments to simpler ones.

3. Rearrangement
Collect[expr, x] collects together terms involving the same powers of
objects matching x.
Collect[expr, {x1, x2, ...}] collects together terms that involve the same
powers of objects matching x1, x2, .
Collect[expr, var, h] applies h to the expression that forms the coefficient
of each term obtained.
Together[expr] puts terms in a sum over a common denominator, and
cancels factors in the result.
Apart[expr] rewrites a rational expression as a sum of terms with minimal
denominators.
Apart[expr, var] treats all variables other than var as constants.
Cancel[expr] cancels out common factors in the numerator and denominator
of expr.
ExpandAll[expr] expands out all products and integer powers in any part of
expr.
ExpandAll[expr, patt] avoids expanding parts of expr that do not contain
terms matching the pattern patt.
FactorTerms[poly] pulls out any overall numerical factor in poly.

Bruce E. Shapiro
Woods Hole, 1998

Page 31

Medical Informations: A Course for Health Professionals

Mathematical Modeling

FactorTerms[poly, x] pulls out any overall factor in poly that does not
depend on x.
FactorTerms[poly, {x1, x2, ...}] pulls out any overall factor in poly that
does not depend on any of the xi.

4. Select Parts of an Expression


Coefficient[expr, form] gives the coefficient of form in the polynomial
expr.
Coefficient[expr, form, n] gives the coefficient of form^n in expr.
Exponent[expr, form] gives the maximum power with which form appears
in the expanded form of expr.
Exponent[expr, form, h] applies h to the set of exponents with which form
appears in expr.
Numerator, Denominator (See Above, I.I Number Representation)
expr[[i]] or Part[expr, i] gives the ia part of expr.
expr[[-i]] counts from the end.
expr[[0]] gives the head of expr.
expr[[i, j, ]] or Part[expr, i, j, ] is equivalent to expr[[i]]
[[j]] .
expr[[ {i1,i2,...} ]] gives a list of the parts i1, i2, of expr.

5. Numerators and Denominators


ExpandNumerator[expr] expands out products and powers that appear in
the numerator of expr.
ExpandDenominator[expr] expands out products and powers that appear
as denominators in expr.

6. Trigonometric Function Manipulation


TrigExpand[expr] expands out trigonometric functions in expr.
TrigFactor[expr] factors trigonometric functions in expr.
TrigFactorList[expr] factors trigonometric functions in expr, yielding a
list of lists containing trigonometric monomials and exponents.
TrigReduce[expr] rewrites products and powers of trigonometric functions
in expr in terms of trigonometric functions with combined arguments.
TrigToExp[expr] converts trigonometric functions in expr to exponentials.
ExpToTrig[expr] converts exponentials in expr to trigonometric functions.

7. Root and Radical Manipulation


RootReduce[expr] attempts to reduce expr to a single Root object.
ToRadicals[expr] attempts to express all Root objects in expr in terms of
radicals.

8. Other Algebraic Manipulation

Bruce E. Shapiro
Woods Hole, 1998

Page 32

Medical Informations: A Course for Health Professionals

Mathematical Modeling

ExcludedForms is an option for FullSimplify which can be set to a list


of patterns for expressions that should not be touched if they are encountered at
intermediate steps in the operation of FullSimplify.
ComplexityFunction is an option for Simplify and FullSimplify
which gives a function to rank the complexity of different forms of an
expression.
TimeConstraint is an option for Simplify and FullSimplify which
gives the maximum number of seconds for which to try any particular
transformation on any subpart of an expression.

C. Equation Solving
lhs == rhs returns True if lhs and rhs are identical.
DSolve[eqn, y, x] solves a differential equation for the function y, with
independent variable x.
DSolve[{eq1, eq1, ...}, {y1, y2, ...}, x] solves a list of differential equations.
DSolve[eqn, y, {x1, x2, ...}] solves a partial differential
equation.
Eliminate[eqns, vars] eliminates variables between a set of simultaneous
equations.
InverseFunction[f] represents the inverse of the function f, defined so that
InverseFunction[f][y] gives the value of x for which f[x] is equal to y.
LogicalExpand[expr] expands out expressions containing logical connectives
such as && and ||.
Reduce[eqns, vars] simplifies the equations eqns, attempting to solve for the
variables vars. The equations generated by Reduce are equivalent to eqns, and
contain all the possible solutions.
Reduce[eqns, vars, elims] simplifies the equations, trying to eliminate the
variables elims.
Root[f, k] represents the ka root of the polynomial equation f[x] == 0.
Solve[eqns, vars] attempts to solve an equation or set of equations for the
variables vars.
Solve[eqns, vars, elims] attempts to solve the equations for vars, eliminating
the variables elims.
SolveAlways[eqns, vars] gives the values of parameters that make the
equations eqns valid for all values of the variables vars.

D. Calculus
1. Derivatives
D[f, x] gives the partial derivative
Bruce E. Shapiro
Woods Hole, 1998

Page 33

Medical Informations: A Course for Health Professionals

Mathematical Modeling

D[f, {x,n}] gives the multiple derivative


D[f, a, a, ] gives multiple Partial derivative
NonConstants is an option for D which gives a list of objects to be taken to
depend implicitly on the differentiation variables.
Dt[f, x] gives the total derivative dfdx
Dt[f] gives the total differential df
Dt[f, {x,n}] gives the nth derivative derivative
Dt[f, a, a, ] gives a multiple derivate wtt multiple variables.
Constants is an option for Dt which gives a list of objects to be taken as
constants.
f' represents the derivative of a function f of one argument.
Derivative[n1, n2, ][f] is the general form, representing a function
obtained from f by differentiating n1 times with respect to the first argument, n2
times with respect to the second argument, and so on.

2. Integration. See Section I.D.


PrincipalValue is an option for Integrate that specifies whether the
Cauchy principal value should be found for a definite integral.
Assumptions is an option for Integrate and other functions that
specifies what assumptions be made about relations between parameters.
GenerateConditions is an option for Integrate that specifies whether
explicit conditions on parameters should be generated in the results of definite
integrals.

3. Limits, Residues, and Series


Limit[expr, x->a] finds the limiting value of expr when x approaches a.
Residue[expr, {x, a}] finds the residue of expr at the point a.
Series[f, {x, a, n}] generates a power series expansion for f about the
n
point a to order (x-a) .
Series[f, {x, x0, nx}, {y, y0, ny}] successively finds series expansions with
respect to y, then x.
Normal[expr] converts expr to a normal expression, from a variety of special
forms.
SeriesCoefficient[series, n] finds the coefficient of the aa order term
in a power series.
InverseSeries[s, x] takes the series s generated by Series, and gives a
series for the inverse of the function represented by s.
SeriesCoefficient[series, {n1, n2, ...}] finds a coefficient in a
multivariate series.
Bruce E. Shapiro
Woods Hole, 1998

Page 34

Medical Informations: A Course for Health Professionals

Mathematical Modeling

ComposeSeries[s1, s2, ] composes several power series, i.e., effectively


replaces the variable in s1 by s2 and so on.
SeriesData[x, x0, {a0, a1, ...J}, nmin, nmax, den] represents a power
series in the variable x about the point x0. The a are the coefficients in the power
series. The powers of (x-x0) that appear are nmin/den, (nmin+1)/den, ,
nmax/den.
n

O[x]^n represents a term of order x .


O[x]^n is generated to represent omitted higher-order terms in power series.
n

O[x, a]^n represents a term of order (x-a) .

4. Polynomial Manipulation
(a) Existence
PolynomialQ[expr, var] yields True if expr is a polynomial in var,
and yields False otherwise.
PolynomialQ[expr, {v1, v2, ...}] tests whether expr is a polynomial in
the vi.

(b) Variables and Coefficients


Variables[poly] gives a list of all independent variables in a polynomial.
CoefficientList[poly, var] gives a list of coefficients of powers of
var in poly, starting with power 0.
CoefficientList[poly, {v1, v2,...}] gives an array of coefficients.
Modulus->n is an option that can be given in certain algebraic functions to
specify that integers should be treated modulo n.

(c) Polynomial Algebra


PolynomialMod[poly, m] gives the polynomial poly reduced modulo
m.
PolynomialMod[poly, {m1, m2, ...}] reduces modulo all of the mi.
PolynomialQuotient[p, q, x] gives the quotient of p and q, treated
as polynomials in x, with any remainder dropped.
PolynomialRemainder[p, q, x] gives the remainder from dividing p
by q, treated as polynomials in x.
PolynomialGCD[p1, p2, ] gives the greatest common divisor of the
polynomials pi.
PolynomialGCD[p1, p2, , Modulus->p] evaluates the GCD
modulo the prime p.
PolynomialLCM[p1, p2, ] gives the least common multiple of the
polynomials pi..
Bruce E. Shapiro
Woods Hole, 1998

Page 35

Medical Informations: A Course for Health Professionals

Mathematical Modeling

PolynomialLCM[p1, p2, , Modulus->p] evaluates the LCM


modulo the prime p.
PolynomialReduce[poly,{p1, p2, ...}, {x1, x2, ...}] yields a list
representing a reduction of poly in terms of the xi.
Resultant[p1, p2, var] computes the resultant of the polynomials p1,
p2 with respect to the variable var.
Resultant[p1, p2,, Modulus->p] computes the resultant modulo the
prime p.
Decompose[poly, x] decomposes a polynomial, if possible, into a
composition of simpler polynomials.
Root[f, k] represents the kth root of the polynomial equation f[x] == 0.
RootSum[f, form] represents the sum of form[x] for all x that satisfy the
polynomial equation f[x] == 0.
RootReduce[expr] attempts to reduce expr to a single Root object.
ToRadicals[expr] attempts to express all Root objects in expr in terms
of radicals.

(d) Polynomial Factoring


Factor[poly] factors a polynomial over the integers.
Factor[poly, Modulus->p] factors a polynomial modulo a prime p.
Factor[poly, Extension->{a1, a2, ...}] factors a polynomial allowing
coefficients that are rational combinations of the algebraic numbers a.
FactorSquareFree[poly] pulls out any multiple factors in a
polynomial.
FactorTerms[poly] pulls out any overall numerical factor in poly.
FactorTerms[poly, x] pulls out any overall factor in poly that does not
depend on x.
FactorList[poly] gives a list of the factors of a polynomial, together
with their exponents.
FactorSquareFreeList[poly] gives a list of square-free factors of a
polynomial, together with their exponents.
FactorTermsList[poly, {x1, x2, ...}] gives a list of factors of poly.
The first element in the list is the overall numerical factor. The second
element is a factor that does not depend on any of the xi. Subsequent
elements are factors which depend on progressively more of the xi.
GaussianIntegers is an option for FactorInteger, PrimeQ,
Factor and related functions which specifies whether factorization should
be done over Gaussian integers.

Bruce E. Shapiro
Woods Hole, 1998

Page 36

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Extension is an option for Factor, PolynomialGCD and related


functions which specifies what algebraic numbers to allow in the coefficients
of resulting polynomials.

(e) Special Polynomials


Cyclotomic[n, x] gives the cyclotomic polynomial of order n in x.
GroebnerBasis[{p1, p2, ...}, {x1, x2, ...}] gives a list of polynomials
that form a Grbner basis for the set of polynomials pi.
GroebnerBasis[{p1, p2, ...}, {x1, x2, ...}, {y1, y2, ...}] finds a Grbner
basis in which the yis have been eliminated.

III. Mathematical Functions


A. Basic Arithmetic
Plus[x, y] or x + y + z represents a sum of terms.
Subtract [x, y] or x - y is equivalent to x + (-1 * y).
Minus[x] or -x is the arithmetic negation of x.
Times[x, ...] or x*y*z, xyz or x y z represents a product of terms.
Divide[x, y] or x/y is equivalent to x y^-1.
Power[x, y] or x^y gives x to the power y.

B. Mathematical Constants: Pi or p, E, Degree, GoldenRatio,


EulerGamma, Catalan, I, Infinity

C. Numerical Functions
Abs[z] gives the absolute value of the real or complex number z.
Sign[x] gives -1, 0 or 1 depending on whether x is negative, zero, or positive.
Round[x] gives the integer closest to x.
IntegerPart[x] gives the integer part of x.
Chop[expr] replaces approximate real numbers in expr that are close to zero by the
exact integer 0.
Mod[m, n] gives the remainder on division of m by n.
Quotient[n, m] gives the integer quotient of n and m.
GCD[n1, n2, ] gives the greatest common divisor of the integers ni.
LCM[n1, n2, ] gives the least common multiple of the integers ni
PrimePi[x] gives the number of primes less than or equal to x..
PowerMod[a, b, n] gives ab mod n
Divisors[n] gives a list of the integers that divide n.
Max, Min : See I.F.3. Data Manipulation
Bruce E. Shapiro
Woods Hole, 1998

Page 37

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Re, Im, Conjugate, Arg: See I.H. Complex Numbers

D. Random Numbers
Random[ ] gives a uniformly distributed pseudorandom Real in the range 0 to 1.
Random[type, range] gives a pseudorandom number of the specified type, lying
in the specified range. Possible types are: Integer, Real and Complex. The
default range is 0 to 1. You can give the range {min, max} explicitly; a range
specification of max is equivalent to {0, max}. Random uses the Wolfram rule 30
cellular automaton generator for integers. It uses a Marsaglia-Zaman subtract-withborrow generator for real numbers.
SeedRandom[n] resets the pseudorandom number generator, using the integer n
as a seed.
SeedRandom[ ] resets the generator, using as a seed the time of day.

E. Elementary Functions
Log[z] gives the natural logarithm of z (logarithm to base a).
Log[b, z] gives the logarithm to base b.
Exp[z] is the exponential function.
Power[x, y] or x^y gives x to the power y.
Sqrt[z] gives the square root of z.
Sin[z], Cos[z], Tan[z], Csc[z], Sec[z], Cot[z]
ArcSin[z], ArcCos[x],ArcTan[z], ArcTan[y,x] = tan-1 (y/x),
ArcCsc[z], ArcSec[z], ArcCot[z]
Sinh[z], Cosh[z], Tanh[z], Sech[z], Csch[z], Coth[z]
ArcSinh[z], ArcCosh[z], ArcTanh[z], ArcSech[z],
ArcCsch[z], ArcCoth[z]

F. Factorial-Based Functions
n! gives the factorial of n. = n(n-1)(n-2)...1
n!! gives the double factorial of n. = n(n-2)(n-4)(n-6)...l
n
Binomial[n, m] gives the binomial coefficient =n!/(n!(n-m)!)
m
Multinomial[n1, n2, ] gives the multinomial coefficient
(n1+n2+..)!/(n1!n2!...)
Pochhammer[a, n] gives the Pochhammer symbol (a)n
Gamma[z] is the Euler gamma function [z]
Gamma[a, z] is the incomplete gamma function [a, z]
Bruce E. Shapiro
Woods Hole, 1998

Page 38

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Gamma[a, z1, x2] is the generalized incomplete gamma function [a,z1]-[a,z2]


GammaRegularized[a, z] is the regularized incomplete gamma function Q(a,z)
InverseGammaRegularized[a, s] gives the inverse of the regularized
incomplete gamma function.
LogGamma[z] gives the logarithm of the gamma function log(z)
Beta[a, b] gives the Euler beta function B[a,b]
Beta[z, a, b] gives the incomplete beta function
BetaRegularized[z, a, b] gives the regularized incomplete beta function
Iz(a,b)
InverseBetaRegularized[s, a, b] gives the inverse of the regularized
incomplete beta function.
PolyGamma[z] gives the digamma function (x)
PolyGamma[n, z] gives the nth derivative of the digamma function (n) (x)

G. Combinatorial Functions
BernoulliB[n] gives the Bernoulli number Bn .
BernoulliB[n, x] gives the Bernoulli polynomial Bn (x)
ClebschGordan[...] gives the Clebsch-Gordan coefficient from Quantum
Mechanics
EulerE[n, x] gives the Euler polynomial En (x)
Fibonacci[n] gives the Fibonacci number Fn .
Fibonacci[n, x] gives the Fibonacci polynomial Fn (x)
PartitionsP[n] gives the number a of unrestricted partitions of the integer a.
PartitionsQ[n] gives the number a of partitions of the integer a into distinct
parts.
SixJSymbol[...] gives the values of the Racah 6-j symbol from Quantum
Mechanics
Signature[list] gives the signature of the permutation needed to place the
elements of list in canonical order.
StirlingS1[n, m] gives the Stirling number of the first kind Sn( m )
StirlingS2[n, m] gives the Stirling number of the second kind
ThreeJSymbol[...] gives the values of the Wigner 3-j symbol from Quantum
Mechanics

Bruce E. Shapiro
Woods Hole, 1998

Page 39

Medical Informations: A Course for Health Professionals

Mathematical Modeling

H. Functions from Number Theory


ArithmeticGeometricMean[a, b] gives the arithmetic-geometric mean of a
and b.
Divisors[n] gives a list of the integers that divide n.
DivisorSigma[k, n] gives the divisor function k (n)
EulerPhi[n] gives the Euler totient function (x).
ExtendedGCD[n, m] gives the extended greatest common divisor of the integers
n and m.
FactorInteger[n] gives a list of the prime factors of the integer n, together
with their exponents.
GCD[n1, n2, ] gives the greatest common divisor of the integers ni.
IntegerDigits[n] gives a list of the decimal digits in the integer n.
n
JacobiSymbol[n, m] gives the Jacobi symbol
m
LCM[n1, n2, ] gives the least common multiple of the integers ni
MoebiusMu[n] gives the Mbius function (x)
Mod[m, n] gives the remainder on division of m by n.
PowerMod[a, b, n] gives ab mod n
For negative b, PowerMod[a, b, n] gives modular inverses.
Prime[n] gives the nth prime number.
PrimePi[x] gives the number of primes less than or equal to x..
PrimeQ[expr] yields True if expr is a prime number, and yields False
otherwise.
Quotient[n, m] gives the integer quotient of n and m.

I. Zeta Function
LerchPhi[z, s, a] gives the Lerch transcendent (z,s,a)
PolyLog[n, z] gives the polylogarithm function Lin (z)
RiemannSiegelTheta[t] gives the Riemann-Siegel function (t)
RiemannSiegelZ[t] gives the Riemann-Siegel function Z[t]
StieltjesGamma[n] gives the Stieltjes constant n
Zeta[s] gives the Riemann zeta function (s).
Zeta[s, a] gives the generalized Riemann zeta function (s,a).
Bruce E. Shapiro
Woods Hole, 1998

Page 40

Medical Informations: A Course for Health Professionals

Mathematical Modeling

J. Hypergeometric and Related Functions


AiryAi[z] gives the Airy function Ai(z)
AiryAiPrime[z] gives the derivative of the Airy function Ai(z)
AiryBi[z] gives the Airy function Bi(z)
AiryBiPrime[z] gives the derivative of the Airy function Bi(z)
BesselJ[n, z] gives the Bessel function of the first kind Jn (z)
BesselK[n, z] gives the modified Bessel function of the second kind Kn (z)
BesselI[n, z] gives the modified Bessel function of the first kind In (z)
BesselY[n, z] gives the Bessel function of the second kind Yn (z)
CoshIntegral[z] gives the hyperbolic cosine integral Chi(z)
CosIntegral[z] gives the cosine integral function Ci(z)
Erf[z] gives the error function erf(z)
Erf[z1, z2] gives the generalized error function erf(z2)-erf(z1)
Erfc[z] gives the complementary error function erfc(z)
Erfi[z] gives the imaginary error function erf(iz)/i
ExpIntegralE[n, z] gives the exponential integral function En (z)
ExpIntegralEi[z] gives the exponential integral function Ei(z)
FresnelC[z] gives the Fresnel integral C(z)
FresnelS[z] gives the Fresnel integral S(z)
Hypergeometric1F1[a, b, z] is the Kummer confluent hypergeometric
function 1 F1 (a; b; z)
Hypergeometric1F1Regularized[a, b, z] is the regularized confluent
hypergeometric function 1 F1 (a; b; z)/(b)
Hypergeometric2F1[a, b, c, z] is the hypergeometric function 2 F1 (a; b; z)
Hypergeometric2F1Regularized[a, b, c, z] is the regularized
hypergeometric function 2 F1 (a; b; z)/(c)
Hypergeometric0F1[a, z] is the confluent hypergeometric function o F1 (;a;z)
Hypergeometric0F1Regularized[a, z] is the regularized confluent
hypergeometric function o F1 (;a;z)/(a)
HypergeometricPFQ[{a1 , ....,ap }, {b1 , ..., bp }, z] is the generalized
hypergeometric function pFq(a; b; z)
HypergeometricPFQRegularized[{a1 , ....,ap }, {b1 , ..., bp }, z] is the
regularized generalized hypergeometric function pFq(a; b; z)/((b1 )...(bq ))
HypergeometricU[a, b, z] is the confluent hypergeometric function U(a,b,z)

Bruce E. Shapiro
Woods Hole, 1998

Page 41

Medical Informations: A Course for Health Professionals

Mathematical Modeling

MeijerG[{{a1 ,...,an },{an+1,...,ap }},{{b1 ,...,bm },{bm+1 ,...,bq }}, z] is the Meijer G
a1 ,K,a p

function Gpqmn z
b1 ,K,bq
LogIntegral[z] is the logarithmic integral function Li(z)
SinIntegral[z] gives the sine integral function Si(z)
SinhIntegral[z] gives the hyperbolic sine integral function Shi(z)

K. Orthogonal Polynomials
ChebyshevT[n, x] gives the Chebyshev polynomial of the first kind Tn (x)
ChebyshevU[n, x] gives the Chebyshev polynomial of the second kind Un (x)
GegenbauerC[n, m, x] gives the Gegenbauer polynomial Cn( m) (x)
GegenbauerC[n, x] gives the renormalized form Cn( m) (x) /m
HermiteH[n, x] gives the Hermite polynomial Hn (x)
LaguerreL[n, x] gives the Laguerre polynomial Ln (x)
LaguerreL[n, a, x] gives the generalized Laguerre polynomial Ln a(x)
JacobiP[n, a, b, x] gives the Jacobi polynomial Pn( a, b) (x)
LegendreP[n, x] gives the Legendre polynomial Pn (x)
LegendreP[n, m, x] gives the associated Legendre polynomial Pnm (x)
SphericalHarmonicY[l, m, q, f] gives the spherical harmonic Yl m ( , )

L. Elliptic Functions
DedekindEta[t] gives the Dedekind eta modular elliptic function ( )
EllipticExp[u, aa, ba] is the inverse for EllipticLog.
EllipticTheta[a, u, q] gives the theta function a(u,q)
EllipticThetaPrime[a, u, q] gives the derivative with respect to a of the
theta function
InverseEllipticNomeQ[q] gives the parameter m corresponding to the nome
q in an elliptic function.
InverseJacobiSN[v, m], InverseJacobiCN[v, m], etc. give the inverse
Jacobi elliptic functions. There are a total of twelve functions, with names of the
form InverseJacobiPQ, where P and Q can be any distinct pair of the letters S,
C, D and N.
JacobiAmplitude[u, m] gives the amplitude am(u|m) for Jacobi elliptic
functions.
KleinInvariantJ[t] gives the Klein invariant modular elliptic function J()

Bruce E. Shapiro
Woods Hole, 1998

Page 42

Medical Informations: A Course for Health Professionals

Mathematical Modeling

InverseWeierstrassP[p, {g2 , g3 }] gives a value of u for which the


Weierstrass function (u; g2 ,g3 ) is equal to p
JacobiSN[u, m], JacobiCN[u, m], etc. give the Jacobi elliptic functions
sn(u|m), cn(u|m), etc. There are a total of twelve functions, with the names of the
form JacobiPQ, where P and Q can be any distinct pair of the letters S, C, D and
N.
ModularLambda[t] gives the modular lambda elliptic function ( )
WeierstrassHalfPeriods[{g2 , g3 }] gives the half-periods {, }for
Weierstrass elliptic functions corresponding to the invariants {g2 , g3 }.
WeierstrassInvariants[{, }] gives the invariants{g2 , g3 } for
Weierstrass elliptic functions corresponding to the half-periods , .
WeierstrassP[u, {g2 , g3 }] gives the Weierstrass elliptic function(u; g2 ,g3 )
WeierstrassPPrime[u, {g2 , g3 }] gives the derivative of the Weierstrass
elliptic function (u; g2 ,g3 )
WeierstrassSigma[u, {g2 , g3 }] gives the Weierstrass sigma (u; g2 , g3 )
WeierstrassZeta[u, {g2 , g3 }] gives the Weierstrass zeta (u; g2 , g3 )

M. Elliptic Integrals
EllipticE[m] gives the complete elliptic integral E(m)
EllipticE[f, m] gives the elliptic integral of the second kind E(,m)
EllipticF[f, m] gives the elliptic integral of the first kind F(|m)
EllipticK[m] gives the complete elliptic integral of the first kind K(m)
EllipticLog[{x, y},{a, b} ] gives the generalized logarithm associated with the
elliptic curve y2=x3 +ax 2 +bx
EllipticNomeQ[m] gives the nome q corresponding to the parameter m in an
elliptic function.
EllipticPi[n, m] gives the complete elliptic integral of the third kind (n|m)
EllipticPi[n, f, m] gives the incomplete elliptic integral (n; |m)
JacobiZeta[f, m] gives the Jacobi zeta function Z(|m)

N. Mathieu Functions
MathieuC[a, q, z] gives the even Mathieu function with characteristic value a
and parameter q.
MathieuS[a, q, z] gives the odd Mathieu function with characteristic value a
and parameter q.
MathieuCPrime[a, q, z] gives the derivative with respect to z of the even
Mathieu function with characteristic value a and parameter q.
MathieuSPrime[a, q, z] gives the derivative with respect to z of the odd
Mathieu function with characteristic value a and parameter q.

Bruce E. Shapiro
Woods Hole, 1998

Page 43

Medical Informations: A Course for Health Professionals

Mathematical Modeling

MathieuCharacteristicA[r, q] gives the characteristic value a for even


Mathieu functions with characteristic exponent r and parameter q.
MathieuCharacteristicB[r, q] gives the characteristic value a for odd
Mathieu functions with characteristic exponent r and parameter q.
MathieuCharacteristicExponent[a, q] gives the characteristic exponent
a for Mathieu functions with characteristic value a and parameter q.

IV. Lists
A. Construction
{a, b, ...} or List[a, b, ...] is a list of elements.
Array[f, n] generates a list of length n, with elements f[i].
Array[f, {n1 , n2 , ...} ] generates an n1 n2 ... array of nested lists, with
elements f[i1 , i2 , ].
Array[f, dims, origin] generates a list using the specified index origin (default
1).
Array[f, dims, origin, h] uses head h, rather than List, for each level of the
array.
Range[imax] generates the list {1, 2, , imax}.
Range[imin, imax] generates the list {imin, , imax}.
Range[imin, imax, di] uses step di.
Table[expr, {i}] generates a list of i copies of expr.
Table[expr, {i, imax}] generates a list of the values of expr when i runs from 1
to imax.
Table[expr, {i, imin, imax}] starts with i = imin.
Table[expr, {i, imin, imax, di}] uses steps di.
Table[expr, {i, imin, imax}, {j, jmin, jmax}, ] gives a nested list. The
list associated with i is outermost.

B. Element Extraction
expr[[i]] or Part[expr, i] gives the ith part of expr.
expr[[-i]] counts from the end.
expr[[0]] gives the head of expr.
expr[[i, j, ]] or Part[expr, i, j, ] is equivalent to expr[[i]] [[j]]

expr[[ {i1 , i2 , ...} ]] gives a list of the parts i1 , i2 , of expr.


Cases[{e1 , e2 , ...}, pattern] gives a list of the ei that match the pattern.
Cases[{e1 , e2 , ...}, pattern -> rhs] gives a list of the values of rhs
corresponding to the ei that match the pattern.
Bruce E. Shapiro
Woods Hole, 1998

Page 44

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Cases[expr, pattern, levspec] gives a list of all parts of expr on levels specified
by levspec which match the pattern.
Cases[expr, pattern -> rhs, levspec] gives the values of rhs which match the
pattern. Drop[list, n] gives list with its first n elements dropped.
Drop[list, -n] gives list with its last n elements dropped.
Drop[list, {n}] gives list with its nth element dropped.
Drop[list, {m, n}] gives list with elements m through n dropped.
Extract[expr, list] extracts the part of expr at the position specified by list.
Extract[expr, {list1, list2, ...}] extracts a list of parts of expr.
Extract[expr, , h] extracts parts of expr, wrapping each of them with head h
before evaluation.
First[expr] gives the first element in expr.
Last[expr] gives the last element in expr.
Head[expr] gives the head of expr.
Rest[expr] gives expr with the first element removed.
Select[list, crit] picks out all elements ei of list for which crit[ei] is True.
Select[list, crit, n] picks out the first n elements for which crit[ei] is True.
Take[list, n] gives the first n elements of list.
Take[list, -n] gives the last n elements of list.
Take[list, {m, n}] gives elements m through n of list.

C. List Testing
Count[list, pattern] gives the number of elements in list that match pattern.
Count[expr, pattern, levelspec] gives the total number of subexpressions
matching pattern that appear at the levels in expr specified by levelspec.
Depth[expr] gives the maximum number of indices needed to specify any part of
expr, plus one.
Dimensions[expr] gives a list of the dimensions of expr.
Dimensions[expr, n] gives a list of the dimensions of expr down to level n.
FreeQ[expr, form] yields True if no subexpression in expr matches form, and
yields False otherwise.
FreeQ[expr, form, levelspec] tests only those parts of expr on levels specified
by levelspec.
Length[expr] gives the number of elements in expr.
MatrixQ[expr] gives True if expr is a list of lists that can represent a matrix, and
gives False otherwise.
MatrixQ[expr, test] gives True only if test yields True when applied to each
of the matrix elements in expr.
Bruce E. Shapiro
Woods Hole, 1998

Page 45

Medical Informations: A Course for Health Professionals

Mathematical Modeling

MemberQ[list, form] returns True if an element of list matches form, and


False otherwise.
MemberQ[list, form, levelspec] tests all parts of list specified by levelspec.
Position[expr, pattern] gives a list of the positions at which objects matching
pattern appear in expr.
Position[expr, pattern, levspec] finds only objects that appear on levels
specified by levspec.
TensorRank[expr] gives the depth to which expr is a full array, with all the parts
at a particular level being lists of the same length.
VectorQ[expr] gives True if expr is a list, none of whose elements are
themselves lists, and gives False otherwise.
VectorQ[expr, test] gives True only if test yields True when applied to each
of the elements in expr.

D. List Operations
Append[expr, elem] gives expr with elem appended.
Complement[eall, a, b, ] gives the elements in eall which are not in any of
the a, b, ...
Delete[expr, n] deletes the element at position n in expr. If n is negative, the
position is counted from the end.
DeleteCases[expr, pattern] removes all elements of expr which match pattern.
DeleteCases[expr, pattern, levspec] removes all parts of expr on levels
specified by levspec which match pattern.
Insert[list, elem, n] inserts elem at position n in list. If n is negative, the
position is counted from the end.
Insert[expr, elem, {i,j,...}] inserts elem at position {i, j, } in expr.
Intersection[a,b, ] gives a sorted list of the elements common to all the
lists
Join[a, b, ] concatenates lists together. Join can be used on any set of
expressions that have the same head.
Prepend[expr, elem] gives expr with elem prepended.
ReplacePart[expr, new, n] yields an expression in which the nth part of expr
is replaced by new.
Reverse[expr] reverses the order of the elements in expr.
Sort[list] sorts the elements of list into canonical order.
RotateLeft[expr, n] cycles the elements in expr n positions to the left.
RotateLeft[expr] cycles one position to the left.
RotateRight[expr, n] cycles the elements in expr n positions to the right.
RotateRight[expr] cycles one position to the right.
Bruce E. Shapiro
Woods Hole, 1998

Page 46

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Sort[list, p] sorts using the ordering function p.


Union[a, b, ] gives a sorted list of all the distinct elements that appear in any
of the a.
Union[list] gives a sorted version of a list, in which all duplicated elements have
been dropped.

E. Structure Manipulations
Flatten[list] flattens out nested lists.
Flatten[list, n] flattens to level n.
Flatten[list, n, h] flattens subexpressions with head h.
FlattenAt[list, n] flattens out a sublist that appears as the nth element of list. If
n is negative, the position is counted from the end.
Order[a, b] gives 1 if a is before b in canonical order, and -1 if a is after b in
canonical order. It gives 0 if a is identical to b.
OrderedQ[h[a, b, ]] gives True if the a, b, ... are in canonical order, and
False otherwise.
Partition[list, n] partitions list into non-overlapping sublists of length n.
Partition[list, n, d] generates sublists with offset d.
Permutations[list] generates a list of all possible permutations of the elements
in list.
Sequence[a, b, ] represents a sequence of arguments to be spliced
automatically into any function.
Signature[list] gives the signature of the permutation needed to place the
elements of list in canonical order.
Split[list] splits list into sublists consisting of runs of identical elements.
Split[list, test] treats pairs of adjacent elements as identical whenever applying
the function test to them yields True.
Thread[f[args]] "threads" f over any lists that appear in args.
Thread[f[args], h] threads f over any objects with head h that appear in args.
Thread[f[args], h, n] threads f over objects with head h that appear in the first
n args.
Thread[f[args], h, -n] threads over the last n args.
Thread[f[args], h, am, na] threads over arguments m through n.

Bruce E. Shapiro
Woods Hole, 1998

Page 47

Medical Informations: A Course for Health Professionals

Mathematical Modeling

V. Graphics and Sound


A. Data Plots
ListPlot[{a, b, c, ...}] plots a list of values. The x coordinates for each point are
taken to be 1, 2, .
ListPlot[{a, b}, {c, d}, {e, f}, ...] plots a list of values with specified x and y
coordinates.
ListPlot3D[array] generates a three-dimensional plot of a surface representing
an array of height values.
ListPlot3D[array, shades] generates a plot with each element of the surface
shaded according to the specification in shades.
ListContourPlot[array] generates a contour plot from an array of height
values.
ListDensityPlot[array] generates a density plot from an array of height
values.

B. Function Plots
Plot[f, {x, xmin, xmax}] generates a plot of f as a function of x from xmin to
xmax.
Plot[{f1 , f2 , ...}, {x, xmin, xmax}] plots several functions fi.
Plot3D[f, {x, xmin, xmax}, {y, ymin, ymax}] generates a three-dimensional
plot of f as a function of x and y.
ContourPlot[f, {x, xmin, xmax}, {y, ymin, ymax}] generates a contour
plot of f as a function of x and y.
DensityPlot[f, {x, xmin, xmax}, {y, ymin, ymax}] makes a density plot of
f as a function of x and y.

C. Parametric Plots
ParametricPlot[{fx, fy}, {t, tmin, tmax} ] produces a
parametric plot with x and y coordinates fx and fy generated as a function of t.
ParametricPlot3D[{fx, fy, fz}, {t, tmin, tmax} ] produces a threedimensional space curve parametrized by a variable t which runs from tmin to tmax.

D. Sound Generation
Play[f, {t, tmin, tmax}] plays a sound whose amplitude is given by f as a
function of time t in seconds between tmin and tmax.
ListPlay[{a, b, c, ...}] plays a sound whose amplitude is given by the sequence
of levels a, b, ....

E. Combinations of Plots
Show[graphics, options] displays two- and three-dimensional graphics, using the
options specified.
Bruce E. Shapiro
Woods Hole, 1998

Page 48

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Show[p1, p2, ] shows several plots combined.


GraphicsArray[{a, b, }] represents a row of graphics objects.
GraphicsArray[{{a, b, }, }] represents a two-dimensional array of
graphics objects.

F. Options.
option -> value sets the option to the desired values. Options are specified in
a list as the last element of the Plot[...] directive.
AspectRatio is an option for Show and related functions which specifies the
ratio of height to width for a plot.
AxesLabel -> None specifies that no labels should be given.
AxesLabel -> label specifies a label for the y axis of a two-dimensional plot, and
the z axis of a three-dimensional plot.
AxesLabel -> {xlabel, ylabel, } specifies labels for different axes
Axes -> True draws all axes.
Axes -> False draws no axes.
Axes -> {False, True} draws a y axis but no x axis in two dimensions.
AxesOrigin -> {x, y} specifies that the axes should cross at the point {x, y}.
AxesOrigin -> Automatic uses an internal algorithm to determine where the
axes should cross
AxesStyle -> style specifies that all axes are to be generated with the specified
graphics directive, or list of graphics directives. AxesStyle -> {{xstyle},
{ystyle}, } specifies that axes should use graphics directives xstyle, . The
styles must be enclosed in lists, perhaps of length one. Styles can be specified
using graphics directives such as Dashing, Hue and Thickness.
The default color of axes is specified by the option DefaultColor.
Epilog is an option for graphics functions which gives a list of graphics primitives
to be rendered after the main part of the graphics is rendered.
Frame is an option for two-dimensional graphics functions which specifies whether
a frame should be drawn around the plot. Frame -> True by default draws a
frame with tick marks. If Ticks -> Automatic, setting Frame -> True
suppresses tick marks on axes.
FrameLabel is an option for two-dimensional graphics functions that specifies
labels to be placed on the edges of a frame around a plot. FrameLabel -> None
specifies that no labels should be given. FrameLabel -> {xmlabel, ymlabel}
specifies labels for the bottom and left-hand edges of the frame.
FrameLabel -> {xmlabel, ymlabel, xplabel, yplabel } specifies labels for each
of the edges of the frame, ordered clockwise starting from the bottom edge.
FrameStyle is an option for two-dimensional graphics functions that specifies
how the edges of a frame should be rendered.
FrameTicks is an option for two-dimensional graphics functions that specifies
tick marks for the edges of a frame. Can be None, Automatica, {xgrid, ygrid}

Bruce E. Shapiro
Woods Hole, 1998

Page 49

Medical Informations: A Course for Health Professionals

Mathematical Modeling

GraphicsSpacing is an option for GraphicsArray which specifies the


spacing between elements in the array.
GridLines is an option for two-dimensional graphics functions that specifies grid
lines.
PlotJoined is an option for ListPlot that specifies whether the points plotted
should be joined by a line.
PlotLabel is an option for graphics functions that specifies an overall label for a
plot. PlotLabel->None is default; PlotLabel->value to set.
PlotRange is an option for graphics functions that specifies what points to
include in a plot. Form is PlotRange->All, PlotRange->Automatic,
PlotRange->{xmin, xmax}, PlotRange->{{xmin,
xmax},{ymin,ymax}}
PlotStyle is an option for Plot and ListPlot that specifies the style of lines
or points to be plotted. PlotStyle -> style specifies that all lines or points are to
be generated with the specified graphics directive, or list of graphics directives.
Prolog is an option for graphics functions which gives a list of graphics primitives
to be rendered before the main part of the graphics is rendered.
Ticks->None no tickmarks
Ticks->Automatic no tickmarks
Ticks->{xtick, ytick} specifies tickmarks; xtick and ytick are a list of
values for each axis

G. Primitives
AbsoluteDashing[{ a,b, }] is a graphics directive which specifies that
lines which follow are to be drawn dashed, with successive segments having
absolute lengths a, b (repeated cyclically).
AbsolutePointSize[d] is a graphics directive which specifies that points
which follow are to be shown if possible as circular regions with absolute diameter
d.
AbsoluteThickness[d] is a graphics directive which specifies that lines which
follow are to be drawn with absolute thickness d.
Circle[{x, y}, r] is a two-dimensional graphics primitive that represents a
circle of radius r centered at the point x, y.
Circle[{x, y},{a, b}] yields an ellipse with semi-axes a and b.
Circle[{x, y}, r, {1 , 2 }] represents a circular arc.
Cuboid[{xmin, ymin, zmin}] is a three-dimensional graphics primitive that
represents a unit cuboid, oriented parallel to the axes.
CMYKColor[cyan, magenta, yellow, black] is a graphics directive which
specifies that graphical objects which follow are to be displayed in the color given.
Cuboid[{xmin, ymin, zmin}, {xmax, ymax, zmax}] specifies a cuboid by
giving the coordinates of opposite corners.
Bruce E. Shapiro
Woods Hole, 1998

Page 50

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Dashing[{a, b, ...}] is a two-dimensional graphics directive which specifies that


lines which follow are to be drawn dashed, with successive segments of lengths a, b,
(repeated cyclically). The a, b, ... is given as a fraction of the total width of the
graph.
Disk[{x, y}, r] is a two-dimensional graphics primitive that represents a filled
disk of radius r centered at the point x, y.
Disk{x, y},{a, b}] yields an elliptical disk with semi-axes a and a.
Disk[{x, y}, r, {1 , 2 }] represents a segment of a disk.
EdgeForm[g] is a three-dimensional graphics directive which specifies that edges
of polygons are to be drawn using the graphics directive or list of graphics directives
g.
FaceForm[gf, gb] is a three-dimensional graphics directive which specifies that
the front faces of polygons are to be drawn with the graphics primitive gf, and the
back faces with gb.
GrayLevel[level] is a graphics directive which specifies the gray-level intensity
with which graphical objects that follow should be displayed.
Hue[h] is a graphics directive which specifies that graphical objects which follow
are to be displayed, if possible, in a color corresponding to hue h.
Hue[h, s, b] specifies colors in terms of hue, saturation and brightness.
Offset[{dx, dy}, position] gives the position of a graphical object obtained by
starting at the specified position and then moving by absolute offset adx, dya.
PointSize[d] is a graphics directive which specifies that points which follow are
to be shown if possible as circular regions with diameter d. The diameter d is given
as a fraction of the total width of the graph.
Polygon[{p1, p2, ...}] is a graphics primitive that represents a filled polygon.
Each pi is {x, y} or {x, y, z}
PostScript["string"] is a graphics primitive which gives PostScript code to
include verbatim in graphics output.
Raster[{{a, b, }, }] is a two-dimensional graphics primitive which
represents a rectangular array of gray cells.
RasterArray[[{{g 11 , g12 , }, }] is a two-dimensional graphics primitive
which represents a rectangular array of cells colored according to the graphics
directives gij.
Rectangle[{xmin, ymin}, {xmax, ymax}] is a two-dimensional graphics
primitive that represents a filled rectangle, oriented parallel to the axes.
Rectangle[{xmin, ymin}, {xmax, ymax}, graphics] gives a rectangle filled
with the specified graphics.
RGBColor[red, green, blue] is a graphics directive which specifies that
graphical objects which follow are to be displayed, if possible, in the color given.

Bruce E. Shapiro
Woods Hole, 1998

Page 51

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Scaled[{x, y, }] gives the position of a graphical object in terms of


coordinates scaled to run from 0 to 1 across the whole plot in each direction.
Scaled[{dx, dy, }, {x, y, ...}] gives a position obtained by starting at
absolute coordinates {x, y, ...}, then moving by a scaled offset {dx, dy, }.
StyleForm[expr, options] prints using the specified style options.
StyleForm[expr, "style"] prints using the specified cell style in the current
notebook.
SurfaceColor[dcol] is a three-dimensional graphics directive which specifies
that the polygons which follow should act as diffuse reflectors of light with a color
given by dcol.
SurfaceColor[dcol, scol] specifies that a specular reflection component
should be included, with a color given by scol.
SurfaceColor[dcol, scol, n] specifies that the reflection should occur with
specular exponent n.
Text[expr, coords] is a graphics primitive that represents text corresponding to
the printed form of expr, centered at the point specified by coords.
Thickness[r] is a graphics directive which specifies that lines which follow are
to be drawn with a thickness r. The thickness r is given as a fraction of the total
width of the graph

Bruce E. Shapiro
Woods Hole, 1998

Page 52

Medical Informations: A Course for Health Professionals

Mathematical Modeling

VI. Programming
A. Assignment
lhs = rhs evaluates rhs and assigns the result to be the value of lhs. From then on,
lhs is replaced by rhs whenever it appears.
lhs := rhs assigns rhs to be the delayed value of lhs. rhs is maintained in an
unevaluated form. When lhs appears, it is replaced by rhs, evaluated afresh each
time.
lhs =. removes any rules defined for lhs.
Clear[a1, a2 ] clears values and definitions for the ai.
x++ increases the value of x by 1, returning the old value of x.
x += dx adds dx to x and returns the new value of x.
x-- decreases the value of x by 1, returning the old value of x.
x -= dx subtracts dx from x and returns the new value of x.
++x increases the value of x by 1, returning the new value of x.
--x decreases the value of x by 1, returning the new value of x.
x *= c multiplies x by c and returns the new value of x.
x /= c divides x by c and returns the new value of x.
AppendTo[s, elem] appends elem to the value of s, and resets s to the result.
PrependTo[s, elem] prepends elem to the value of s, and resets s to the result.
f/: lhs = rhs assigns rhs to be the value of lhs, and associates the assignment with
the symbol f.
f/: lhs := rhs assigns rhs to be the delayed value of lhs, and associates the
assignment with the symbol f.
f/: lhs =. removes any rules defined for lhs, associated with the symbol f.
lhs^=rhs assigns rhs to be the value of lhs, and associates the assignment with
symbols that occur at level one in lhs.
lhs^:=rhs assigns rhs to be the delayed value of lhs, and associates the assignment
with symbols that occur at level one in lhs.

B. Testing
lhs == rhs returns True if lhs and rhs are identical.
lhs != rhs or lhs rhs returns False if lhs and rhs are identical.
lhs === rhs yields True if the expression lhs is identical to rhs, and yields False
otherwise.
Bruce E. Shapiro
Woods Hole, 1998

Page 53

Medical Informations: A Course for Health Professionals

Mathematical Modeling

lhs =!= rhs yields True if the expression lhs is not identical to rhs, and yields
False otherwise.
x < y yields True if x is determined to be less than y.
x > y yields True if x is determined to be greater than y.
x <= y or x y yields True if x is determined to be less than or equal to y.
x >= y or x y yields True if x is determined to be greater than or equal to y.
EvenQ[expr] gives True if expr is an even integer, and False otherwise.
IntegerQ[expr] gives True if expr is an integer, and False otherwise.
MatrixQ[expr] gives True if expr is a list of lists that can represent a matrix, and
gives False otherwise.
MemberQ[list, form] returns True if an element of list matches form, and
False otherwise.
Negative[x] gives True if x is a negative number.
NonNegative[x] gives True if x is a non-negative number.
NonPositive[x] gives True if x is a non-positive number.
NumberQ[expr] gives True if expr is a number, and False otherwise.
NumericQ[expr] gives True if expr is a numeric quantity, and False otherwise.
OddQ[expr] gives True if expr is an odd integer, and False otherwise.
PolynomialQ[expr, var] yields True if expr is a polynomial in var, and yields
False otherwise.
Position[expr, pattern] gives a list of the positions at which objects matching
pattern appear in expr.
Position[expr, pattern, levspec] finds only objects that appear on levels
specified by levspec.
Positive[x] gives True if x is a positive number.
PrimeQ[expr] yields True if expr is a prime number, and yields False
otherwise.
VectorQ[expr] gives True if expr is a list, none of whose elements are
themselves lists, and gives False otherwise.
VectorQ[expr, test] gives True only if test yields True when applied to each
of the elements in expr.

C. Flow of Control
1. Compound Expressions
expression; expression; expression; ... evaluates each expression in turn,
giving the last one as the result.
Bruce E. Shapiro
Woods Hole, 1998

Page 54

Medical Informations: A Course for Health Professionals

Mathematical Modeling

2. Logical Testings: If, Which, Switch


If[condition, t, f] gives t if condition evaluates to True, and f if it evaluates
to False.
If[condition, t, f, u] gives u if condition evaluates to neither True nor
False.
Which[test, value, test, value, ] evaluates each of the test in turn, returning
the value corresponding to the first one that yields True.
Switch[expr, form, value, form, value, ... ] evaluates expr, then compares it
with each of the form in turn, evaluating and returning the value corresponding
to the first match found.

3. Looping: Do, While, For


Do[expr, {imax}] evaluates expr imax times.
Do[expr, {i, imax}] evaluates expr with the variable i successively taking on
the values 1 through imax (in steps of 1).
Do[expr, {i, imin, imax}] starts with i = imin.
Do[expr, {i, imin, imax, di}] uses steps di.
Do[expr, {i, imin, imax}, {j, jmin, jmax}, ] evaluates expr looping over
different values of j, etc. for each i.
While[test, body] evaluates test, then body, repetitively, until test first fails to
give True.
For[start, test, incr, body] executes start, then repeatedly evaluates body
and incr until test fails to give True.

4. Transfer of Control: Return, Throw, Catch, Break,


Continue, Goto, Label, Check, Interrupt, Abort,
Print
Return[expr] returns the value expr from a function.
Return[ ] returns the value Null.
Throw[value] stops evaluation and returns value as the value of the nearest
enclosing Catch.
Throw[value, tag] is caught only by Catch[expr, form] where form is a
pattern that matches tag.
Catch[expr] returns the argument of the first Throw generated in the
evaluation of expr.
Catch[expr, form] returns value from the first Throw[value, tag] for
which form matches tag.
Catch[expr, form, f] returns f[value, tag].
Break[ ] exits the nearest enclosing Do, For or While.
Continue[ ] exits to the nearest enclosing Do, For or While in a procedural
program.
Goto[tag] scans for Label[tag], and transfers control to that point.

Bruce E. Shapiro
Woods Hole, 1998

Page 55

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Label[tag] represents a point in a compound expression to which control can


be transferred using Goto.
Check[expr, failexpr] evaluates expr, and returns the result, unless messages
were generated, in which case it evaluates and returns failexpr.
CheckAbort[expr, failexpr] evaluates expr, returning failexpr if an abort
occurs. And my computer kept crashing every time I tried to

copy this line into MS Word! At exactly this spot!


Interrupt[ ] generates an interrupt.
Abort[ ] generates an interrupt to abort a computation.
TimeConstrained[expr, t] evaluates expr, stopping after t seconds.
MemoryConstrained[expr, b] evaluates expr, stopping if more than b
bytes of memory are requested.
AbortProtect[expr] evaluates expr, saving any aborts until the evaluation is
complete.

D. Input & Output


Print[expression, expression, ] prints the expression followed by a newline
(line feed).
Input[ ] interactively reads in one Mathematica expression.
Input["prompt"] requests input, using the specified string as a prompt.
InputString[ ] interactively reads in a character string.
InputString["prompt"] requests input, using the specified string as a prompt.
Note: Mathematica contains an extensive number of input, output, and file
access facilities which are beyond the scope of this doucument.

D. Functions
functionName[arg1_, arg2_, arg3_, ...] := expression;
defines a function with arguments arg1, arg2, arg3. expression may be a
single expression, a compound expression, or a list. The tag _ is not used in the
right hand side of the function defintion when the arguments are being referenced.
The expressions on the right hand side are evaluated sequentially, and the functions
return value is the last expression in the list. If the last expression ends in a
semicolon : then the return value is null.
Map[f, expr] or f /@ expr applies f to each element on the first level in expr.
Apply[f, expr] or f @@ expr replaces the head of expr by f.
Note: Mathematica contains an extensive number of functions which greatly
expand the ability to write functions.

E. Pattern Matching
_ or Blank[ ] is a pattern object that can stand for any Mathematica expression.
__ (two _ characters) or BlankSequence[ ] is a pattern object that can stand for
any sequence of one or more Mathematica Expressions

Bruce E. Shapiro
Woods Hole, 1998

Page 56

Medical Informations: A Course for Health Professionals

Mathematical Modeling

__h or BlankSequence[h] can stand for any sequence of one or more


expressions, all of which have head h.
___ (three _ characters) or BlankNullSequence[ ] is a pattern object that can
stand for any sequence of zero or more Mathematica expressions.
___h or BlankNullSequence[h] can stand for any sequence of expressions,
all of which have head h.
a | a | is a pattern object which represents any of the patterns a.
s:obj represents the pattern object obj, assigned the name s.
p:v is a pattern object which represents an expression of the form p, which, if
omitted, should be replaced by v.
p.. is a pattern object which represents a sequence of one or more expressions,
each matching p.
p... is a pattern object which represents a sequence of zero or more expressions,
each matching p.
patt /; test is a pattern which matches only if the evaluation of test yields True.
lhs :> rhs /; test represents a rule which applies only if the evaluation of test
yields True.
lhs := rhs /; test is a definition to be used only if test yields True.
p?test is a pattern object that stands for any expression which matches p, and on
which the application of test gives True.
Verbatim[expr] represents expr in pattern matching, requiring that expr be
matched exactly as it appears, with no substitutions for blanks or other
transformations.
HoldPattern[expr] is equivalent to expr for pattern matching, but maintains
expr in an unevaluated form.
Orderless is an attribute that can be assigned to a symbol f to indicate that the
elements a in expressions of the form f[a, a, ] should automatically be sorted
into canonical order. This property is accounted for in pattern matching.
Flat is an attribute that can be assigned to a symbol f to indicate that all
expressions involving nested functions f should be flattened out. This property is
accounted for in pattern matching.
OneIdentity is an attribute that can be assigned to a symbol f to indicate that
f[x], f[f[x]], etc. are all equivalent to x for the purpose of pattern matching.
Default[f], if defined, gives the default value for arguments of the function f
obtained with a _. pattern object.
Position[expr, pattern] gives a list of the positions at which objects matching
pattern appear in expr.
Count[list, pattern] gives the number of elements in list that match pattern.
MatchQ[expr, form] returns True if the pattern form matches expr, and returns
False otherwise.

Bruce E. Shapiro
Woods Hole, 1998

Page 57

Medical Informations: A Course for Health Professionals

Mathematical Modeling

F. Rules
lhs -> rhs or lhs rhs represents a rule that transforms lhs to rhs.
lhs :> rhs or lhs rhs represents a rule that transforms lhs to rhs, evaluating rhs
only after the rule is used.
Replace[expr, rules] applies a rule or list of rules in an attempt to transform the
entire expression expr.
expr /. rules applies a rule or list of rules in an attempt to transform each subpart
of an expression expr.
expr //. rules repeatedly performs replacements until expr no longer changes.
ReplaceList[expr, rules] attempts to transform the entire expression expr by
applying a rule or list of rules in all possible ways, and returns a list of the results
obtained.

G. Strings
String is the head of a character string "text".
"s1" <> "s2" <> , StringJoin["s1", "s2", ] or
StringJoin[{"s1", "s2", }] yields a string consisting of a concatenation
of the si.
StringLength["string"] gives the number of characters in a string.
StringReverse["string"] reverses the order of the characters in "string".
StringTake["string", n] gives a string containing the first n characters in
"string".
StringTake["string", -n] gives the last n characters in "string".
StringTake["string", {n}] gives the nth character in "string".
StringTake["string", {m,n}] gives characters m through n th characters in
"string".
StringDrop["string", n] gives "string" with its first n characters dropped.
StringDrop["string", -n] gives "string" with its last n characters dropped.
StringDrop["string", {n}] gives "string" with its ntth character dropped
StringDrop["string", {m,n}] gives "string" with characters m through n
dropped
StringReplace[string, {s->sp, s->sp, ...}] replaces the s by sp
in string.
StringPosition[string, substring] finds where substring occurs in
string.
StringMatchQ[String, pattern] returns True if pattern occurs in
string.
string1 == string2 returns True if the strings are identical.

Bruce E. Shapiro
Woods Hole, 1998

Page 58

Medical Informations: A Course for Health Professionals

Mathematical Modeling

References
Abell, Martha L., and James P. Braselton, Mathematica by Example, Revised Edition, AP
Professional, 1994. Mathematica techniques for the beginning user.
Andrew, A.D., G.L. Cain, S. Crum, and T.D. Morley. Calculus Projects Using
Mathematica, Revised Edition. Mc Graw Hill, 1993.
Andrew, A.D., and T.D. Morley. Linear Algebra Projects Using Mathematica. Mc Graw
Hill, 1993.
AP Professional, Mathematica CD-ROM Library, 1996. Multi-platform cd-rom that
contains searchable electronic versions of 5 books: Mathematica by Example, Revised
Edition by M. Abell and J. Braselton; The Mathematica Handbook by M. Abell and J.
Braselton; Differential Equations with Mathematica by M. Abell and J. Braselton;
Mastering Mathematica by J. Gray; and Introduction to Computer Performance
Analyiswith Mathematica by A. Allen.
Bahder, Thomas. B. Mathematica for Scientists and Engineers. Addison Wesley, 1995.
Barker, William H., David A. Smith and Lawrence C. Moore. Mathematica Laboratory
Manual to accompany Calculus: Modeling and Application by David Smith and Lawrence
Moore. Heath, 1996.
Baumann, Gerd. Mathematica in Theoretical Physics: Selected Examples from Classical
Mechanics to Fractals. TELOS, 1996.
Blachman, Nancy, Mathematica: A Practical Approach, Prentice Hall, 1992. General
introduction to Mathematica.
Blachman, Nancy, Mathematica: Quick Reference, Version 2, Addison-Wesley, 1992.
Spiral bound pocket size comprehensive cross reference.
Blachman, Nancy. CalcLabs with Mathematica. Brooks and Cole, 1996.
Braden, Bart , Donald K. Krug, Philip W. McCartney, and Steven Wilkinson. Discovering
Calculus with Mathematica. Wiley, 1992.
Burbullam D.C.M. and C.T.J. Dodson. Self-Tutor for Computer Calculus Using
Mathematica. Prentice Hall, 1992.
Burkhardt, Werner, First Steps in Mathematica, Springer-Verlag, 1994. A step-by-step
introduction to Mathematica for first-time users
Cheung, C. K., G. E. Keough and Tim Murdoch. Exploring Multivariable Calculus with
Mathematica. Wiley, 1996. Laboratory manual to accompany Multivariate Calculus by W.
McCallum, D. Hughes-Hallett and A. Gleason.
Cohen, Jack K. and Frank G. Hagin. Calculus Explorations with Mathematica. Prentice
Hall, 1995. Undergraduate calculus lab manual and diskette.
Bruce E. Shapiro
Woods Hole, 1998

Page 59

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Coombes, Kevin R., Brian R. Hunt, Ronald L. Lipsman, John E. Osborn, and Garrett J.
Stuck Differential Equations with Mathematica. Wiley, 1995.
Crandall, Richard E. Mathematica for the Sciences. Addison Wesley, 1991.
Crooke, Phillip and John Ratcliffe. A Guidebook to Calculus with Mathematica.
Wadsworth, 1991.
Davis, Bill, Horacio Porta, and Jerry Uhl. Calculus & Mathematica. Addison Wesley,
1994. Windows, Mac, NeXT versions.
Ellis, Wade, Jr., and Ed Lodi, A Tutorial Introduction to Mathematica, Brooks/Cole, 1991.
Title speaks for itself.
Ellison, John. Mathematica Notebook for Differential Equations with Computer Lab
Experiments by Dennis G. Zill, PWS Publishing, 1995. Mac or DOS diskette.
Emert, John and Roger Nelson. Calculus & Mathematica. Saunders, 1992.
Feagin, James M. Quantum Methods with Mathematica. TELOS, 1994.
Finch, James K. and Millianne Lehmann. Exploring Calculus with Mathematica. Addison
Wesley, 1992.
Freeman, James A. Simulating Neural Networks with Mathematica. Addison Wesley,
1994.
Ganzha Victor G. and Evgenii V. Vorozhtsov. Numerical Solutions for Partial Differential
Equations: Problem Solving Using Mathematica . CRC Press, 1996.
Green, Edward. Benny Evans, and Jerry Johnson. Exploring Calculus with Mathematca.
Wiley, 1994.
Hibbard, Allen. Calculus Explorations using Mathematica. Saunders, 1996.
Hft, Margret H. Laboratories for Calculus I Using Mathematica. Addison Wesley 1992.
Gaylord, Richard J., Sam N. Kamin and Paul R. Wellin. An Introduciton to Programming
with Mathematica. TELOS/Spring-Verlag, 1996. Programming in Mathematica.
Gaylord, Richard J. and Paul R. Wellin. Computer Simulations with Mathematica:
Explorations in Complex Physical and Biological Systems. TELOS, 1995.
Gloor, Oliver, Beatrice Amrhein and Roman E. Maeder. Illustrated Mathematics:
Visualization of Mathematical Objects with Mathematica. TELOS, 1995. Visualization of
various concepts in college Mathematics at all levels.
Gray, Alfred. Modern Differential Geometry of Curves and Surfaces. CRC Press, 1993.
Gray, John. Mastering Mathematica: Programming Methods and Applications. AP
Professional, 1994. Various programming styles in Mathematica.
Gray, Theodore W., and Jerry Glynn, The Beginner's Guide to Mathematica Version 2,
Addison-Wesley, 1992. Tutorial and reference.
Bruce E. Shapiro
Woods Hole, 1998

Page 60

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Gray, Theodore W. and Jerry Glynn. Exploring Mathematics with Mathematica. Addison
Wesley, 1991.
Johnson, Eugene. Linear Algebra with Mathematica. Brooks and Cole, 1995.
Kaufmann, Stephan, Mathematica as a Tool, Birkhuser, 1994. General introduction to
Mathematica. with emphasis on programming and examples from mechanical and civil
engineering.
Kerckhove, Michael G. and Van C. Nall. Calculus Laboratories with Mathematica (3
Vols.) . McGraw Hill, 1993.
Kernen, V. and P. Mitic, Ed. Mathematics with Vision: Proceedings of the First
International Mathematica Symposium. Computational Mechanics Publications, 1995.
Knoll, Cecilia A., Michael D. Shaw, Jerry Johnston and Benny Evans. Discovering Calculus
with Mathematica. Wiley, 1995.
Kreyszig, E. and E.J. Normington. Mathematica Computer Manual to accompany
Advanced Engineering Mathematics, Seventh Edition. Wiley, 1994.
Maeder, Roman. The Mathematica Programmer. AP Professional, 1994. Mathematica as
an object oriented programming language.
Maeder, Roman. Programming in Mathematica. Third Edition. Addison-Wesley, 1997.
Programming in Version 3.0 of Mathematica.
Olinick, Eli. V. Mathematic Notebook for Calculus, Sixth Edition, by Swokowski, Olinick,
and Pence and for Calculus of a Single Variable, Second Edition by Swokowski,
Olinick, and Pence. PWS Publishing. Mac or DOS diskette.
ONeil, Peter V. Mathematica Lab Manual to accompany Peter V. O'Neil's Advanced
Engineering Mathematics, Fourth Edition. PWS, 1995.
Ostovic, Vlado. Computer Aided Analysis of Electric Machines: A Mathematica Approach.
Prentice Hall, 1994.
Packel, Ed. Mathematica for Mathematics Teachers: Notes from an Introdutory Course.
Front Range Press, 1996.
Packel, Ed and Stan Wagon. Animating Calculus: Mathematica Notebooks for the
Laboratory. Freeman, 1994.
Parker, Leonard and Steven M. Christensen. MathTensor: A System for Doing Tensor
Analysis by Computer. Addison Wesley, 1994.
Pidgeon, Charles, ed. Advanced Tutorials for the Biomedical Sciences: Animations,
Simulations, and Calculations Using Mathematica. VCH, 1996.
Riddle, Alfred, and Samuel Dick. Applied Electronic Engineering with Mathematica.
Addison Wesley, 1994.

Bruce E. Shapiro
Woods Hole, 1998

Page 61

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Robertson, John S. Engineering Mathematics with Mathematica. McGraw Hill, 1994.


Ross, Clay C. Differential Equations: An Introduction with Mathematica. Springer-Verlag,
1995.
Shaw, William T., and Jason Tigg, Applied Mathematica: Getting Started, Getting It Done,
Addison-Wesley, 1994. Problems in engineering, finance, environmental engineering, and
image processing.
Shuchat, Alan, and Fred Shultz, The Joy of Mathematica: A Point-and-Click Way to Use
and Learn Mathematica, Addison-Wesley, 1994. Software program for the Macintosh that
adds menus and dialog boxes while running concurrently with Mathematica.
Skeelm Robert D. and Jerry B. Keiper. Elementary Numerical Computing with
Mathematica . McGraw Hill, 1993.
Skiena, Steven. Implementing Discrete Mathematics: Combinatorics and Graph Theory
with Mathematica. Addison Wesley, 1990.
Smith, Cameron and Nancy Blachman. The Mathematica Graphics Guidebook. Addison
Wesley, 1995. Tutorial in graphics with Mathematica.
Sparks, Arthur G. , John W. Davenport, and James P. Braselton. Calculus Labs Using
Mathematica. Harper Collins, 1993.
Stroyan, K. D. Calculus Using Mathematica. Academic, 1993.
Vardi, Ilan. Computational Recreations in Mathematica. Addison Wesley, 1991.
Varley, Rodney. Mathematica Exercises in Introductory Physics. Prentice Hall, 1996. Mac
and DOS versions.
Vvedensky, Dmitri. Partial Differential Equations with Mathematica. Addison Wesley,
1993.
Wanger, David B., Power Programming with Mathematica: The Kernel. Mc Graw-Hill,
1996. Guide to Mathematicas programming language.
Wagon, Stan. Mathematica in Action, W. H. Freeman, 1991.
Wagon, Stan. The Power of Visualization: Notes from a Mathematica Course. Front
Range Press, 1994. Course is aimed at mathematics (calculus) teachers.
Wickham-Jones, Tom. Mathematica Graphics: Techniques and Applications. TELOS,
1994. Introduction to using graphics in Mathematica.
Wicks, John R. Linear Algebra: An Interactive Laboratory Approach with Mathematica.
Addison Wesley, 1996. Undergraduate course in linear algebra.
Wolfram, Stephen, The Mathematica Book, Third Edition, Wolfram Media, Inc. and
Cambridge University Press, 1996,

Bruce E. Shapiro
Woods Hole, 1998

Page 62

Medical Informations: A Course for Health Professionals

Mathematical Modeling

Wolfram, Stephen, Mathematica: A System for Doing Mathematics by Computer, Second


Edition, Addison-Wesley, 1991.
Wolfram, Stephen, Mathematica Reference Guide (for Mathematica Version 2), AddisonWesley, 1992.
Wolfram, Stephen, and George Beck, Mathematica: The Student Book, Addison-Wesley,
1994.
Wolfram Research, MathLink Reference Guide, Version 2.2, Wolfram Media, 1993.
Wolfram Research, Mathematica 3.0 Standard Add-on Packages, Wolfram Media, Inc.
and Cambridge University Press, 1996.
Wolfram Research, Guide to Standard Mathematica Packages, Version 2.2, 1993.
Zimmerman, Robert L. and Fredrick I. Olness. Mathematica for Physics. Addison Wesley,
1995.

Bruce E. Shapiro
Woods Hole, 1998

Page 63

You might also like