Professional Documents
Culture Documents
Mathematica Reference
Mathematica Reference
TH EDITION
BOOK
THE
Authors website:
www.stephenwolfram.com
Authors address:
email: s.wolfram@wolfram.com
mail: c/o Wolfram Research, Inc.
100 Trade Center Drive
Champaign, IL 61820, USA
15
14 13
12
11
10 9
8 7
6 5
4 3 2
www.wolfram.com
vii
puting. In the years that followed, the popularity of Mathematica grew rapidly, and Wolfram Research became established
Wolfram became in 1981 the youngest recipient of a MacArthur Prize Fellowship. Late in 1981, Wolfram then set out
between computation and nature, and inventing such concepts as computational irreducibility. Wolframs work led to a
book was widely acclaimed and immediately became a bestseller. Its publication has been seen as initiating a paradigm
ix
About Mathematica
Mathematica is the worlds only fully integrated environment
for technical computing. First released in 1988, it has had
a profound effect on the way computers are used in many
technical and other fields.
It is often said that the release of Mathematica marked the beginning of modern technical computing. Ever since the 1960s
individual packages had existed for specific numerical, algebraic, graphical and other tasks. But the visionary concept of
Mathematica was to create once and for all a single system
that could handle all the various aspects of technical computing in a coherent and unified way. The key intellectual
advance that made this possible was the invention of a new
kind of symbolic computer language that could for the first
time manipulate the very wide range of objects involved in
technical computing using only a fairly small number of basic
primitives.
When Mathematica Version 1 was released, the New York
Times wrote that the importance of the program cannot
be overlooked, and Business Week later ranked Mathematica
among the ten most important new products of the year.
Mathematica was also hailed in the technical community as a
major intellectual and practical revolution.
At first, Mathematicas impact was felt mainly in the physical
sciences, engineering and mathematics. But over the years,
Mathematica has become important in a remarkably wide
range of fields. Mathematica is used today throughout the
sciencesphysical, biological, social and otherand counts
many of the worlds foremost scientists among its enthusiastic
supporters. It has played a crucial role in many important
discoveries, and has been the basis for thousands of technical
papers. In engineering, Mathematica has become a standard
tool for both development and production, and by now many
of the worlds important new products rely at one stage
or another in their design on Mathematica. In commerce,
Mathematica has played a significant role in the growth of
sophisticated financial modeling, as well as being widely used
in many kinds of general planning and analysis. Mathematica
has also emerged as an important tool in computer science
and software development: its language component is widely
used as a research, prototyping and interface environment.
Symbolic Computation
Solutions to mixed systems of equations and inequalities in
Reduce.
Complete solving of polynomial systems over real or complex
numbers.
Solving large classes of Diophantine equations.
Numerical Computation
xi
Interfaces
Notebook Interface
xii
This book is intended to be a complete introduction to Mathematica. It describes essentially all the capabilities of Mathematica,
these new functions that you use, rather than the standard
ones described in the book.
are using, then you must rely on the documentation for that
system.
perspective on Mathematica.
Getting Started with Mathematica: a booklet describing installation, basic operation, and troubleshooting of Mathematica on
specific computer systems.
xiii
As with any other computer system, there are a few points that you
need to get straight before you can even start using Mathematica.
For example, you absolutely must know how to type your input to
Once you know the basics, you can begin to get a feeling for
Mathematica by typing in some examples from this book. Always
be sure that you type in exactly what appears in the bookdo
not change any capitalization, bracketing, etc.
After you have tried a few examples from the book, you should
start experimenting for yourself. Change the examples slightly,
and see what happens. You should look at each piece of output
carefully, and try to understand why it came out as it did.
After you have run through some simple examples, you should
In going through the steps to solve your problem, you will learn
once you have the formulation, you can easily do many different
xiv
calculations with it. This means that you can effectively carry out
of your problem.
a while you should know all of its basic principles, you may never
There are typically many different ways to formulate a given problem in Mathematica. In almost all cases, however, the most direct
and simple formulations will be best. The more you can formulate
your problem in Mathematica from the beginning, the better.
Often, in fact, you will find that formulating your problem directly
in Mathematica is better than first trying to set up a traditional
mathematical formulation, say an algebraic one. The main point
learn the details of all its features. As a result, even after you
have had a great deal of experience with Mathematica, you will
undoubtedly still find it useful to look through this book. When
you do so, you are quite likely to notice features that you never
noticed before, but that with your experience, you can now see
how to use.
Writing Programs
For most of the more sophisticated problems that you want to
solve with Mathematica, you will have to create Mathematica
useful to try out examples from this Tour with your own copy of
Mathematica.
and you have to choose which one to use in each case. It turns
out that no single type of programming suits all cases well. As a
the first three or four sections in Part 1 before you start to use
Mathematica on your own. These sections describe the basics that
you need to know in order to use Mathematica at any level.
computations.
a sequence of specific features, Part 2 takes a more global approach. If you want to learn how to create your own Mathematica
grows over a period of months or years, you will probably find that
xv
Until you are familiar with Mathematica, make sure to type the
input exactly as it appears in the book. Do not change any of
the capital letters or brackets. Later, you will learn what things
you can change. When you start out, however, it is important
that you do not make any changes; otherwise you may not get
the same results as in the book.
Never type the prompt In[n]:= that begins each input line.
Type only the text that follows this prompt.
You will see that the lines in each dialog are numbered
in sequence. Most subsections in the book contain separate
dialogs. To make sure you get exactly what the book says, you
should start a new Mathematica session each time the book
does.
xvii
A Tour of Mathematica..................................................1
Part 1.A Practical Introduction to Mathematica
1.0
1.1
1.2
1.3
1.4
1.5
Symbolic Mathematics.................................................79
1.6
1.7
Numbers...................................................................... 722
3.2
3.3
3.4
3.5
3.6
3.7
3.8
3.9
3.10
1.8
Lists..............................................................................115
1.9
1.10
A.1
1.11
A.2
1.12
A.3
A.4
A.5
A.6
A.7
A.8
A.9
Expressions .................................................................230
2.2
2.3
Patterns .......................................................................259
2.4
Manipulating Lists......................................................283
2.5
2.6
2.7
2.8
2.9
2.10
2.11
Manipulating Notebooks...........................................572
2.12
2.13
2.14
xix
Table of Contents
,
-
A Tour of Mathematica..................................................................................................................................1
Mathematica as a Calculator Power Computing with Mathematica Accessing Algorithms in Mathematica Mathematical Knowledge in Mathematica Building Up Computations Handling Data Visualization with Mathematica Mathematica Notebooks Palettes and Buttons Mathematical Notation Mathematica and Your Computing Environment
The Unifying Idea of Mathematica Mathematica as a Programming Language Writing Programs in Mathematica
Building Systems with Mathematica Mathematica as a Software Component
Part 1.
1.0
Running Mathematica.....................................................................................................................................26
Notebook Interfaces
1.1
Text-Based Interfaces
Numerical Calculations....................................................................................................................................29
Arithmetic Exact and Approximate Results
Some Mathematical Functions
Arbitrary-Precision Calculations
Complex Numbers Getting Used to Mathematica Mathematical Notation in Notebooks
1.2
Building Up Calculations.................................................................................................................................38
Using Previous Results Defining Variables Making Lists of Objects
Kinds of Bracketing in Mathematica Sequences of Operations
1.3
The Four
1.4
Algebraic Calculations.....................................................................................................................................63
Symbolic Computation Values for Symbols Transforming Algebraic Expressions Simplifying Algebraic Expressions Advanced Topic: Putting Expressions into Different Forms Advanced Topic: Simplifying with Assumptions
Picking Out Pieces of Algebraic Expressions Controlling the Display of Large Expressions - The Limits of
Mathematica Using Symbols to Tag Objects
1.5
Symbolic Mathematics....................................................................................................................................79
Basic Operations Differentiation Integration Sums and Products Equations - Relational and Logical Operators - Solving Equations , Inequalities - Differential Equations Power Series Limits Integral Transforms
, Recurrence Equations - Packages for Symbolic Mathematics
Advanced Topic: Generic and Non-Generic Cases
Mathematical Notation in Notebooks
-
xx
1.6
Numerical Mathematics................................................................................................................................102
Basic Operations Numerical Sums, Products and Integrals - Numerical Equation Solving
Equations - Numerical Optimization - Manipulating Numerical Data - Statistics
1.7
Numerical Differential
1.8
Functions as Procedures
Repetitive Operations
Lists.................................................................................................................................................................115
Collecting Objects Together Making Tables of Values - Vectors and Matrices - Getting Pieces of Lists Testing
and Searching List Elements - Adding, Removing and Modifying List Elements Combining Lists Advanced Topic:
Lists as Sets - Rearranging Lists Grouping Together Elements of Lists , Ordering in Lists - Advanced Topic:
Rearranging Nested Lists
1.9
Why You Do Not Usually Need to Know about Internals Basic Internal Architecture
The Software Engineering of Mathematica Testing and Verification
Part 2.
2.1
Principles of Mathematica
Expressions.....................................................................................................................................................230
Everything Is an Expression The Meaning of Expressions
Manipulating Expressions like Lists Expressions as Trees
2.2
Parts of Expressions
Functional Operations...................................................................................................................................240
Function Names as Expressions Applying Functions Repeatedly Applying Functions to Lists and Other Expressions Applying Functions to Parts of Expressions Pure Functions Building Lists from Functions Selecting Parts
of Expressions with Functions - Expressions with Heads That Are Not Symbols Advanced Topic: Working with
Operators - Structural Operations Sequences
2.3
Patterns...........................................................................................................................................................259
Introduction Finding Expressions That Match a Pattern Naming Pieces of Patterns Specifying Types of Expression in Patterns - Putting Constraints on Patterns Patterns Involving Alternatives Flat and Orderless Functions
xxi
Functions with Variable Numbers of Arguments Optional and Default Arguments Setting Up Functions with
Optional Arguments Repeated Patterns Verbatim Patterns Patterns for Some Common Types of Expression An
Example: Defining Your Own Integration Function
2.4
Manipulating Lists.........................................................................................................................................283
Constructing Lists
Arrays
2.5
Nested Lists
Sparse
2.6
Evaluation of Expressions............................................................................................................................324
Principles of Evaluation Reducing Expressions to Their Standard Form Attributes The Standard Evaluation Procedure Non-Standard Evaluation Evaluation in Patterns, Rules and Definitions Evaluation in Iteration Functions
Conditionals Loops and Control Structures , Collecting Expressions During Evaluation Advanced Topic: Tracing
Evaluation Advanced Topic: The Evaluation Stack Advanced Topic: Controlling Infinite Evaluation Advanced
Topic: Interrupts and Aborts Compiling Mathematica Expressions Advanced Topic: Manipulating Compiled Code
2.7
2.8
2.9
xxii
Part 3.
3.1
Dialogs
Memory Management
Numbers.........................................................................................................................................................722
Types of Numbers Numeric Quantities Digits in Numbers - Numerical Precision - Arbitrary-Precision Numbers
Machine-Precision Numbers Advanced Topic: Interval Arithmetic Advanced Topic: Indeterminate and Infinite
Results Advanced Topic: Controlling Numerical Evaluation
3.2
Mathematical Functions................................................................................................................................745
Naming Conventions - Numerical Functions Pseudorandom Numbers - Integer and Number-Theoretical Functions Combinatorial Functions Elementary Transcendental Functions Functions That Do Not Have Unique Values
Mathematical Constants Orthogonal Polynomials Special Functions Elliptic Integrals and Elliptic Functions
Mathieu and Related Functions Working with Special Functions Statistical Distributions and Related Functions
3.3
Algebraic Manipulation................................................................................................................................797
Structural Operations on Polynomials Finding the Structure of a Polynomial Structural Operations on Rational
Expressions Algebraic Operations on Polynomials Polynomials Modulo Primes Advanced Topic: Polynomials
over Algebraic Number Fields Trigonometric Expressions Expressions Involving Complex Variables Simplification
- Using Assumptions
3.4
xxiii
3.5
Calculus...........................................................................................................................................................853
Differentiation Total Derivatives Derivatives of Unknown Functions Advanced Topic: The Representation of
Derivatives Defining Derivatives Indefinite Integrals Integrals That Can and Cannot Be Done Definite Integrals
Manipulating Integrals in Symbolic Form - Differential Equations Integral Transforms and Related Operations
Generalized Functions and Related Objects
3.6
3.7
Linear Algebra...............................................................................................................................................896
Constructing Matrices - Getting and Setting Pieces of Matrices Scalars, Vectors and Matrices Operations on
Scalars, Vectors and Matrices Multiplying Vectors and Matrices Matrix Inversion - Basic Matrix Operations
- Solving Linear Systems - Eigenvalues and Eigenvectors , Advanced Matrix Operations - Advanced Topic:
Tensors , Sparse Arrays
-
3.8
3.9
Fourier Transforms
Convolutions
Operators
Basic Objects................................................................................................................................................1014
Expressions
A.2
Symbols
Contexts
Atomic Objects
Numbers
Character Strings
Input Syntax.................................................................................................................................................1018
Entering Characters Types of Input Syntax Character Strings Symbol Names and Contexts Numbers Bracketed
Objects Operator Input Forms Two-Dimensional Input Forms Input of Boxes The Extent of Input Expressions
Special Input Front End Files
A.3
xxiv
A.4
Evaluation.....................................................................................................................................................1045
The Standard Evaluation Sequence Non-Standard Argument Evaluation
Evaluation Preventing Evaluation Global Control of Evaluation Aborts
A.5
A.6
Assignments
Types of Values
Streams
Mathematica Sessions.................................................................................................................................1055
Command-Line Options and Environment Variables
Network License Management
A.8
Initialization
Messages
Termination
A.9
Transformation Rules
A.7
Loadable Files
Listing
Listing
Listing
Index....................................................................................................................................................................1407
A Tour of
Mathematica
The purpose of this Tour is to show examples of a few of the
things that Mathematica can do. The Tour is in no way intended
to be completeit is just a sampling of a few of Mathematicas
capabilities. It also concentrates only on general features, and
does not address how these features can be applied in particular
fields. Nevertheless, by reading through the Tour you should get
at least some feeling for the basic Mathematica system.
Sometimes, you may be able to take examples from this Tour
and immediately adapt them for your own purposes. But more
often, you will have to look at some of Part 1, or at online
Mathematica documentation, before you embark on serious
work with Mathematica. If you do try repeating examples from
the Tour, it is very important that you enter them exactly as they
appear here. Do not change capitalization, types of brackets, etc.
On most versions of Mathematica, you will be able to find this
Tour online as part of the Mathematica help system. Even if you
do not have access to a running copy of Mathematica, you may
still be able to try out the examples in this Tour by visiting
www.wolfram.com/tour.
A Tour of
Mathematica
A Tour of Mathematica
Mathematica as a Calculator . . . . . . . . . . . . . . . . 4
Power Computing with Mathematica . . . . . . . . . . . 5
Accessing Algorithms in Mathematica . . . . . . . . . . . 6
Mathematical Knowledge in Mathematica . . . . . . . . 7
Building Up Computations . . . . . . . . . . . . . . . . . 8
Handling Data
. . . . . . . . . . . . . . . . . . . . . . . . 9
10
Mathematica Notebooks
. . . . . . . . . . . . . . . . .
12
13
Mathematical Notation . . . . . . . . . . . . . . . . . .
14
15
16
17
18
19
20
Mathematica as a Calculator
In[1]:=
Out[1]=
In[2]:=
Out[2]=
In[3]:=
Out[3]=
35
8
57.1 ^ 100
4.60904 10175
Mathematica represents
matrices as lists of lists.
Out[1]=
In[2]:=
Out[2]=
Solvex ^ 2 x a, x
1
1
x 1 1 4 a , x 1 1 4 a
2
2
In[1]:=
2
1
10
20
30
40
-1
-2
In[1]:=
4
3
2
1
1
2
3
40
Here is a 3D plot.
Mathematica comes with
a collection of palettes
that let you do many
operations by clicking
buttons rather than typing
commands.
In[1]:=
In[2]:=
ListPlot[Abs[Eigenvalues[m]]]
10
8
6
4
2
In[1]:=
Out[1]=
In[2]:=
Out[2]=
100 !
100
200
300
400
500
93326215443944152681699238856266700490715968264381621468592
9638952175999932299156089414639761565182862536979208272237
58251185210916864000000000000000000000000
N[Pi, 100]
3.1415926535897932384626433832795028841971693993751
05820974944592307816406286208998628034825342117068
In[1]:=
Out[1]=
In[2]:=
Out[2]=
Factor[x ^ 99 + y ^ 99]
In[1]:=
Out[1]=
PartitionsP[10 ^ 9] // Short
16045350842809668832728039026391874671468439 35131
85690668610189731030457526857797923685688339
In[2]:=
Out[2]=
In[3]:=
Out[3]=
FactorInteger10 ^ 54 3
Out[4]=
21518801375655714851137, 1,
46470989835488840363806434126781, 1
In[1]:=
Out[1]=
2 x, 2 x2 , 2 x3 , 2 x4 ,
4 x, 4 x2 , 4 x3 , 4 x4 , 8 x, 8 x2 , 8 x3 , 8 x4
MatrixFormm
Out[2]//MatrixForm=
2 x 2 x2 2 x3 2 x4
4
x 4 x2 4 x3 4 x4
2 8 x3 8 x4
8
x
8
x
In[3]:=
Out[3]=
NullSpacem
In[1]:=
Out[1]=
In[2]:=
2
1
-2
-1
1
-1
Here is a parametric
plot of the solution.
-2
In[1]:=
Out[1]=
In[2]:=
Out[2]=
LegendreQ3, x
2
5 x2
1
1x
x 3 5 x2 Log
3
2
4
1x
NMathieuC1 , 2, 3, 50
3.9251311374125198643497646168158379203627176844794
1.8988239115433472411052747971439115776785813553761
In[1]:=
Out[1]=
IntegrateSqrtxArcTanx, x
1
8 x 2 2 ArcTan
1 2 x 2 2 ArcTan
1 2 x
6
32
ArcTan
x 2 Log
1 2 x x 2 Log
1 2 x x
4x
In[1]:=
Out[1]=
In[2]:=
Out[2]=
1777777
Out[1]=
1
2
Gamma
6 EulerGamma 3 9 Log
3
81
3
1
1
3
1
1
1
4 HypergeometricPFQ
1, , , 2 Cos
Sin
8
4
4
64
4
4
Out[1]=
Prime10 ^ 9
Out[1]=
22801763489
Mathematicas algorithms
can generate a huge range
of mathematical results.
In[1]:=
Out[1]=
In[1]:=
Out[1]=
In[1]:=
Out[1]=
In[1]:=
Out[1]=
Log2
Zeta3
Sqrt2
True
Building Up Computations
Being able to work with formulas lets you easily
integrate all the parts of a computation.
In[1]:=
Out[1]=
Out[1]=
In[2]:=
10
-5
10
-5
-10
In[3]:=
Out[3]=
In[4]:=
Out[4]=
In[5]:=
Out[5]=
In[6]:=
Out[6]=
In[1]:=
Out[1]=
In[2]:=
Out[2]=
In[3]:=
Out[3]=
In[4]:=
Out[4]=
SolveFirstv 0, c
2
c
3
IntegrateFirstv, c
1
2
3
c
3 c
c2
3 c 17 6 c c2 4 ArcSinh
2
2
2
2 2
3
3
2 c3
3 c4
17
3
17
3
1
2
O
c5
2 ArcSinh
c
c
4
2
2
4
51
17
578
17
2
2
4
17
FindRoot%% 1 c ^ 2, c, 1
c 2.14314
Handling Data
Mathematica lets you import data in any format, then
manipulate it using powerful and flexible functions.
In[1]:=
27 19 32 Out[1]=
17 19
69 69 89 87 97
11 6 6 3 3 3 3
52 45 45 36 39
87 69 74 78 79
29 29 27 22 22
87 73 77 86 66
6 3 6 3 3 6 14
27 29 32 27 27
66 64 73 66 69
27 34 34 29 19
78 81 56 69 79
data Import"image.dat"
27,
29
22 22 19,
22 27 32,
43 7 17, 19, 29, 22, 22, 22, 27
105 106 101 85 79 8
69, 69, 89, 87, 97, 105, 106, 101, 85
14 9 9 9 3 19 14 17
41 53
55 11,
61 80 6,
80 66, 3, 3, 3, 3, 14, 9, 9, 9,
17,
93 74 61 66 73 72 6
In[2]:=
29 27 34 27 22 45 7
66 78 102 108 93 83
19 14 11 29 36 43 3
22 19 22 39 69 53 5
70 66 77 64 61 65 6
19 22 27 22 27 56 6
89 73 69 83 92 77 7
ListDensityPlotdata
In[3]:=
In[4]:=
ListDensityPlotListConvolve
3, 1, 3, 1, data;
In[6]:=
ListDensityPlot
MapIndexedRotateRigh
ListPlotSortFlattendata
200
150
100
In[5]:=
ListContourPlotdata,
ContourShading False,
Contours 6
50
Here is a contour
plot of the data.
ListPlot3Ddata,
ColorFunction GrayLevel,
Mesh False,
ViewPoint 0.2, 2, 5
In[1]:=
Out[1]=
In[3]:=
In[4]:=
Here is a 3D plot
based on the data.
This selects words
that are palindromes with
length more than 4.
4000
3000
In[1]:=
2000
1000
10
15
20
This represents a
million-by-million
identity matrix.
10
In[1]:=
In[2]:=
10
0
-10
40
20
0
-25
-20
0
25
-40
50
Here is a list of
point primitives.
Out[1]=
In[1]:=
Out[1]=
g FlattenTableIfBitAndx, y, z 0,
Cuboidx, y, z, , x, 0, 15,
y, 0, 15, z, 0, 15
Cuboid
0, 0, 0, Cuboid
0, 0, 1,
Cuboid
0, 0, 2, Cuboid
0, 0, 3,
In[2]:=
0
0
0.2
0.4
0.6
0.8
Show[Graphics3D[g]]
11
In[1]:=
Latitude
Nov 17
38 South
3:20 am
South
West
North
12
Mathematica Notebooks
Every Mathematica notebook is a complete interactive document which
combines text, tables, graphics, calculations and other elements.
Mathematica notebooks are automatically
retargeted for screen or printoutoptimizing
fonts and layout for each medium.
In[1]:= PlotSin
Sin , , 0, 100 ;
Notebooks are
automatically organized
in a hierarchy of cells.
In[1]:= PlotSin
Sin , , 0, 100 ;
1
50
100
150
200
250
300
-1
In[1]:=
50
100
150
200
250
300
-1
-2
2
50
100
150
200
250
300
-1
-2
-2
A notebook targeted
for presentation.
2
3
1
1
Forward
2
3
Backward
3 2
Reverse
2
3 2
2 3
2 2
Like other objects in Mathematica , the cells in a notebook, and in fact the whole
notebook itself, are all ultimately represented as Mathematica expressions. With
the standard notebook front end, you can use the command Show Expression to
see the text of the Mathematica expression that corresponds to any particular cell.
Text can contain formulas such as . It can also contain Hyperlinks.
, face,
1
1
, face,
Text can contain formulas such as . It can also contain Hyperlinks.
2 2
Like other objects in Mathematica , the cells in a notebook, and in fact the whole
notebook itself, are all ultimately represented as Mathematica expressions. With
the standard notebook front end, you can use the command Show Expression to
see the text of the Mathematica expression that corresponds to any particular cell.
Like other objects in Mathematica, the cells in a notebook, and in fact the
whole notebook itself, are all ultimately represented as Mathematica expressions.
With the standard notebook front end, you can use the command Show
Expression to see the text of the Mathematica expression that corresponds to any
particular cell.
RiemannSiegelTheta t
RiemannSiegelZ t
StieltjesGamma n
Stieltjes constants n
Zeta
s
Zeta
s, a
1
2
Res .
1
2
In studying i t, it is often convenient to define the two analytic RiemannS i e g e l functions RiemannSiegelZ[t] and RiemannSiegelTheta[z]
1
1
according to Z t e i t i t and t Im log i t2 tlog2
2
DoStylePrint"Heading "
ToStringi, "Subsection",
i, 3
In[1]:=
A Subsection Heading
DoStylePrint"Heading "
ToStringi, "Subsection",
i, 3
Heading 1
Here is the cell.
Heading 2
Heading 3
Here are the three new cells.
13
.
Cross,
Outer, ,
Det
Inverse
Transpose
Eigenvalues
Eigenvectors
LinearSolve,
RowReduce
21
Log
2
21
Darken
Lighten
EdgeSelect
A button waiting
to be filled.
Expand
Factor
Simplify
Clicking the button immediately
factors the part of the expression
you have selected.
1 a b2 p q^2
1 Sinx Cosx
Exp
1
Sinx Cosx
14
Mathematical Notation
Mathematica notebooks fully support standard
mathematical notationfor both output and input.
Here is an integral entered using only
ordinary keyboard characters.
In[1]:=
Out[1]=
IntegrateLog1 x Sqrtx, x
4 ArcTan
x 2 x 2 Log
1 x
Here is the same integral entered in twodimensional form with special characters.
In[2]:=
Log1
int Log1 x 2 x dd x
4 ArcTan
2 2 Log
1
o
.
.
o.
Out[2]=
#. o
o .
.
o .
#.,. o
o
o
..
..
..
..
Out[1]=
+ (4 ArcTan[ ] + 2 ) + 2 Log[1 + ]
o .
%
& '
( )
*
+ "
, - . /
4
In[2]:=
TraditionalForm%
Mathematicas StandardForm
is precise and unambiguous.
TraditionalForm requires
heuristics for interpretation.
Out[2]//TraditionalForm=
4 tan1 2 log 1 2
#
#
7
+>
,E
L
&
%
Q
+
4
X
$
'8
?
!F
'M
&
.R
,
5Y
! "
% &
6
9 : (; )<
=
@ A jB
kC
D
-!G "H" #qI $Jr
N )
O
%K
(
'
( )x *y
S T U V
,P
-/ .0 / 0
]
3W
Z [ \
^ _ ` a b c d
e f g h i
/
:
In[1]:=
0 1
2 3
4
0
5
# $ % & '
*+ 6 , 1l 2m 3n 4 o5
.9s :t ;u < v=
z
A
I
Q
B{ C| D }E
* +
J KL M
1 2
R CST
X
7 89JW
Script
Q
Double-struck U V W
^ _ `
Gothic
g h i
(
.
p6
w
>
!
)
/
7
Exp
4
TraditionalForm
2 2 2
Out[1]//TraditionalForm=
; 1, 1 ; 4 1 F2 ; 1, 1; 4
4
1 F2 ; 1, 1 ; 1 F2 ; 1, 1; 4
2
"
*
0
8
? @
~F G H
N O fP
U V
g
h
: ; MY
i j k
X Y Z [
a b c d
j k l m
1 F2
l
\
e
m
]
f
n
!!!!!!!!!!!! 3i
Table i i " , i, 3
i
Out[1]=
nnnnnnnnnnnn 2
nnnnnnnnnnnn 1
nnnnnnnnnnnn 0
) 1 ' 1 " o, ) 2 ' 2 " o, ) 3 ' 3 " o
1
Greek
All characters have consistent full names;
some also have aliases and TEX names.
15
Notebook[{
Cell[CellGroupData[{
Cell[A Sample Notebook, Title],
Cell[CellGroupData[{
Cell[\<\
Notebooks look the same on every computer
platform and calculations \
give the same results\
\>, Subsection],
Cell[CellGroupData[{
Cell[TextData[N[\[Pi],40]], Input,
CellLabel->In[1]:=],
Notebooks have a
portable underlying plain
text representation.
Macintosh
Unix/Linux
Windows
Log1
\!\(\[Integral]\(Log[1 + \[Xi]]\/\@\[Xi]\)\[DifferentialD]\[Xi]\)
In[1]:=
Install"sampler.exe"
all FileNames"1",
$HomeDirectory, Infinity;
In[2]:=
In[3]:=
ListPlotSortLog10, 1 sizes
LinkObject
sampler.exe, 2, 2
7
In[2]:=
Out[2]=
6
5
4
3
2
1
500
1000
1500
2000
2500
16
m1 a
a, b, c
Lista, b, c
A list of elements
x x
2
Graphics
x Sinx
Equalx, Sinx
Press here
An equation
p && q
TildeCirclePlusa, b,
Subscriptc, Infinity
a b 2 c
An algebraic expression
ButtonBox"Press here"
A button
Andp, Notq
A cell containing text
A logic expression
HNO3
ChemicalHydrogen, 1,
Nitrogen, 1, Oxygen, 3
CircuitResistor"R",
Capacitor"C"
A chemical compound
An electric circuit
In[1]:=
fx_ : 2 x
In[2]:=
f0 : e
In[3]:=
Out[3]=
In[1]:=
Out[1]=
In[2]:=
Out[2]=
In[3]:=
Out[3]=
1
2
e
3
ab
Here is a special
case that overrides the
general definition.
a, b, c, d . b 1 x
a, 1 x, c, d
a b, c d, a c . x_ y_ x^2 y^2
a2 b2 , c2 d2 , a2 c2
a b, c d, a c . a x_ x^3
b3 , c d, c3
In[1]:=
gx_, y_ : x y
In[2]:=
g4, a
Out[2]=
4a
17
In[1]:=
In[1]:=
z a;
DoPrintz 1 z i, i, 3
Out[1]=
a 1 a
Out[2]=
In[2]:=
a 1 a 2 a 1 a
This flattens
out sublists.
a 1 a 2 a 1 a 3 a 1 a 2 a 1 a
In[3]:=
Out[3]=
In[4]:=
Procedural programming
Out[4]=
1 a, b, c^2
1 a2 , 1 b2 , 1 c2
Tablei^j, i, 4, j, i
1, 2, 4, 3, 9, 27, 4, 16, 64, 256
List-based programming
In[1]:=
Out[1]=
In[2]:=
Out[2]=
NestListf, x, 4
x, f
x, f
f
x, f
f
f
x, f
f
f
f
x
NestList1 #^2 &, x, 3
2 2
2 2 2
x, 1 x , 1 1 x , 1 1 1 x
2
In[1]:=
In[2]:=
pa b c
Out[2]=
Functional programming
In[4]:=
s1, 2, 3, 4, 5, 6, 4
Out[4]=
In[1]:=
Out[1]=
StringReplace"aababbaabaabababa",
"aa" "AAA", "ba" "V"
p a p b p c
In[3]:=
4, 1, 2, 3, 1, 2, 3, 5, 6, 5, 6
Rule-based programming
AAAVbVaVaVVV
String-based programming
f Factorial
Object-oriented programming
fn_ : n
fn_ : Gamman 1
fn_ : n fn 1 ; f1 1
In[1]:=
Out[1]=
In[2]:=
Out[2]=
In[3]:=
Out[3]=
In[4]:=
Out[4]=
Position1, 2, 3, 4, 5 2, _Integer
2, 4
MapIndexedPower, a, b, c, d
a, b2 , c3 , d4
18
In[2]:=
ShowGraphics3D
LineRandomWalk1000, 3
20
Here is a plot of a
200-step random walk.
15
10
Here is a plot of a
3D random walk.
50
100
150
200
ElementaryRulenum_Integer :
IntegerDigitsnum, 2, 8
Lif St li t
LifeSteplist_ :
Withu SplitSortFlattenOuterPlus, list, N9, 1, 1,
UnionCasesu, x_, _, _ x,
IntersectionCasesu, x_, _, _, _ x, list
CAGraphicshistory_List :
GraphicsRaster1 Reversehistory,
AspectRatio Automatic
TransferMatrix_, _, p_ :
If1 Modp , 1
1, 1, 0, 1, 1, 0
TransferMatrixList_, _ :
TableTransferMatrix, , p,
p, 0, Denominator 1
TransferMatrixProduct_, _ :
In[8]:= ShowGraphics
FoldExpandDot##&, First#,
Rest#&
SpectrumData 4
TransferMatrixList,
EnergyPolynomial_, _ : Plus44 FareySequence20
TransposeTransferMatrixProduct, , 1, 1
Mathematica
programs can
SpectrumData
: mix
MapLine,
numerical, symbolic and graphics
operations. This short program solves a
sophisticated quantum model.
In[6]:=
ShowCAGraphicsCAEvolveList
ElementaryRule30,
CenterList101, 50
ImpedanceResistorr_, _ : r
1
ImpedanceCapacitorc_, _ :
c
ImpedanceInductorl_, _ : l
FareySequenceq_ :
ApplyUnion, ArrayRange# 1 #&, q
Mathematica is a uniquely
scalable languagesuitable
for programs of any size.
CenterListn_Integer :
ReplacePartTable0, n, 1, Ceilingn 2
ImpedanceSeriesElemente_, _ :
ApplyPlus, MapImpedance#, &, e
ImpedanceParallelElemente_, _ :
1 ApplyPlus, 1 MapImpedance#, &, e
In[6]:=
Out[6]=
ImpedanceSeriesElementTableParallelElement
TableSeriesElementResistorRn , n,
n, 1, 4, Simplify
1
R1 6 R2 4 R3 3 R4
12
Mathematica programs
are often a direct translation
of material in textbooks.
5n_ : TotalMapLast, FactorIntegern
n_ : MoebiusMun
Log2,x
px_ :
k1
1k
x
x1k
; x 0
k n 5n
n
n2
19
In[1]:=
In[2]:=
DiscreteMath`Combinatorica`
Miscellaneous`WorldPlot`
WorldPlotWorld, WorldProjection
N#2 AbsSinDegree 60 #1 1 2, #1 &,
WorldBackground Hue.5;
ShowGraphLineGraphLineGraph
CirculantGraph5, Range1, 3;
Section 3.12
Approximating
an Integral
A common use for integration is determining the area under a curve. That
is, given a curve f x we want to find the area bounded by the curve, the x
axis, and the vertical lines at points a and b. A natural way of estimating this
area is to first subdivide the x axis between a and b into evenly spaced
intervals. Place rectangles as tall as some part of the curve within each
subinterval, and as wide as the subinterval itself along the axis, then add
together the areas of the rectangles. The result is an approximation of the
integral of f(x) from a to b.
In[1]:=
<< Optica`
In[2]:=
DrawSystem[{
ConeOfRays[10,NumberOfRays->10],
Move[PlanoConvexLens[100,50,10],{100,0,0}],
Move[PlanoConvexCylindricalLens[
100, {50, 50},10], {130,0,0}],
Move[BeamSplitter[{50,50},{50,50},10],{180,0,45}],
Boundary[{-100,-100,-100},{250,100,200}]}];
A approx f x i x
i 1
sin x
Sinx
AreaApproximationPlot , x, 0.01, 10;
x
3.9 Lenses
0.8
0.6
Spherical Lenses
0.4
0.2
10
- 0.2
Computer Hardware
Computer Software
ADSK
Autodesk, Inc.
BORL
Borland International
INGR
Intergraph Corp.
INTU
Intuit
MSFT
Microsoft
NOVL
Novell, Inc.
ORCL
512
49
Microsoft
310
512
49
310
13
25
13
28
26
SY
Sybase
Telecommunications
24
22
20
Summary Statistics
Min
Average
Volatility
Close
94.5
80.187
88.486
2.833
Volume
Max
14215.
711.1
5784.4
2879.6
20
:Begin:
:Function:
:Pattern:
:Arguments:
anneal
TSPTour[r:{{_, _}..}]
{First[Transpose[r]], Last[Transpose[r]],
Length[r], Range[Length[r]]}
:ArgumentTypes: {RealList, RealList, Integer, IntegerList}
:ReturnType:
Manual
:End:
In[1]:= Install"anneal";
This installs the
In[2]:=
Out[2]=
In[1]:=
Out[1]:=
In[2]:=
Needs"DatabaseAccess`"
dbselect OpenDataSource"dbselect"
DataSourceObjectdbselect, 1,
DataSourceEvaluatedbselect, SQLSelectSQLTable"publishers",
ShowColumnHeadings True TableForm
Out[2]:=
C program.
10, 7, 34, 30, 46, 40, 43, 38, 65, 57, 28, 23, 80,
78, 94, 6, 92, 32, 18, 26, 98, 56, 31, 97, 37, 45,
Now
program
27 49 11 84 44 96 16 76 82 68
55 the
36 87
pub_id
0736
0877
1389
pub_name
Second Galaxy Books
Boskone & Helmuth
NanoSoft Book Publishers
address
100 1st St.
201 2nd Ave.
TheDr.
data
302 3rd
city
Boston
Washington
canBerkeley
now be
analyzed in Mathematica.
is just like
any Mathematica function.
The Mathematica J/Link system gives you immediate access to any Java library.
Java objects and behaviors are automatically
mapped to Mathematica symbolic functions.
Needs"JLink`"
In[2]:=
PrimeFinder : JavaBlock
Modulefrm, txtField, pane, statusLabel, prevButton, nextButton,
primesVisited ,
InstallJava;
frm JavaNew"com.wolfram.jlink.MathJFrame", "Prime Finder";
frm getContentPane setLayoutJavaNew"java.awt.BorderLayout";
txtField JavaNew"javax.swing.JTextField", "1";
txtField setHorizontalAlignmentJTextField`RIGHT;
txtField addKeyListener JavaNew"com.wolfram.jlink.MathKeyListener",
"keyReleased", "testIfPrime";
pane JavaNew"javax.swing.JPanel";
statusLabel JavaNew"javax.swing.JLabel", "Number is not prime.";
prevButton JavaNew"javax.swing.JButton", "Previous";
prevButton addActionListener
JavaNew"com.wolfram.jlink.MathActionListener", "findPrime1&";
nextButton JavaNew"javax.swing.JButton",Running
"Next";the program brings
nextButton addActionListener
Out[1]:=
In[1]:=
traceTask JavaNew"com.wolfram.net.util.TraceRoute";
traceTask setHost
JavaNew"java.net.URL", "http:www.wolfram.com";
traceTask execute;
This indicates function nesting
"HopCount" traceTask getHopCount,
representing Java object structure.
"HopTimes" traceTask getHopTimes
HopCount 4, HopTimes 0.12, 3.4, 2.1, 0.09
link.putfunction(EvaluatePacket,1)
a computation to a
link.putfunction(Integrate,2)
Mathematica kernel.
link.putfunction(Sqrt,1)
link.PutFunction(EvaluatePacket, 1);
link.putfunction(Log,1)
link.PutFunction(Integrate, 2);
link.putsymbol(x)
link.PutFunction(Sqrt, 1);
link.putsymbol(x)
MLPutFunction( link,
link.PutFunction(Log,
1); EvaluatePacket , 1);
Shorter forms
link.endpacket()
MLPutFunction( link, Integrate, 2);
link.PutSymbol(x);
work in simple
MLPutFunction( link, Sqrt, 1);
link.PutSymbol(x);
link.putFunction(EvaluatePacket,
1);
MLPutFunction(
link,
Log,
1);
Python
cases.
link.EndPacket(); link.putFunction(Integrate, 2);
MLPutSymbol( link, x, 1);
link.putFunction(Sqrt,
1);
MLPutSymbol(
link, x);
link.putFunction(Log,
1);
C#
MLEndPacket( link);
link.evaluate(Integrate[Sqrt[Log[x]], x]);
link.putSymbol(x);
link.putSymbol(x);
C/C++
link.endPacket();
In[1]:=
In[1]:=
Java
Integrate[Sqrt[Log[x]], x]
Mathematica
4, 4]
LinkWrite[link, 15!]
In[2]:=
LinkRead[link]
Out[2]:= 1307674368000
In[3]:=
Out[3]:=
LinkWrite[link, N[%^6]]
LinkRead[link]
5.00032 1072
gridMathematica supports
parallel computation.
In[3]:=
LaunchSlaves;
In[4]:=
RemoteEvaluate $System
Out[4]:=
4, 4]
Link = LinkConnect["8000"]
Out[1]:= LinkObject["8000@frog.wolfram.com",
In[2]:=
In[3]:=
MathLink is supported
for many languages.
link = LinkCreate["8000"]
Out[1]:= LinkObject[8000@frog.wolfram.com,
21
In[1]:=
Out[1]:=
ExportStringx 1, "XML"
?xml versionp'1.0'?
Expression xmlns:mathematicap'
http:www.wolfram.comXML'
xmlnsp'http:www.wolfram.comXML'
Function
Symbol
Plus Symbol
Number
1 Number
Symbol
x Symbol
Function
Expression
<?xml version="1.0"?>
<document>
<!-- CML document - caffeine - karne - 7/8/00 -->
<cml title="caffeine" id="cml_caffeine_karne" xmlns="x-sche
This imports XML as a
<molecule title="caffeine" id="mol_caffeine_karne">
<formula>C8 H10 N4 O2</formula>
In[1]:= mol Import"caffeine.xml"
SymbolicXML expression.
<string title="CAS">58-08-2</string>
Out[1]:= XMLObject
Document
<string title="RTECS">EV6475000</string>
XMLObject
Declaration
Version 1.0,
<float title="molecule weight">194.19</float>
<float title="specific gravity">1.23</float>
XMLElement
document, , XMLElement
cml,
<string title="water solubility" units="g/100
mL" convent
title
caffeine, id cml_caffeine_karne,
<list title="alternate names">
http:www.w3.org2000xmlns, xmlns
<string title="name">1,3,7-Trimethylxanthine</string>
xschema:cml_schema_ie_02.xml,
<string title="name">Cafipel</string>
<string title="name">Guaranine</string> XMLElement
molecule, title caffeine,
id mol_caffeine_karne, ,
</list>
In[2]:= atoms
<atomArray>
Casesmol,
<atom id="caffeine_karne_a_1">
<float builtin="x3" units="A">-2.8709</float>
XMLElement_, _ "elementType", type_ )
<float builtin="y3" units="A">-1.0499</float>
type , 0,
Out[2]:=
In[3]:=
Out[3]:=
C, N, C, C, C, N, N, C, N, C, O,
C, O, C, H, H, H, H, H, H, H, H, H, H
Part 1
This part gives a self-contained introduction to Mathematica,
concentrating on using Mathematica as an interactive problemsolving system.
When you have read this part, you should have sufficient knowledge
of Mathematica to tackle many kinds of practical problems.
You should realize, however, that what is discussed in this part is
in many respects just the surface of Mathematica. Underlying all the various features and capabilities that are discussed, there are powerful and
general principles. These principles are discussed in Part 2. To get the
most out of Mathematica, you will need to understand them.
This part does not assume that you have used a computer before. In
addition, most of the material in it requires no knowledge of mathematics
beyond high-school level. The more advanced mathematical aspects of
Mathematica are discussed in Part 3 of this book.
Part 1
A Practical Introduction to
Mathematica
1.0
Running Mathematica . . . . . . . . . . . . . . . . . . .
26
1.1
Numerical Calculations . . . . . . . . . . . . . . . . . . .
29
1.2
Building Up Calculations . . . . . . . . . . . . . . . . . .
38
1.3
. . . . . . . . . . . . .
44
1.4
Algebraic Calculations . . . . . . . . . . . . . . . . . . .
63
1.5
Symbolic Mathematics . . . . . . . . . . . . . . . . . . .
79
1.6
1.7
1.8
Lists
1.9
1.10
1.11
1.12
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
. . . . . . . . . . . . . . 204
26
mathematica
text ending with SHIFT-ENTER
choose the Quit menu item
27
22
In[1]:=
Out[1]=
22
4
Throughout this book, dialogs with Mathematica are shown in the following way:
With a notebook interface, you just
type in 2 + 2. Mathematica then adds
the label In[1]:=, and prints the
result.
In[1]:= 2 + 2
Out[1]= 4
Page xv discusses some important details about reproducing the dialogs on your computer system.
Section 1.3 gives more information about Mathematica notebooks.
You should realize that notebooks are part of the front end to Mathematica. The Mathematica
kernel which actually performs computations may be run either on the same computer as the front
end, or on another computer connected via some kind of network or line. In most cases, the kernel is
not even started until you actually do a calculation with Mathematica.
To exit Mathematica, you typically choose the Quit menu item in the notebook interface.
With a text-based interface, you interact with your computer primarily by typing text on the keyboard.
To start Mathematica with a text-based interface, you typically type the command math at an operating system prompt. On some systems, you may also be able to start Mathematica with a text-based
interface by double-clicking on a Mathematica Kernel icon.
When Mathematica has started, it will print the prompt In[1]:=, signifying that it is ready for your
input. You can then type your input, ending with ENTER or RETURN.
28
Mathematica will then process the input, and generate a result. If it prints the result out, it will label
it with Out[1]=.
Throughout this book, dialogs with Mathematica are shown in the following way:
The computer prints In[1]:=. You just
type in 2 + 2. The line that starts with
Out[1]= is the result from Mathematica.
In[1]:= 2 + 2
Out[1]= 4
Page xv discusses some important details about reproducing the dialogs on your computer system.
Note that you do not explicitly type the In[n]:= prompt; only type the text that follows this prompt.
Note also that most of the actual dialogs given in the book show output in the form you get with
a notebook interface to Mathematica; output with a text-based interface looks similar, but lacks such
features as special characters and font size changes.
Section 1.3 gives more details on running Mathematica with a text-based interface. To exit Mathematica, either type CONTROL-D, CONTROL-Z or Quit[ ] at an input prompt.
1.1.1 Arithmetic
29
In[3]:= 2 3 4
In[4]:= (3 + 4) ^ 2 - 2 (3 + 1)
Out[2]= 0.0302992
Out[3]= 24
Out[4]= 41
In[5]:= (3+4)^2-2(3+1)
Out[5]= 41
x^y
power
-x
minus
x/y
divide
x y z or x*y*z
x+y+z
multiply
add
Arithmetic operations in Mathematica are grouped according to the standard mathematical conventions. As usual, 2 ^ 3 + 4, for example, means (2 ^ 3) + 4, and not 2 ^ (3 + 4). You can always
control grouping by explicitly using parentheses.
This result is given in scientific
notation.
In[6]:= 2.4 ^ 45
Or like this.
In[8]:= 2.3*^70
30
In[1]:= 2 ^ 100
Out[1]= 1267650600228229401496703205376
You can tell Mathematica to give you an approximate numerical result, just as a calculator would,
by ending your input with //N. The N stands for numerical. It must be a capital letter. Section 2.1.3
will explain what the // means.
This gives an approximate numerical
result.
expr //N
13
Out[3]=
21
Out[4]= 0.619048
When you type in an integer like 7, Mathematica assumes that it is exact. If you type in a number
like 4.5, with an explicit decimal point, Mathematica assumes that it is accurate only to a fixed number
of decimal places.
This is taken to be an exact rational
number, and reduced to its lowest
terms.
In[5]:= 452/62
In[6]:= 452.3/62
In[7]:= 452./62
In[8]:= 1. + 452/62
226
Out[5]=
31
Out[6]= 7.29516
Out[7]= 7.29032
Out[8]= 8.29032
31
Sqrt[x]
square root ( x)
Exp[x]
exponential (ex )
Log[x]
Log[b, x]
Sin[x], Cos[x], Tan[x]
ArcSin[x], ArcCos[x], ArcTan[x]
n!
Abs[x]
Round[x]
Mod[n, m]
Random[ ]
maximum, minimum of x, y,
prime factors of n (see page 750)
It is important to remember that all function arguments in Mathematica are enclosed in square brackets, not parentheses. Parentheses in Mathematica are used only to indicate the grouping of terms, and
never to give function arguments.
This gives loge
. Notice the capital
letter for Log, and the square brackets
for the argument.
In[1]:= Log[8.4]
Out[1]= 2.12823
Just as with arithmetic operations, Mathematica tries to give exact values for mathematical functions
when you give it exact input.
32
This gives
as an exact integer.
In[2]:= Sqrt[16]
Out[2]= 4
In[4]:= Sqrt[2.]
In[5]:= Sqrt[2]
Out[5]=
2
In[6]:= 30!
Out[3]= 1.41421
Out[4]= 1.41421
Out[6]= 265252859812191058636308480000000
Pi
E
Degree
I
Infinity
e (normally output as )
: degrees-to-radians conversion factor (normally output
as )
i (normally output as )
Notice that the names of these built-in constants all begin with capital letters.
This gives the numerical value of .
In[8]:= Pi ^ 2 //N
Out[8]= 9.8696
In[9]:= Sin[Pi/2]
Out[9]= 1
33
In[11]:= Log[E ^ 5]
Out[10]= 0.34202
Out[11]= 5
expr//N or N[expr]
N[expr, n]
In[1]:= N[Pi]
Out[1]= 3.14159
Out[2]= 3.141592653589793238462643383279502884197
Here is
to 30 digits.
Doing any kind of numerical calculation can introduce small roundoff errors into your results.
When you increase the numerical precision, these errors typically become correspondingly smaller.
Making sure that you get the same answer when you increase numerical precision is often a good
way to check your results.
The quantity e
turns out to be
very close to an integer. To check that
the result is not, in fact, an integer, you
have to use sufficient numerical
precision.
34
. Make
If you are using notebooks, you can also enter I as by typing ii (see page 36). The form
is normally what is used in output. Note that an ordinary i means a variable named i, not .
This gives the imaginary number
result i.
In[1]:= Sqrt[-4]
Out[1]= 2
Out[2]= 1 2
In[2]:= (4 + 3 I) / (2 - I)
x+Iy
Re[z]
real part
Im[z]
imaginary part
Conjugate[z]
complex conjugate z or z
Abs[z]
Arg[z]
This section has given you a first glimpse of Mathematica. If you have used other computer systems
before, you will probably have noticed some similarities and some differences. Often you will find
35
the differences the most difficult parts to remember. It may help you, however, to understand a little
about why Mathematica is set up the way it is, and why such differences exist.
One important feature of Mathematica that differs from other computer languages, and from conventional mathematical notation, is that function arguments are enclosed in square brackets, not
parentheses. Parentheses in Mathematica are reserved specifically for indicating the grouping of terms.
There is obviously a conceptual distinction between giving arguments to a function and grouping
terms together; the fact that the same notation has often been used for both is largely a consequence
of typography and of early computer keyboards. In Mathematica, the concepts are distinguished by
different notation.
This distinction has several advantages. In parenthesis notation, it is not clear whether c x
means c[1 + x] or c*(1 + x). Using square brackets for function arguments removes this ambiguity.
It also allows multiplication to be indicated without an explicit * or other character. As a result,
Mathematica can handle expressions like 2x and a x or a (1 + x), treating them just as in standard
mathematical notation.
You will have seen in this section that built-in Mathematica functions often have quite long names.
You may wonder why, for example, the pseudorandom number function is called Random, rather than,
say, Rand. The answer, which pervades much of the design of Mathematica, is consistency. There is a
general convention in Mathematica that all function names are spelled out as full English words, unless
there is a standard mathematical abbreviation for them. The great advantage of this scheme is that it
is predictable. Once you know what a function does, you will usually be able to guess exactly what
its name is. If the names were abbreviated, you would always have to remember which shortening of
the standard English words was used.
Another feature of built-in Mathematica names is that they all start with capital letters. In later
sections, you will see how to define variables and functions of your own. The capital letter convention
makes it easy to distinguish built-in objects. If Mathematica used max instead of Max to represent the
operation of finding a maximum, then you would never be able to use max as the name of one of your
variables. In addition, when you read programs written in Mathematica, the capitalization of built-in
names makes them easier to pick out.
36
You can also give input by using special keys on your keyboard. Pressing one of these keys does
not lead to an ordinary character being entered, but instead typically causes some action to occur or
some structure to be created.
p
inf
the symbol
the symbol
ee
ii
deg
^ or 6
/
@ or 2
(CONTROL-SPACE)
(equivalent to I)
In[1]:= N[Pi^2/6]
Out[1]= 1.64493
2
In[2]:= N
6
Out[2]= 1.64493
In[3]:= N[ p ^ 2 / 6 ]
Out[3]= 1.64493
37
In a traditional computer language such as C, Fortran, Java or Perl, the input you give must always
consist of a string of ordinary characters that can be typed directly on a keyboard. But the Mathematica
language also allows you to give input that contains special characters, superscripts, built-up fractions,
and so on.
The language incorporates many features of traditional mathematical notation. But you should realize that the goal of the language is to provide a precise and consistent way to specify computations.
And as a result, it does not follow all of the somewhat haphazard details of traditional mathematical
notation.
Nevertheless, as discussed on page 193, it is always possible to get Mathematica to produce output
that imitates every aspect of traditional mathematical notation. And as discussed on page 194, it is
also possible for Mathematica to import text that uses such notation, and to some extent to translate it
into its own more precise language.
38
%
%%
%% ... % (k times)
%n
In[1]:= 77 ^ 2
Out[1]= 5929
In[2]:= % + 1
Out[2]= 5930
In[3]:= 3 % + % ^ 2 + %%
Out[3]= 35188619
You will have noticed that all the input and output lines in Mathematica are numbered. You can
use these numbers to refer to previous results.
This adds the results on lines 2 and 3
above.
In[4]:= %2 + %3
Out[4]= 35194549
If you use a text-based interface to Mathematica, then successive input and output lines will always
appear in order, as they do in the dialogs in this book. However, if you use a notebook interface to
Mathematica, as discussed in Section 1.0.1, then successive input and output lines need not appear in
order. You can for example scroll back and insert your next calculation wherever you want in the
notebook. You should realize that % is always defined to be the last result that Mathematica generated.
This may or may not be the result that appears immediately above your present position in the
notebook. With a notebook interface, the only way to tell when a particular result was generated is to
look at the Out[n] label that it has. Because you can insert and delete anywhere in a notebook, the
textual ordering of results in a notebook need have no relation to the order in which the results were
generated.
39
In[1]:= x = 5
In[2]:= x ^ 2
In[3]:= x = 7 + 4
Out[1]= 5
Out[2]= 25
Out[3]= 11
In[5]:= pi
Out[4]= 3.141592653589793238462643383279502884197
Out[5]= 3.141592653589793238462643383279502884197
x = value
x = y = value
x =. or Clear[x]
In[6]:= pi ^ 2
Out[6]= 9.86960440108935861883449099987615113531
It is very important to realize that values you assign to variables are permanent. Once you have
assigned a value to a particular variable, the value will be kept until you explicitly remove it. The
value will, of course, disappear if you start a whole new Mathematica session.
Forgetting about definitions you made earlier is the single most common cause of mistakes when
using Mathematica. If you set x = 5, Mathematica assumes that you always want x to have the value
5, until or unless you explicitly tell it otherwise. To avoid mistakes, you should remove values you
have defined as soon as you have finished using them.
Remove values you assign to variables as soon as you finish using them.
A useful principle in using Mathematica.
40
The variables you define can have almost any names. There is no limit on the length of their
names. One constraint, however, is that variable names can never start with numbers. For example,
x2 could be a variable, but 2x means 2*x.
Mathematica uses both upper- and lower-case letters. There is a convention that built-in Mathematica
objects always have names starting with upper-case (capital) letters. To avoid confusion, you should
always choose names for your own variables that start with lower-case letters.
aaaaa
Aaaaa
Naming conventions.
You can type formulas involving variables in Mathematica almost exactly as you would in mathematics. There are a few important points to watch, however.
x y means x times y.
xy with no space is the variable with name xy.
5x means 5 times x.
x^2y means (x^2) y, not x^(2y).
Some points to watch when using variables in Mathematica.
In[1]:= {3, 5, 1}
Out[1]= 3, 5, 1
41
In[4]:= %
In[5]:= Exp[ % ] // N
Out[5]= 12.1825, 20.0855, 244.692
Just as you can set variables to be numbers, so also you can set them to be lists.
This assigns v to be a list.
In[7]:= v / (v - 1)
4
Out[7]= 2, , 1.47619
{a, b, c}
Part[list, i] or list[[i]]
a list
the ith element of list (the first element is list[[1]])
Out[1]= 8
Out[2]= 6, 5, 6, 8, 9
In[3]:= v = {2, 4, 7}
Out[3]= 2, 4, 7
42
In[4]:= v[[ 2 ]]
Out[4]= 4
By assigning a variable to be a list, you can use Mathematica lists much like arrays in other
computer languages. Thus, for example, you can reset an element of a list by assigning a value to
v[[i]].
Part[v, i] or v[[i]]
Part[v, i] = value or v[[i]] = value
Here is a list.
In[6]:= v[[3]] = 0
Out[6]= 0
In[7]:= v
Out[7]= 4, 1, 0, 7
(term)
f[x]
{a, b, c}
v[[i]]
When the expressions you type in are complicated, it is often a good idea to put extra space
inside each set of brackets. This makes it somewhat easier for you to see matching pairs of brackets.
v[[ {a, b} ]] is, for example, easier to recognize than v[[{a, b}]].
43
In[1]:= x = 4; y = 6; z = y + 6
Out[1]= 12
If you end your input with a semicolon, it is as if you are giving a sequence of operations, with
an empty one at the end. This has the effect of making Mathematica perform the operations you
specify, but display no output.
expr ;
Inhibiting output.
In[2]:= x = 67 - 5 ;
In[3]:= %
Out[3]= 62
44
Mathematica is a modular software system in which the kernel which actually performs computations
is separate from the front end which handles interaction with the user.
The most common type of front end for Mathematica is based on interactive documents known
as notebooks. Notebooks mix Mathematica input and output with text, graphics, palettes and other
material. You can use notebooks either for doing ongoing computations, or as means of presenting or
publishing your results.
Notebook interface
interactive documents
Text-based interface
MathLink interface
The notebook front end includes many menus and graphical tools for creating and reading notebook
documents and for sending and receiving material from the Mathematica kernel.
45
Examples of Integrals
Here is an example of a very simple algebraic integral:
In[1]:=
Out[1]=
1
x
x3 1
12 x
ArcTan
Log
1 x Log
1 x x2
3
3
6
3
-1
-1.5
-2
-2.5
-3
-3.5
1.2
Out[2]=
1.4
1.6
1.8
Graphics
In some cases, you may not need to use the notebook front end, and you may want instead to
interact more directly with the Mathematica kernel. You can do this by using a text-based interface, in
which text you type on the keyboard goes straight to the kernel.
In[1]:= 2^100
Out[1]= 1267650600228229401496703205376
In[2]:= Integrate[1/(x^3 - 1), x]
1 + 2 x
ArcTan[-------]
2
Sqrt[3]
Log[-1 + x]
Log[1 + x + x ]
Out[2]= -(---------------) + ----------- - --------------Sqrt[3]
3
6
An important aspect of Mathematica is that it can interact not only with human users but also with
other programs. This is achieved primarily through MathLink, which is a standardized protocol for
two-way communication between external programs and the Mathematica kernel.
46
MLPutFunction(stdlink,
"EvaluatePacket", 1);
Among the many MathLink-compatible programs that are now available, some are set up to serve as
complete front ends to Mathematica. Often such front ends provide their own special user interfaces,
and treat the Mathematica kernel purely as an embedded computational engine. If you are using
Mathematica in this way, then only some parts of the discussion in the remainder of this section will
probably be relevant.
The commands that you give to the Mathematica kernel, for example, are absolutely identical on
every computer system. This means that when you write a program using these commands, you can
immediately take the program and run it on any computer that supports Mathematica.
47
The structure of Mathematica notebooks is also the same on all computer systems. And as a result,
if you create a notebook on one computer system, you can immediately take it and use it on any other
system.
Although the underlying structure of Mathematica notebooks is always the same, there are often
superficial differences in the way notebooks look on different computer systems, and in some of the
mechanisms provided for interacting with them.
The goal in each case is to make notebooks work in a way that is as familiar as possible to people
who are used to a particular type of computer system.
And in addition, by adapting the details of notebooks to each specific computer system, it becomes
easier to exchange material between notebooks and other programs running on that computer system.
The same Mathematica notebook on
three different computer systems. The
underlying structure is exactly the
same, but some details of the
presentation are different.
One consequence of the modular nature of the Mathematica system is that its parts can be run on
different computers. Thus, for example, it is not uncommon to run the front end for Mathematica on
one computer, while running the kernel on a quite separate computer.
Communications between the kernel and the front end are handled by MathLink, using whatever
networking mechanisms are available.
48
%n or Out[n]
InString[n]
In[n]
With a text-based interface, each line of Mathematica input and output appears sequentially. Often your computer system will allow you to scroll backwards to review previous work, and to
cut-and-paste previous lines of input.
But whatever kind of computer system you have, you can always use Mathematica to retrieve or
re-evaluate previous input and output. In general, re-evaluating a particular piece of input or output
may give you a different result than when you evaluated it in the first place. The reason is that in
between you may have reset the values of variables that are used in that piece of input or output. If
you ask for Out[n], then Mathematica will give you the final form of your nth output. On the other
hand, if you ask for In[n], then Mathematica will take the nth input you gave, and re-evaluate it using
whatever current assignments you have given for variables.
49
Here is a factorial:
In[1]:=
Out[1]=
In[2]:=
Out[2]=
100
933262154439441526816992388562667004907159682643816214685929638952
17599993229915608941463976156518286253697920827223758251185210916
864000000000000000000000000
N%
9.33262 10157
-2
-5
-10
Out[3]=
Graphics
Mathematica notebooks are structured interactive documents that are organized into a sequence of
cells. Each cell contains material of a definite typeusually text, graphics, sounds or Mathematica
expressions. When a notebook is displayed on the screen, the extent of each cell is indicated by a
bracket on the right.
The notebook front end for Mathematica provides many ways to enter and edit the material in a
notebook. Some of these ways will be standard to whatever computer system or graphical interface
you are using. Others are specific to Mathematica.
SHIFT-ENTER or SHIFT-RETURN
Once you have prepared the material in a cell, you can send it as input to the Mathematica kernel
simply by pressing SHIFT-ENTER or SHIFT-RETURN. The kernel will send back whatever output is generated, and the front end will create new cells in your notebook to display this output. Note that if
you have a numeric keypad on your keyboard, then you can use its ENTER key as an alternative to
SHIFT-ENTER.
50
3 ^ 100
In[1]:=
3 ^ 100
Out[1]=
515377520732011331036461129765621272702107522001
Most kinds of output that you get in Mathematica notebooks can readily be edited, just like input.
Usually Mathematica will make a copy of the output when you first start editing it, so you can keep
track of the original output and its edited form.
Once you have done the editing you want, you can typically just press SHIFT-ENTER to send what
you have created as input to the Mathematica kernel.
Here is a typical computation in a
Mathematica notebook.
In[1]:=
Out[1]=
1 x
1 x 1 x 2 ArcSinh
2
In[1]:=
Out[1]=
1 x
1 x 1 x 2 ArcSinh
2
1 x
In[1]:=
Out[1]=
1 x
1 x 1 x 2 ArcSinh
2
In[2]:=
1 x
Out[2]=
x2
1 x 1 x
When you do computations in a Mathematica notebook, each line of input is typically labeled with
In[n]:=, while each line of output is labeled with the corresponding Out[n]=.
There is no reason, however, that successive lines of input and output should necessarily appear
one after the other in your notebook. Often, for example, you will want to go back to an earlier part
of your notebook, and re-evaluate some input you gave before.
It is important to realize that wherever a particular expression appears in your notebook, it is
the line number given in In[n]:= or Out[n]= which determines when the expression was processed
by the Mathematica kernel. Thus, for example, the fact that one expression may appear earlier than
51
another in your notebook does not mean that it will have been evaluated first by the kernel. This will
only be the case if it has a lower line number.
Each line of input and output is given
a label when it is evaluated by the
kernel. It is these labels, not the
position of the expression in the
notebook, that indicate the ordering of
evaluation by the kernel.
Results:
In[2]:=
s^2 2
Out[2]=
146
In[4]:=
s^2 2
Out[4]=
10002
Settings for s:
In[1]:=
s 12
Out[1]=
12
In[3]:=
s 100
Out[3]=
100
If you make a mistake and try to enter input that the Mathematica kernel does not understand, then
the front end will produce a beep. In general, you will get a beep whenever something goes wrong in
the front end. You can find out the origin of the beep using the Why the Beep? item in the Help menu.
Animate graphics
Resize a graphic
52
Section heading
Subsection heading
Text within a subsection.
More text.
Another subsection
Text within the second subsection.
A group of cells can be either open or closed. When it is open, you can see all the cells in it explicitly.
But when it is closed, you see only the first or heading cell in the group.
Large notebooks are often distributed with many closed groups of cells, so that when you first look
at the notebook, you see just an outline of its contents. You can then open parts you are interested in
by double-clicking the appropriate brackets.
Double-clicking the bracket that spans
a group of cells closes the group,
leaving only the first cell visible.
Section heading
Subsection heading
Another subsection
Section heading
Subsection heading
Text within a subsection.
More text.
Another subsection
Each cell within a notebook is assigned a particular style which indicates its role within the notebook. Thus, for example, material intended as input to be executed by the Mathematica kernel is
typically in Input style, while text that is intended purely to be read is typically in Text style.
The Mathematica front end provides menus and keyboard shortcuts for creating cells with different
styles, and for changing styles of existing cells.
53
By putting a cell in a particular style, you specify a whole collection of properties for the cell,
including for example how large and in what font text should be given.
The Mathematica front end allows you to modify such properties, either for complete cells, or for
specific material within cells.
Even within a cell of a particular style,
the Mathematica front end allows a
wide range of properties to be
modified separately.
It is worth realizing that in doing different kinds of things with Mathematica notebooks, you are
using different parts of the Mathematica system. Operations such as opening and closing groups of
cells, doing animations and playing sounds use only a small part of the Mathematica front end, and
these operations are supported by a widely available program known as MathReader.
To be able to create and edit notebooks, you need more of the Mathematica front end. And finally,
to be able to actually do computations within a Mathematica notebook, you need a full Mathematica
system, with both the front end and the kernel.
MathReader
Mathematica front end
Mathematica kernel
54
Later in this book, we will discuss how you can set up buttons and other similar objects in Mathematica notebooks. But here suffice it to say that whenever a cell is indicated as active, typically by
the presence of a stylized A in its cell bracket, clicking on active elements within the cell will cause
actions that have been programmed for these elements to be performed.
It is common to set up palettes which consist of arrays of buttons. Sometimes such palettes appear
as cells within a notebook. But more often, a special kind of separate notebook window is used,
which can conveniently be placed on the side of your computer screen and used in conjunction with
any other notebook.
Palettes consisting of arrays of buttons
are often placed in separate notebooks.
In the simplest cases, the buttons in palettes serve essentially like additional keys on your keyboard.
Thus, when you press a button, the character or object shown in that button is inserted into your
notebook just as if you had typed it.
Here is a palette of Greek letters with
buttons that act like additional keys on
your keyboard.
+
/ 0 1
2 3 4 5 6
55
Often, however, a button may contain a placeholder indicated by . This signifies that when you
press the button, whatever is currently selected in your notebook will be inserted at the position of
the placeholder.
The buttons here contain placeholders
indicated by .
2
14 4
1 1 1 1 x2
2 2
1
1 1 1 x2
2
2 2
Sometimes buttons that contain placeholders will be programmed simply to insert a certain expression in your notebook. But more often, they will be programmed to evaluate the result, sending it as
input to the Mathematica kernel.
These buttons are set up to perform
algebraic operations.
Simplify
FullSimplify
Expand
Factor
Apart
Together
2 2 Cos2 x
1
12 16 Cos2 x 4 Cos4 x
4
32
2 2 Cos2 x
Sinx4
4
There are some situations in which it is convenient to have several placeholders in a single button.
Your current selection is typically inserted at the position of the primary placeholder, indicated by
. Additional placeholders may however be indicated by , and you can move to the positions of
successive placeholders using TAB.
Here is a palette containing buttons
with several placeholders.
7
8
7 8,
56
Sinx
1x
Sinx
x
1x
Here is some text. The text can contain a link, which points elsewhere.
Hyperlinks in notebooks work very much like the buttons discussed in the previous section. And
once again, all aspects of hyperlinks are programmable.
Indeed, it is possible to set up active text in notebooks that performs almost any kind of action.
57
Getting Started
Built-in Functions
The Mathematica Book
Master Index
If you type the name of a function into a notebook, most versions of the front end allow you immediately to find information about the function by pressing an appropriate key (F1 under Windows).
When you first start Mathematica, you will typically be presented with a basic tutorial. You can visit
the tutorial again with the Tutorial menu item in the Help menu.
58
In[1]:= ?Log
Log[z] gives the natural logarithm of z (logarithm to base
e). Log[b, z] gives the logarithm to base b.
You can ask for information about any object, whether it is built into Mathematica, has been read in
from a Mathematica package, or has been introduced by you.
When you use ? to get information, you must make sure that the question mark appears as the first
character in your input line. You need to do this so that Mathematica can tell when you are requesting
information rather than giving ordinary input for evaluation.
You can get extra information by using
??. Attributes will be discussed in
Section 2.6.3.
In[2]:= ??Log
Log[z] gives the natural logarithm of z (logarithm to base
e). Log[b, z] gives the logarithm to base b.
Attributes[Log] = {Listable, NumericFunction, Protected}
In[3]:= ?Lo*
Locked
Log
LogGamma
LogIntegral
LogicalExpand LongForm
Loopback
LowerCaseQ
?Aaaa will give you information on the particular object whose name you specify. Using the
metacharacter *, however, you can get information on collections of objects with similar names. The
rule is that * is a wild card that can stand for any sequence of ordinary characters. So, for example,
?Lo* gets information on all objects whose names consist of the letters Lo, followed by any sequence
of characters.
You can put * anywhere in the string you ask ? about. For example, ?*Expand would give you
all objects whose names end with Expand. Similarly, ?x*0 would give you objects whose names start
with x, end with 0, and have any sequence of characters in between. (You may notice that the way
you use * to specify names in Mathematica is similar to the way you use * in Unix and other operating
systems to specify file names.)
You can ask for information on most of
the special input forms that
Mathematica uses. This asks for
information about the := operator.
In[4]:= ?:=
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.
59
<<package
If you want to use functions from a particular package, you must first read the package into Mathematica. The details of how to do this are discussed in Section 1.11. There are various conventions that
govern the names you should use to refer to packages.
This command reads in a particular
Mathematica package.
In[2]:= Subfactorial[10]
Out[2]= 1334961
There are a number of subtleties associated with such issues as conflicts between names of functions
in different packages. These are discussed in Section 2.7.9. One point to note, however, is that you
must not refer to a function that you will read from a package before actually reading in the package.
If you do this by mistake, you will have to execute the command Remove["name"] to get rid of the
function before you read in the package which defines it. If you do not call Remove, Mathematica will
use your version of the function, rather than the one from the package.
Remove["name"]
The fact that Mathematica can be extended using packages means that the boundary of exactly what
is part of Mathematica is quite blurred. As far as usage is concerned, there is actually no difference
between functions defined in packages and functions that are fundamentally built into Mathematica.
60
In fact, a fair number of the functions described in this book are actually implemented as Mathematica packages. However, on most Mathematica systems, the necessary packages have been preloaded,
so that the functions they define are always present.
To blur the boundary of what is part of Mathematica even further, Section 2.7.11 describes how
you can tell Mathematica automatically to load a particular package if you ever try to use a certain
function. If you never use that function, then it will not be present. But as soon as you try to use it,
its definition will be read in from a Mathematica package.
As a practical matter, the functions that should be considered part of Mathematica are probably
those that are present in all Mathematica systems. It is these functions that are primarily discussed in
this book.
Nevertheless, most versions of Mathematica come with a standard set of Mathematica packages,
which contain definitions for many more functions. Some of these functions are mentioned in this
book. But to get them, you must usually read in the necessary packages explicitly.
You can use the Help Browser to get
information on standard Mathematica
add-on packages.
It is possible to set your Mathematica system up so that particular packages are pre-loaded, or are
automatically loaded when needed. If you do this, then there may be many functions that appear as
standard in your version of Mathematica, but which are not documented in this book.
One point that should be mentioned is the relationship between packages and notebooks. Both are
stored as files on your computer system, and both can be read into Mathematica. However, a notebook
61
is intended to be displayed, typically with a notebook interface, while a package is intended only
to be used as Mathematica input. Many notebooks in fact contain sections that can be considered as
packages, and which contain sequences of definitions intended for input to Mathematica. There are
also capabilities that allow packages set up to correspond to notebooks to be maintained automatically.
In[1]:= Sqrt[4, 5]
In[2]:= Off[Sqrt::argx]
In[3]:= Sqrt[4, 5]
In[4]:= On[Sqrt::argx]
Off[Function::tag]
On[Function::tag]
Functions for controlling message output.
Sqrt::argx:
Sqrt called with 2 arguments; 1 argument is expected.
Out[1]= Sqrt 4, 5
Out[3]= Sqrt 4, 5
62
ALT-COMMA or COMMAND-COMMA
CONTROL-C
notebook interfaces
text-based interfaces
On some computer systems, it may take Mathematica some time to respond to your interrupt. When
Mathematica does respond, it will typically give you a menu of possible things to do.
continue
show
inspect
abort
exit
63
In[1]:= 3 + 62 - 1
In[2]:= 3x - x + 2
Out[1]= 64
Out[2]= 2 2 x
Numerical computation
3 + 62 - 1
64
Symbolic computation
3x - x + 2
2+2x
In[3]:= -1 + 2x + x^3
Out[3]= 1 2 x x3
Out[4]= x 3 x2
You can type in any algebraic expression, using the operators listed on page 29. You can use spaces
to denote multiplication. Be careful not to forget the space in x y. If you type in xy with no space,
Mathematica will interpret this as a single symbol, with the name xy, not as a product of the two
symbols x and y.
Mathematica rearranges and combines
terms using the standard rules of
algebra.
Out[5]= x y 2 x2 y x2 y2
Out[6]= 2 x 1 x 2 y
In[7]:= Expand[%]
In[8]:= Factor[%]
Out[7]= 4 3 x2 x3 8 y 8 x y 2 x2 y
Out[8]= 2 x 1 x 2 y
64
When you type in more complicated expressions, it is important that you put parentheses in the
right places. Thus, for example, you have to give the expression x
y in the form x^(4y). If you leave
out the parentheses, you get x
y instead. It never hurts to put in too many parentheses, but to find
out exactly when you need to use parentheses, look at Section A.2.
Here is a more complicated formula,
requiring several parentheses.
When you type in an expression, Mathematica automatically applies its large repertoire of rules for
transforming expressions. These rules include the standard rules of algebra, such as x x , together
with much more sophisticated rules involving higher mathematical functions.
Mathematica uses standard rules of
algebra to replace x
by x .
Out[10]= 1 x
The notion of transformation rules is a very general one. In fact, you can think of the whole of
Mathematica as simply a system for applying a collection of transformation rules to many different
kinds of expressions.
The general principle that Mathematica follows is simple to state. It takes any expression you input,
and gets results by applying a succession of transformation rules, stopping when it knows no more
transformation rules that can be applied.
Take any expression, and apply transformation rules until the result no longer changes.
The fundamental principle of Mathematica.
65
To apply a transformation rule to a particular Mathematica expression, you type expr /. rule. The
replacement operator /. is typed as a pair of characters, with no space in between.
This uses the transformation rule x->3
in the expression 1 + 2x.
In[1]:= 1 + 2x /. x -> 3
In[3]:= x -> 3 + y
In[4]:= x^2 - 9 /. %
Out[1]= 7
Out[2]= 3 2 y y
Out[3]= x 3 y
Out[4]= 9 3 y
Out[5]= 4 a 2 a
The replacement operator /. allows you to apply transformation rules to a particular expression.
Sometimes, however, you will want to define transformation rules that should always be applied. For
example, you might want to replace x with 3 whenever x occurs.
As discussed in Section 1.2.2, you can do this by assigning the value 3 to x using x = 3. Once you
have made the assignment x = 3, x will always be replaced by 3, whenever it appears.
This assigns the value 3 to x.
In[6]:= x = 3
Out[6]= 3
In[7]:= x^2 - 1
In[8]:= x = 1 + a
Now x is replaced by 1 + a.
In[9]:= x^2 - 1
Out[7]= 8
Out[8]= 1 a
Out[9]= 1 1 a
You can define the value of a symbol to be any expression, not just a number. You should realize
that once you have given such a definition, the definition will continue to be used whenever the
66
symbol appears, until you explicitly change or remove the definition. For most people, forgetting to
remove values you have assigned to symbols is the single most common source of mistakes in using
Mathematica.
x = value
x =.
In[10]:= x + 5 - 2x
In[11]:= x =.
In[12]:= x + 5 - 2x
Out[10]= 6 a 2 1 a
Out[12]= 5 x
A symbol such as x can serve many different purposes in Mathematica, and in fact, much of the
flexibility of Mathematica comes from being able to mix these purposes at will. However, you need to
keep some of the different uses of x straight in order to avoid making mistakes. The most important
distinction is between the use of x as a name for another expression, and as a symbolic variable that
stands only for itself.
Traditional programming languages that do not support symbolic computation allow variables to
be used only as names for objects, typically numbers, that have been assigned as values for them. In
Mathematica, however, x can also be treated as a purely formal variable, to which various transformation rules can be applied. Of course, if you explicitly give a definition, such as x = 3, then x will
always be replaced by 3, and can no longer serve as a formal variable.
You should understand that explicit definitions such as x = 3 have a global effect. On the other
hand, a replacement such as expr /. x->3 affects only the specific expression expr. It is usually much
easier to keep things straight if you avoid using explicit definitions except when absolutely necessary.
You can always mix replacements with assignments. With assignments, you can give names to
expressions in which you want to do replacements, or to rules that you want to use to do the
replacements.
This assigns a value to the symbol t.
In[13]:= t = 1 + x^2
Out[13]= 1 x2
In[14]:= t /. x -> 2
Out[14]= 5
67
In[15]:= t /. x -> 5a
Out[15]= 1 25 a2
Out[16]= 10.8696
Expand[expr]
Factor[expr]
In[2]:= Factor[ % ]
Out[1]= 1 2 x x2
Out[2]= 1 x
In[4]:= Factor[ % ]
In[6]:= Expand[ % ]
Out[3]= 1 4 x 6 x2 4 x3 x4 12 y 36 x y 36 x2 y 12 x3 y
54 y2 108 x y2 54 x2 y2 108 y3 108 x y3 81 y4
Out[4]= 1 x 3 y
Out[5]= 1 x 1 x 1 x x2 x3 x4 1 x x2 x3 x4
Out[6]= 1 x10
68
Simplify[expr]
FullSimplify[expr]
In[1]:= Simplify[x^2 + 2x + 1]
2
Out[1]= 1 x
In[2]:= Simplify[x^10 - 1]
Out[2]= 1 x10
You can often use Simplify to clean up complicated expressions that you get as the results of
computations.
Here is the integral of x
.
Integrals are discussed in more detail
in Section 1.5.3.
In[3]:= Integrate[1/(x^4-1), x]
1
Out[3]= 2 ArcTan
x Log
1 x Log
1 x
4
In[4]:= D[%, x]
In[5]:= Simplify[%]
1
1
1
2
Out[4]=
4 1 x 1 x 1 x2
1
Out[5]=
1 x4
Simplify is set up to try various standard algebraic transformations on the expressions you give.
Sometimes, however, it can take more sophisticated transformations to make progress in finding the
simplest form of an expression.
FullSimplify tries a much wider range of transformations, involving not only algebraic functions,
but also many other kinds of functions.
Simplify does nothing to this
expression.
69
For fairly small expressions, FullSimplify will often succeed in making some remarkable simplifications. But for larger expressions, it can become unmanageably slow.
The reason for this is that to do its job, FullSimplify effectively has to try combining every part of
an expression with every other, and for large expressions the number of cases that it has to consider
can be astronomically large.
Simplify also has a difficult task to do, but it is set up to avoid some of the most time-consuming
transformations that are tried by FullSimplify . For simple algebraic calculations, therefore, you may
often find it convenient to apply Simplify quite routinely to your results.
In more complicated calculations, however, even Simplify, let alone FullSimplify , may end up
needing to try a very large number of different forms, and therefore taking a long time. In such cases,
you typically need to do more controlled simplification, and use your knowledge of the form you
want to get to guide the process.
Expand[expr]
ExpandAll[expr]
Factor[expr]
Together[expr]
Apart[expr]
Cancel[expr]
Simplify[expr]
Functions for transforming algebraic expressions.
70
1 x 2 x
Out[1]=
2
3 x 1 x
In[2]:= Expand[e]
In[3]:= ExpandAll[e]
In[4]:= Together[%]
In[5]:= Apart[%]
In[6]:= Factor[%]
In[7]:= Simplify[e]
3x
x3
2
Out[2]=
2
2
2
3 x 1 x 3 x 1 x 3 x 1 x
3x
x3
2
Out[3]=
2
3
2
3
93x5x x
9 3 x 5 x2 x3
93x5x x
2 3 x x3
Out[4]=
2
3 x 1 x
5
19
1
Out[5]= 1
2
4
3
x
4
1
x
3 x
1 x 2 x
Out[6]=
2
3 x 1 x
1 x 2 x
Out[7]=
2
3 x 1 x
Getting expressions into the form you want is something of an art. In most cases, it is best simply
to experiment, trying different transformations until you get what you want. Often you will be able
to use palettes in the front end to do this.
When you have an expression with a single variable, you can choose to write it as a sum of terms, a
product, and so on. If you have an expression with several variables, there is an even wider selection
of possible forms. You can, for example, choose to group terms in the expression so that one or
another of the variables is dominant.
Collect[expr, x]
FactorTerms[expr, x]
Rearranging expressions in several variables.
In[9]:= Collect[v, x]
In[10]:= Collect[v, y]
71
Out[8]= 9 x2 12 x3 4 x4 36 x y
48 x2 y 16 x3 y 36 y2 48 x y2 16 x2 y2
Out[9]= 4 x4 36 y2 x3 12 16 y
x2 9 48 y 16 y2 x 36 y 48 y2
Out[10]= 9 x2 12 x3 4 x4
36 x 48 x2 16 x3 y 36 48 x 16 x2 y2
In[11]:= FactorTerms[v, y]
Out[11]= 9 12 x 4 x2 x2 4 x y 4 y2
As we have seen, even when you restrict yourself to polynomials and rational expressions, there
are many different ways to write any particular expression. If you consider more complicated expressions, involving, for example, higher mathematical functions, the variety of possible forms becomes
still greater. As a result, it is totally infeasible to have a specific function built into Mathematica to
produce each possible form. Rather, Mathematica allows you to construct arbitrary sets of transformation rules for converting between different forms. Many Mathematica packages include such rules; the
details of how to construct them for yourself are given in Section 2.5.
There are nevertheless a few additional built-in Mathematica functions for transforming expressions.
TrigExpand[expr]
TrigFactor[expr]
TrigReduce[expr]
TrigToExp[expr]
ExpToTrig[expr]
FunctionExpand[expr]
ComplexExpand[expr]
PowerExpand[expr]
3
Tan
x 1
2
Out[12]= Cos
x Sin
x Sin
x Tan
x
2
2
2
72
In[13]:= TrigFactor[%]
In[14]:= TrigReduce[%]
1
Out[14]= Sec
x Sin
x Sin
3 x
2
The transformations on expressions done by functions like Expand and Factor are always correct,
whatever values the symbolic variables in the expressions may have. Sometimes, however, it is useful
to perform transformations that are only correct for some possible values of symbolic variables. One
such transformation is performed by PowerExpand .
Mathematica does not automatically
expand out non-integer powers of
products.
In[17]:= Sqrt[x y]
Out[17]=
xy
In[18]:= PowerExpand[%]
Out[18]=
x y
In[1]:= Simplify[Sqrt[x^2]]
Out[1]=
x2
Out[2]= 4, 4
Out[3]= x
Out[4]= 2 a 2
a b
a b
Out[6]= x
Element[x, dom]
Element[{x , x , ... }, dom]
Reals
Integers
Primes
This simplifies
a real number.
x assuming that x is
Out[8]= Sin x
Out[9]= Mod a, p
73
74
In[2]:= Coefficient[e, x]
Out[2]= 6 24 y2
In[3]:= Exponent[e, y]
In[4]:= Part[e, 4]
Out[3]= 4
Out[4]= 8 y2
You may notice that the function Part[expr, n] used to pick out the nth term in a sum is the same as
the function described in Section 1.2.4 for picking out elements in lists. This is no coincidence. In fact,
as discussed in Section 2.1.5, every Mathematica expression can be manipulated structurally much like
a list. However, as discussed in Section 2.1.5, you must be careful, because Mathematica often shows
algebraic expressions in a form that is different from the way it treats them internally.
Coefficient works even with
polynomials that are not explicitly
expanded out.
Numerator[expr]
Denominator[expr]
numerator of expr
denominator of expr
1x
Out[6]=
2 2 y
In[7]:= Denominator[%]
Out[7]= 2 2 y
Out[8]= 1
75
Even though you may not want to see the whole result from a computation, you often do need to
see its basic form. You can use Short to display the outline of an expression, omitting some of the
terms.
Ending your input with ; stops
Mathematica from displaying the
complicated result of the computation.
In[2]:= % //Short
In[3]:= Short[%, 3]
In[4]:= Length[%]
command ;
expr // Short
Short[expr, n]
Out[4]= 45
76
result is small, the intermediate parts of a calculation can be too big for your computer to handle. If
this happens, you can usually break your calculation into pieces, and succeed in doing each piece on
its own. You should know that the internal scheme which Mathematica uses for memory management
is such that once part of a calculation is finished, the memory used to store intermediate expressions
that arose is immediately made available for new expressions.
Memory space is the most common limiting factor in Mathematica calculations. Time can also,
however, be a limiting factor. You will usually be prepared to wait a second, or even a minute, for
the result of a calculation. But you will less often be prepared to wait an hour or a day, and you will
almost never be able to wait a year.
The internal code of Mathematica uses highly efficient and optimized algorithms. But there are some
tasks for which the best known algorithms always eventually take a large amount of time. A typical
issue is that the time required by the algorithm may increase almost exponentially with the size of the
input. A classic case is integer factorizationwhere the best known algorithms require times that grow
almost exponentially with the number of digits. In practice, you will find that FactorInteger[k]
will give a result almost immediately when k has fewer than about 40 digits. But if k has 60 digits,
FactorInteger[k] can start taking an unmanageably long time.
In some cases, there is progressive improvement in the algorithms that are known, so that successive versions of Mathematica can perform particular computations progressively faster. But ideas from
the theory of computation strongly suggest that many computations will always in effect require an
irreducible amount of computational workso that no fast algorithm for them will ever be found.
Whether or not the only algorithms involve exponentially increasing amounts of time, there will
always come a point where a computation is too large or time-consuming to do on your particular
computer system. As you work with Mathematica, you should develop some feeling for the limits on
the kinds of calculations you can do in your particular application area.
77
78
In[1]:= 12 meters
Out[1]= 12 meters
0.692 meters
Out[3]=
seconds
This converts to a speed in feet per
second.
2.27034 feet
Out[4]=
seconds
There is in fact a standard Mathematica package that allows you to work with units. The package
defines many symbols that represent standard types of units.
Load the Mathematica package for
handling units.
In[5]:= <<Miscellaneous`Units`
In[6]:= 12 Meter/Second
12 Meter
Out[6]=
Second
37500 Mile
Out[7]=
1397 Hour
250000 Inch
Out[8]=
127 Minute
1.5.2 Differentiation
79
Mathematicas ability to deal with symbolic expressions, as well as numbers, allows you to use it for
many kinds of mathematics.
Calculus is one example. With Mathematica, you can differentiate an expression symbolically, and
get a formula for the result.
This finds the derivative of xn .
In[1]:= D[ x^n, x ]
Out[1]= n x1n
D[f, x]
Integrate[f, x]
Sum[f, {i, imin, imax}]
Solve[lhs==rhs, x]
Series[f, {x, x , order}]
Limit[f, x->x ]
,
Minimize[f, x]
x2
Out[2]= 2 x Log
a x
ax
"f
"x
Getting formulas as the results of computations is usually desirable when it is possible. There
are however many circumstances where it is mathematically impossible to get an explicit formula
as the result of a computation. This happens, for example, when you try to solve an equation for
which there is no closed form solution. In such cases, you must resort to numerical methods and
approximations. These are discussed in Section 1.6.
1.5.2 Differentiation
Here is the derivative of xn with
respect to x.
In[1]:= D[ x^n, x ]
Out[1]= n x1n
80
In[2]:= D[ ArcTan[x], x ]
1
Out[2]=
1 x2
Out[3]= 2 n 1 n n x3n
The function D[x^n, x] really gives a partial derivative, in which n is assumed not to depend on x.
Mathematica has another function, called Dt, which finds total derivatives, in which all variables are
"f
df
assumed to be related. In mathematical notation, D[f, x] is like "x , while Dt[f, x] is like dx . You can
think of Dt as standing for derivative total.
Dt gives a total derivative, which
assumes that n can depend on x.
Dt[n, x] stands for dn
.
dx
D[f, x]
D[f, x , x , ... ]
D[f, {x, n}]
Dt[f]
Dt[f, x]
n Dt
x
Out[5]= xn Dt
n Log
x
x
partial derivative
"
"x
multiple derivative
repeated derivative
f
" "
"x "x
"n f
"xn
total differential df
total derivative
d
dx
As well as treating variables like x symbolically, you can also treat functions in Mathematica symbolically. Thus, for example, you can find formulas for derivatives of f[x], without specifying any
explicit form for the function f.
Mathematica does not know how to
differentiate f, so it gives you back a
symbolic result in terms of f'.
In[6]:= D[ f[x], x ]
In[7]:= D[ 2 x f[x^2], x ]
Out[6]= f< x
Out[7]= 2 f x2 4 x2 f< x2
1.5.3 Integration
81
1.5.3 Integration
Here is the integral xn dx in
Mathematica.
In[1]:= Integrate[x^n, x]
x1n
Out[1]=
1n
Mathematica knows how to do almost any integral that can be done in terms of standard mathematical
functions. But you should realize that even though an integrand may contain only fairly simple
functions, its integral may involve much more complicated functionsor may not be expressible at
all in terms of standard mathematical functions.
Here is a fairly straightforward
integral.
1
Out[4]= PolyLog
2, x2
2
1
Out[5]= Erf
x
2
And this one involves a Fresnel
function.
In[6]:= Integrate[Sin[x^2], x]
2
Out[6]=
FresnelS
x
2
1
3
Out[7]= x Hypergeometric2F1 , n, , x2
2
2
Out[8]= xx 7x
82
Integrate[f, x]
Integrate[f, x, y]
xmax
dx.
1
Out[9]= a b Cos
a Sin
a Cos
b Sin
b
2
In[10]:= Integrate[Exp[-x^2], {x, 0, Infinity}]
Out[10]=
2
Mathematica cannot give you a formula
for this definite integral.
Out[11]= xx 7x
0
In[12]:= N[ % ]
1
Out[13]=
3
x
dx dy x
Out[12]= 0.783431
x2
x3
x4
x5
x6
x7
Out[1]= x
2
3
4
5
6
7
You can leave out the lower limit if it
is equal to 1.
x2
x3
x4
x5
x6
x7
Out[2]= x
2
3
4
5
6
7
x3
x5
Out[3]= x
3
5
83
1
Out[5]= n 1 n 1 2 n
6
4
Out[6]=
90
2 x14 EllipticTheta
2, 0, x
Out[7]=
2 x14
1
Out[8]=
i 9 2 i9
i=1
In[9]:= N[%]
Out[9]= 0.373197
The way the ranges of variables are specified in Sum and Product is an example of the rather general
iterator notation that Mathematica uses. You will see this notation again when we discuss generating
tables and lists using Table (Section 1.8.2), and when we describe Do loops (Section 1.7.3).
84
{imax}
{i, imax}
1.5.5 Equations
Section 1.2.2 discussed assignments such as x = y which set x equal to y. This section discusses equations,
which test equality. The equation x == y tests whether x is equal to y.
This tests whether 2 + 2 and 4 are
equal. The result is the symbol True.
In[1]:= 2 + 2 == 4
Out[1]= True
It is very important that you do not confuse x = y with x == y. While x = y is an imperative statement that actually causes an assignment to be done, x == y merely tests whether x and y are equal,
and causes no explicit action. If you have used the C programming language, you will recognize that
the notation for assignment and testing in Mathematica is the same as in C.
x=y
x == y
In[2]:= x = 4
Out[2]= 4
In[3]:= x
Out[3]= 4
In[4]:= x == 4
x is equal to 4, not 6.
In[5]:= x == 6
Out[4]= True
Out[5]= False
In[6]:= x =.
1.5.5 Equations
85
The tests we have used so far involve only numbers, and always give a definite answer, either True
or False. You can also do tests on symbolic expressions.
Mathematica cannot get a definite result
for this test unless you give x a
specific numerical value.
In[7]:= x == 5
In[8]:= % /. x -> 4
Out[7]= x 5
Out[8]= False
Even when you do tests on symbolic expressions, there are some cases where you can get definite
results. An important one is when you test the equality of two expressions that are identical. Whatever the numerical values of the variables in these expressions may be, Mathematica knows that the
expressions must always be equal.
The two expressions are identical, so
the result is True, whatever the value
of x may be.
In[10]:= 2 x + x^2 == x (2 + x)
Out[9]= True
Out[10]= 2 x x2 x 2 x
Expressions like x == 4 represent equations in Mathematica. There are many functions in Mathematica
for manipulating and solving equations.
This is an equation in Mathematica.
Subsection 1.5.7 will discuss how to
solve it for x.
In[11]:= x^2 + 2 x - 7 == 0
In[12]:= eqn = %
Out[11]= 7 2 x x2 0
Out[12]= 7 2 x x2 0
In[13]:= eqn
Out[13]= 7 2 x x2 0
86
x != y
x>y
x >= y
x<y
x <= y
greater than
greater than or equal to (also input as x y)
less than
less than or equal to (also input as x y)
x == y == z
all equal
x != y != z
Relational operators.
In[1]:= 10 < 7
Out[1]= False
In[2]:= 3 != 2 != 3
Out[2]= False
Out[3]= True
In[5]:= x > y
Out[4]= True
Out[5]= x > y
87
!p
p && q && ...
p || q || ...
Xor[p, q, ... ]
,
Logical operations.
You should remember that the logical operations ==, && and || are all double characters in Mathematica.
If you have used a programming language such as C, you will be familiar with this notation.
In[7]:= p && q
In[9]:= LogicalExpand[ % ]
Out[7]= p && q
Out[8]= p q && 9 r s
In[1]:= Solve[x^2 + 2x - 7 == 0, x]
Out[1]=
x 1 2 2 !, x 1 2 2 !!
In[2]:= N[ % ]
Out[2]= x 3.82843, x 1.82843
88
In[3]:= x /. %
In[4]:= x^2 + 3 x /. %%
Solve[lhs == rhs, x]
x /. solution
expr /. solution
Solve always tries to give you explicit formulas for the solutions to equations. However, it is a basic
mathematical result that, for sufficiently complicated equations, explicit algebraic formulas cannot be
given. If you have an algebraic equation in one variable, and the highest power of the variable is at
most four, then Mathematica can always give you formulas for the solutions. However, if the highest
power is five or more, it may be mathematically impossible to give explicit algebraic formulas for all
the solutions.
Mathematica can always solve algebraic
equations in one variable when the
highest power is less than five.
5
37
5
37
Out[5]= x
, x
,
2
2
2
2
1
1
x
5 37
, x
5 37
2
2
In[6]:= Solve[x^6 == 1, x]
Out[6]=
13
x 1
There are some equations, however, for
which it is mathematically impossible
to find explicit formulas for the
solutions. Mathematica uses Root
objects to represent the solutions in this
case.
23
!, x 1
!,
23
!, x 1
x Root2 4 #1 #15
x Root2 4 #1 #15
x Root2 4 #1 #15
x Root2 4 #1 #15
x Root2 4 #1 #15
&,
&,
&,
&,
&,
1!,
2!,
3!,
4!,
5!!
In[8]:= N[ % ]
Out[8]= x 1.51851, x 0.508499,
x 1.2436, x 0.116792 1.43845 ,
x 0.116792 1.43845
!!
89
In addition to being able to solve purely algebraic equations, Mathematica can also solve some
equations involving other functions.
After printing a warning, Mathematica
returns one solution to this equation.
It is important to realize that an equation such as sinx a actually has an infinite number of
possible solutions, in this case differing by multiples of . However, Solve by default returns just
one solution, but prints a message telling you that other solutions may exist. You can use Reduce to
get more information.
There is no explicit closed form
solution for a transcendental equation
like this.
Solve can also handle equations involving symbolic functions. In such cases, it again prints a
warning, then gives results in terms of formal inverse functions.
Mathematica returns a result in terms of
the formal inverse function of f.
Out[12]= x
f1
a
, x
f1
a
You can also use Mathematica to solve sets of simultaneous equations. You simply give the list of
equations, and specify the list of variables to solve for.
Here is a list of two simultaneous
equations, to be solved for the
variables x and y.
1
a
Out[13]= x
, y
2 a a2
2 a a2
90
In[15]:= x + y /. %
3
1
3
1
Out[14]= x
, y
, x
, y
10
10
10
10
2
2
,
Out[15]=
5
5
Mathematica can solve any set of simultaneous linear equations. It can also solve a large class of
simultaneous polynomial equations. Even when it does not manage to solve the equations explicitly,
Mathematica will still usually reduce them to a much simpler form.
When you are working with sets of equations in several variables, it is often convenient to reorganize
the equations by eliminating some variables between them.
This eliminates y between the two
equations, giving a single equation
for x.
If you have several equations, there is no guarantee that there exists any consistent solution for a
particular variable.
There is no consistent solution to these
equations, so Mathematica returns {},
indicating that the set of solutions is
empty.
Out[17]=
Out[18]=
The general question of whether a set of equations has any consistent solution is quite a subtle
one. For example, for most values of a, the equations {x==1, x==a} are inconsistent, so there is no
possible solution for x. However, if a is equal to 1, then the equations do have a solution. Solve is set
up to give you generic solutions to equations. It discards any solutions that exist only when special
constraints between parameters are satisfied.
If you use Reduce instead of Solve, Mathematica will however keep all the possible solutions to a
set of equations, including those that require special conditions on parameters.
This shows that the equations have a
solution only when a==1. The notation
a==1 && x==1 represents the
requirement that both a==1 and x==1
should be True.
91
In[20]:= Reduce[a x - b == 0, x]
In[22]:= Reduce[Sin[x] == a, x]
Solve[lhs==rhs, x]
b
Out[20]= b 0 && a 0 a 0 && x
a
b
b %
"
'
$x
x
Out[21]= b 0 && a 0 a 0 && $
'
a
a &
#
Out[22]= C
1 Integers && x ArcSin
a 2 C
1
x ArcSin
a 2 C
1
Reduce also has powerful capabilities for handling equations specifically over real numbers or
integers. Section 3.4.9 discusses this in more detail.
This reduces the equation assuming x
and y are complex.
92
1.5.8 Inequalities
Handling inequalities.
1
Out[1]= 0 ? x ? && x ? y ? 1 x
2
In[2]:= Reduce[x + y < 1 && y > x > 1, {x, y}]
Out[2]= False
In[3]:= Reduce[x + y < 1 && y^2 > x > 0, {x, y}]
1
Out[3]= 0 ? x ? 3 5 && y ? x x ? y ? 1 x
2
1
1
3 5 x ? 3 5 && y ? x
2
2
1
x 3 5 && y ? 1 x
2
Equations can often be solved to give definite values of variables. But inequalities typically just define
regions that can only be specified by other inequalities. You can use FindInstance to find definite
values of variables that satisfy a particular set of inequalities.
This finds a point in the region
specified by the inequalities.
7
Out[4]= x , y 3
5
3
1
Out[5]= , x , y
4
2
2
93
1
Out[1]= y
x a x C
1
1 a x
Out[2]= y
x
Whereas algebraic equations such as x x are equations for variables, differential equations such
as y$$ x y$ x yx are equations for functions. In Mathematica, you must always give differential
equations explicitly in terms of functions such as y[x], and you must specify the variables such as x
on which the functions depend. As a result, you must write an equation such as y$$ x y$ x yx
in the form y''[x] + y'[x] == y[x]. You cannot write it as y'' + y' == y.
Mathematica can solve both linear and nonlinear ordinary differential equations, as well as lists of
simultaneous equations. If you do not specify enough initial or boundary conditions, Mathematica will
give solutions that involve an appropriate number of undetermined coefficients. Each time you use
DSolve, it names the undetermined coefficients C[1], C[2], etc.
Here is a pair of simultaneous
differential equations, with no initial or
boundary conditions. The solution you
get involves two undetermined
coefficients.
1
1
Out[3]= x
t t 1 2 t C
1 t 1 2 t C
2,
2
2
1
1 t
2t
y
t 1 C
1 t 1 2 t C
2
2
2
When you ask DSolve to get you a solution for y[x], the rules it returns specify how to replace
y[x] in any expression. However, these rules do not specify how to replace objects such as y'[x]. If
you want to manipulate solutions that you get from DSolve, you will often find it better to ask for
solutions for y, rather than for y[x].
This gives the solution for y as a pure
function.
94
Section 2.2.5 explains how the pure function indicated by & that appears in the result from DSolve
works.
Note that DSolve can handle combinations of algebraic and differential equations. It can also handle
partial differential equations, in which there is more than one independent variable.
1
1
4
Out[1]= 1 n x 1 n n x2 2 n 1 n n x3 O
x
2
6
a
$2 a %
' t2
Out[2]= 1 2 a t "
2 &
#
4
a3
4 a a3
a4
"
$ a2 %
' t3 "
$ %
' t4 O
t5
6 &
3
24 &
# 3
# 3
1
1
4
Out[3]= 1 f
0 f<
0 t f<<
0 t2 f3
0 t3 O
t
2
6
Power series are approximate formulas that play much the same role with respect to algebraic
expressions as approximate numbers play with respect to numerical expressions. Mathematica allows
you to perform operations on power series, in all cases maintaining the appropriate order or degree
of precision for the resulting power series.
Here is a simple power series, accurate
to order x .
In[5]:= %^2 (1 + %)
In[6]:= Normal[%]
x2
x3
x4
x5
6
Out[4]= 1 x O
x
2
6
24 120
13 x2
35 x3
97 x4
55 x5
6
Out[5]= 2 5 x O
x
2
6
24
24
13 x2
35 x3
97 x4
55 x5
Out[6]= 2 5 x
2
6
24
24
1.5.11 Limits
95
In[7]:= %^2
2
13 x2
35 x3
97 x4
55 x5
'
$2 5 x %
Out[7]= "
2
6
24
24 &
#
Applying Expand gives a result with
eleven terms.
In[8]:= Expand[%]
265 x3
467 x4
1505 x5
Out[8]= 4 20 x 51 x2
3
4
12
1385 x7
24809 x8
5335 x9
3025 x10
7883 x6
72
18
576
288
576
1.5.11 Limits
Here is the expression sinxx.
In[1]:= t = Sin[x]/x
Sin
x
Out[1]=
x
If you replace x by 0, the expression
becomes 0/0, and you get an
indeterminate result.
In[2]:= t /. x->0
1
Power::infy: Infinite expression - encountered.
0
Infinity::indet:
Indeterminate expression 0 ComplexInfinity encountered.
Out[2]= Indeterminate
Out[3]= 0.999983
Limit[expr, x->x ]
Limits.
In[3]:= t /. x->0.01
Out[4]= 1
96
InverseLaplaceTransform[expr, s, t]
find the inverse Laplace transform of expr
Laplace transforms.
6
Out[1]=
4
a s
Here is the inverse transform.
In[2]:= InverseLaplaceTransform[%, s, t]
Out[2]= a t t3
FourierTransform[expr, t, w]
InverseFourierTransform[expr, w, t]
find the inverse Fourier transform of expr
Fourier transforms.
w2
w2
1
4 w4
34 4 34 4 w2
16
Out[3]=
2
In[4]:= InverseFourierTransform[%, w, t]
Out[4]= t t4
2
Note that in the scientific and technical literature many different conventions are used for defining
Fourier transforms. Page 936 describes the setup in Mathematica.
RSolve[eqns, a[n], n]
1
Out[1]= a
n 1 3n
97
Vector Analysis
<<Calculus`VectorAnalysis`
SetCoordinates[system[names]]
Grad[f]
Div[f]
Curl[f]
Laplacian[f]
Vector analysis.
In[1]:= <<Calculus`VectorAnalysis`
98
Variational Methods
<<Calculus`VariationalMethods`
VariationalD[f, y[x], x]
Variational methods.
In[1]:= <<Calculus`VariationalMethods`
2 y<
x y
x y<<
x
Out[2]=
32
4 y<
x
2
Quaternions
<<Algebra`Quaternions`
Quaternion[a, b, c, d]
the quaternion a bi cj dk
Quaternions.
In[1]:= <<Algebra`Quaternions`
ArcTan 2
Out[2]= Quaternion314 Cos ,
2
ArcTan 2
ArcTan 2
In[1]:= Integrate[x^n, x]
In[2]:= Integrate[x^-1, x]
x1n
Out[1]=
1n
Out[2]= Log x
99
The overall goal of symbolic computation is typically to get formulas that are valid for many possible
values of the variables that appear in them. It is however often not practical to try to get formulas
that are valid for absolutely every possible value of each variable.
Mathematica always replaces x by .
In[3]:= 0 / x
Out[3]= 0
In[4]:= 0 / 0
1
Power::infy: Infinite expression - encountered.
0
Infinity::indet:
Indeterminate expression 0 ComplexInfinity encountered.
Out[4]= Indeterminate
If Mathematica did not automatically replace x by 0, then few symbolic computations would get
very far. But you should realize that the practical necessity of making such replacements can cause
misleading results to be obtained when exceptional values of parameters are used.
The basic operations of Mathematica are nevertheless carefully set up so that whenever possible the
results obtained will be valid for almost all values of each variable.
x is not automatically replaced by x.
In[6]:= Sqrt[x^2]
Out[6]=
x2
In[7]:= % /. x -> -2
Out[7]= 2
Out[8]= x
100
imax
f
sum
product
Integrate[f, x]
indefinite integral
i=imin
imax
( f
i=imin
f 7x
xmax
definite integral
xmin
8x f
D[f, x]
partial derivative
8x,y f
D[f, x, y]
7
8
7 8,
)= *=
+,
sum
prod
int
summation sign
product sign
integral sign
dd
pd
@ or -
^ or 6
+ or =
& or 7
% or 5
(CONTROL-SPACE)
In[1]:= xn x
x1n
Out[1]=
1n
x1n
Out[2]=
1n
101
102
N[expr]
NIntegrate[f, {x, xmin, xmax}]
NSum[f, {i, imin, Infinity}]
FindRoot[lhs==rhs, {x, x }]
NSolve[lhs==rhs, x]
FindMinimum[f, {x, x }]
,
NMinimize[f, x]
In[1]:= (3 + Sqrt[2])^3
In[2]:= Expand[ % ]
Out[2]= 45 29 2
In[3]:= N[ % ]
Out[1]= 3
3
2
Out[3]= 86.0122
Functions such as Integrate always try to get exact results for computations. When they cannot
get exact results, they typically return unevaluated. You can then find numerical approximations by
explicitly applying N. Functions such as NIntegrate do the calculations numerically from the start,
without first trying to get an exact result.
103
In[5]:= N[ % ]
Out[5]= 0.81645
In[6]:= NIntegrate[Sin[Sin[x]], {x, 1, 2}]
Out[6]= 0.81645
numerical approximation to
imin f
numerical approximation to
imin f
xmax
xmax
ymax
Out[1]= 1.20206
Out[3]= 1.77245
Out[4]= 0.119906
104
NSolve[lhs==rhs, x]
If your equations involve only linear functions or polynomials, then you can use NSolve to get numerical approximations to all the solutions. However, when your equations involve more complicated
functions, there is in general no systematic procedure for finding all solutions, even numerically. In
such cases, you can use FindRoot to search for solutions. You have to give FindRoot a place to start
its search.
This searches for a numerical solution,
starting at x .
Out[3]= x 1.44726
Out[4]= x 13.1064
105
In[2]:= y[1.5] /. %
Out[2]= 4.48169
With an algebraic equation such as x
x , each solution for x is simply a single number. For
a differential equation, however, the solution is a function, rather than a single number. For example,
in the equation y$ x yx, you want to get an approximation to the function yx as the independent
variable x varies over some range.
Mathematica represents numerical approximations to functions as InterpolatingFunction objects.
These objects are functions which, when applied to a particular x, return the approximate value of
yx at that point. The InterpolatingFunction effectively stores a table of values for yxi , then
interpolates this table to find an approximation to yx at the particular x you request.
y[x] /. solution
use the list of rules for the function y to get values for y[x]
InterpolatingFunction[data][x]
evaluate an interpolated function at the point x
In[4]:= z[2] /. %
Out[4]= 0.416147
106
0.5
0.5
1.5
2.5
-0.5
-1
minimize f
maximize f
In[2]:= NMinimize[{Cos[x] - Exp[x y], x^2 + y^2 < 1}, {x, y}]
NMinimize and NMaximize can find the absolute minima and maxima of many functions. But in some
cases it is not realistic to do this. You can search for local minima and maxima using FindMinimum
and FindMaximum .
FindMinimum[f, {x, x }]
107
FindMaximum[f, {x, x }]
108
One common way of picking out signals in numerical data is to find the Fourier transform, or
frequency spectrum, of the data.
Fourier[data]
InverseFourier[data]
Fourier transforms.
In[9]:= Fourier[data]
Out[9]= 0. 0. , 0.707107 1.70711 ,
0. 0. , 0.707107 0.292893 , 0. 0. ,
0.707107 0.292893 , 0. 0. , 0.707107 1.70711
Note that the Fourier function in Mathematica is defined with the sign convention typically used
in the physical sciencesopposite to the one often used in electrical engineering. Section 3.8.4 gives
more details.
1.6.7 Statistics
109
1.6.7 Statistics
Mean[data]
Median[data]
Variance[data]
StandardDeviation[data]
Quantile[data, q]
Total[data]
In[2]:= Mean[data]
Out[2]= 6.46667
In[3]:= Variance[data]
Out[3]= 4.69467
The standard set of packages distributed with Mathematica includes several for doing more sophisticated statistical analyses of data.
Statistics`DescriptiveStatistics`
Statistics`MultivariateDescriptiveStatistics`
multivariate descriptive statistics functions
Statistics`ContinuousDistributions`
Statistics`DiscreteDistributions`
Statistics`HypothesisTests`
Statistics`ConfidenceIntervals`
Statistics`MultinormalDistribution`
Statistics`LinearRegression`
Statistics`NonlinearFit`
Statistics`DataSmoothing`
Statistics`DataManipulation`
Some standard statistical analysis packages.
110
In[2]:= f[a+1]
2
Out[2]= 1 a
In[3]:= f[4]
Out[3]= 16
In[5]:= Expand[f[(x+1+y)]]
Out[4]= 3 x x2
Out[5]= 1 2 x x2 2 y 2 x y y2
In[6]:= ?f
Global`f
f[x_] := x^2
f[x_] := x^2
?f
Clear[f]
The names like f that you use for functions in Mathematica are just symbols. Because of this, you
should make sure to avoid using names that begin with capital letters, to prevent confusion with
111
built-in Mathematica functions. You should also make sure that you have not used the names for
anything else earlier in your session.
Mathematica functions can have any
number of arguments.
In[10]:= ?hump
Global`hump
hump[x_, xmax_] := (x - xmax)^4
In[11]:= Clear[hump]
When you have finished with a particular function, it is always a good idea to clear definitions you
have made for it. If you do not do this, then you will run into trouble if you try to use the same
function for a different purpose later in your Mathematica session. You can clear all definitions you
have made for a function or symbol f by using Clear[f] .
In[4]:= exprod[5]
Out[1]= 6 11 x 6 x2 x3
Out[2]= 24 50 x 35 x2 10 x3 x4
The functions you define in Mathematica are essentially procedures that execute the commands you
give. You can have several steps in your procedures, separated by semicolons.
112
In[6]:= cex[5, 3]
Out[6]= 85
Constructing procedures.
When you write procedures in Mathematica, it is usually a good idea to make variables you use
inside the procedures local, so that they do not interfere with things outside the procedures. You can
do this by setting up your procedures as modules, in which you give a list of variables to be treated
as local.
The function cex defined above is not
a module, so the value of t escapes,
and exists even after the function
returns.
In[7]:= t
In[9]:= ncex[5, 3]
In[10]:= u
Out[9]= 85
Out[10]= u
113
1
2
6
24
120
Out[2]= 1, 2, 6, 24, 120
573147844013817084101
Out[3]=
927372692193078999176
Out[1]= 1 f 3 f y
Out[2]= 1 p f y
Out[3]= 1 x2 y2
Probably the most powerful aspect of transformation rules in Mathematica is that they can involve
not only literal expressions, but also patterns. A pattern is an expression such as f[t_] which contains
a blank (underscore). The blank can stand for any expression. Thus, a transformation rule for f[t_]
specifies how the function f with any argument should be transformed. Notice that, in contrast, a
transformation rule for f[x] without a blank, specifies only how the literal expression f[x] should be
transformed, and does not, for example, say anything about the transformation of f[y].
114
When you give a function definition such as f[t_] := t^2, all you are doing is telling Mathematica
to automatically apply the transformation rule f[t_] -> t^2 whenever possible.
You can set up transformation rules for
expressions of any form.
Out[4]= f a f b f c f d
Out[5]= 1 f 2 f 4
Sections 2.3 and 2.5 will explain in detail how to set up patterns and transformation rules for any
kind of expression. Suffice it to say here that in Mathematica all expressions have a definite symbolic
structure; transformation rules allow you to transform parts of that structure.
115
1.8 Lists
1.8.1 Collecting Objects Together
We first encountered lists in Section 1.2.3 as a way of collecting numbers together. In this section,
we shall see many different ways to use lists. You will find that lists are some of the most flexible
and powerful objects in Mathematica. You will see that lists in Mathematica represent generalizations
of several standard concepts in mathematics and computer science.
At a basic level, what a Mathematica list essentially does is to provide a way for you to collect
together several expressions of any kind.
Here is a list of numbers.
In[1]:= {2, 3, 4}
Out[1]= 2, 3, 4
In[2]:= x^% - 1
In[3]:= D[%, x]
Out[2]= 1 x2 , 1 x3 , 1 x4
Out[3]= 2 x, 3 x2 , 4 x3
In[4]:= % /. x -> 3
Out[4]= 6, 27, 108
The mathematical functions that are built into Mathematica are mostly set up to be listable so that
they act separately on each element of a list. This is, however, not true of all functions in Mathematica.
Unless you set it up specially, a new function f that you introduce will treat lists just as single objects.
Sections 2.2.4 and 2.2.10 will describe how you can use Map and Thread to apply a function like this
separately to each element in a list.
1
2
3
4
Out[2]= 0, Sin , Sin , Sin , Sin
5
5
5
5
116
In[3]:= N[%]
Out[3]= 0., 0.198669, 0.389418, 0.564642, 0.717356
In[7]:= %^2 + 3
In[8]:= % // TableForm
Out[5]= 2 x 4 x2 6 x3 8 x4 10 x5
3
3.25
Out[8]//TableForm= 3.5
3.75
4.
All the examples so far have been of tables obtained by varying a single parameter. You can also
make tables that involve several parameters. These multidimensional tables are specified using the
standard Mathematica iterator notation, discussed in Section 1.5.4.
This makes a table of x i y j with i
running from to
and j running
from to .
The table in this example is a list of lists. The elements of the outer list correspond to successive
values of i. The elements of each inner list correspond to successive values of j, with i fixed.
Sometimes you may want to generate a table by evaluating a particular expression many times,
without incrementing any variables.
This creates a list containing four
copies of the symbol x.
Out[10]= x, x, x, x
Table[f, {imax}]
Table[f, {i, imax}]
Table[f, {i, imin, imax}]
Table[f, {i, imin, imax, di}]
117
You can use the operations discussed in Section 1.2.4 to extract elements of the table.
This creates a table, and gives it
the name m.
In[13]:= m[[1]]
In[14]:= %[[2]]
In[15]:= m[[1,2]]
Out[14]= 1
Out[15]= 1
In[16]:= TableForm[m]
Out[16]//TableForm=
t[[i]] or Part[t, i]
0
1
1
0
118
As we mentioned in Section 1.2.4, you can think of lists in Mathematica as being analogous to
arrays. Lists of lists are then like two-dimensional arrays. When you lay them out in a tabular
form, the two indices of each element are like its x and y coordinates.
You can use Table to generate arrays with any number of dimensions.
This generates a three-dimensional
array. It is a list of lists of
lists.
In[17]:= Table[i j^2 k^3, {i, 2}, {j, 2}, {k, 2}]
Out[17]= 1, 8, 4, 32, 2, 16, 8, 64
{a, b, c}
{{a, b}, {c, d}}
vector a b c
matrix
a b
c d
This is a matrix.
In[2]:= m[[1]]
Out[2]= a, b
In[3]:= m[[1,2]]
Out[3]= b
In[4]:= v = {x, y}
Out[4]= x, y
In[5]:= p v + q
In[8]:= m . v
Out[5]= q p x, q p y
Out[7]= x xp y yp
Out[8]= a x b y, c x d y
119
Or a matrix by a matrix.
In[9]:= m . m
Out[9]= a2 b c, a b b d, a c c d, b c d2
Or a vector by a matrix.
In[10]:= v . m
Out[10]= a x c y, b x d y
In[11]:= v . m . v
Out[11]= x a x c y y b x d y
Because of the way Mathematica uses lists to represent vectors and matrices, you never have to
distinguish between row and column vectors.
Length[list]
ColumnForm[list]
cv
a.b
Cross[a, b]
,
Norm[v]
120
Dimensions[list]
MatrixForm[list]
In[13]:= MatrixForm[s]
In[14]:= Array[a, 4]
In[16]:= Dimensions[%]
2 3 4%
"
$
'
$
'
3 4 5'
Out[13]//MatrixForm= $
$
'
$
'
$
'
4
5
6
#
&
Out[16]= 3, 2
121
cm
a.b
Inverse[m]
MatrixPower[m, n]
Det[m]
Tr[m]
Transpose[m]
multiply by a scalar
matrix product
matrix inverse
nth power of a matrix
determinant
trace
transpose
Eigenvalues[m]
eigenvalues
Eigenvectors[m]
eigenvectors
In[18]:= m
In[19]:= Det[m]
Out[19]= b c a d
In[20]:= Transpose[m]
Out[20]= a, c, b, d
In[21]:= Inverse[m]
d
b
c
a
Out[21]= ,
, ,
b c a d
b c a d
b c a d b c a d
1 1
1 1 1
1 1 1
Out[22]= 1, ,
, , ,
, , ,
2 3
2 3 4
3 4 5
This gives its inverse.
In[23]:= Inverse[h]
Out[23]= 9, 36, 30, 36, 192, 180, 30, 180, 180
In[24]:= % . h
Here is a matrix.
122
In[26]:= Eigenvalues[r]
In[27]:= rn = N[r]
In[28]:= Eigenvalues[rn]
1
1
Out[26]= 15 249 , 15 249 , 0
2
2
Out[27]= 3., 4., 5., 4., 5., 6., 5., 6., 7.
Out[28]=
Section 3.7 discusses many other matrix operations that are built into Mathematica.
Last[list]
Part[list, n] or list[[n]]
In[1]:= t = {a,b,c,d,e,f,g}
Out[1]= a, b, c, d, e, f, g
In[2]:= Last[t]
Out[2]= g
In[3]:= t[[3]]
Out[3]= c
Take[list, n]
Take[list, -n]
Take[list, {m, n}]
Rest[list]
Drop[list, n]
Most[list]
Drop[list, -n]
Drop[list, {m, n}]
123
In[5]:= Take[t, 3]
Out[5]= a, b, c
Out[6]= e, f, g
In[9]:= Rest[t]
In[10]:= Drop[t, 3]
Out[7]= b, c, d, e
Out[8]= c, e, g
Out[9]= b, c, d, e, f, g
Out[10]= d, e, f, g
Out[11]= a, b, d, e, f, g
Section 2.1.5 will show how all the functions in this section can be generalized to work not only on
lists, but on any Mathematica expressions.
The functions in this section allow you to pick out pieces that occur at particular positions in lists.
Section 2.3.2 will show how you can use functions like Select and Cases to pick out elements of lists
based not on their positions, but instead on their properties.
124
The previous section discussed how to extract pieces of lists based on their positions or indices.
Mathematica also has functions that search and test for elements of lists, based on the values of those
elements.
This gives a list of the positions at
which a appears in the list.
Out[2]= 2
Out[3]= True
Out[4]= False
In[5]:= m = IdentityMatrix[3]
In[6]:= FreeQ[m, 0]
In[7]:= Position[m, 0]
Out[6]= False
Out[7]= 1, 2, 1, 3, 2, 1, 2, 3, 3, 1, 3, 2
As discussed in Section 2.3.2, the functions Count and Position , as well as MemberQ and FreeQ,
can be used not only to search for particular list elements, but also to search for classes of elements
which match specific patterns.
125
Out[2]= a, x, b, c
Out[3]= a, b, x, d
Functions like ReplacePart take explicit lists and give you new lists. Sometimes, however, you may
want to modify a list in place, without explicitly generating a new list.
v = {e , e , ... }
v[[i]] = new
In[5]:= v = {a, b, c, d}
Out[5]= a, b, c, d
In[6]:= v[[3]] = x
Out[6]= x
126
In[7]:= v
Out[7]= a, b, x, d
Out[1]= a, b, c, x, y, t, u
Out[2]= a, b, c, d
127
give a list of the elements that are common to all the listi
Out[1]= a, b, c, d, e
Out[2]= a, b
Out[3]= b, c
Out[1]= a, a, b, b, c
Out[2]= a, b, c
Out[3]= c, d, e, a, b
128
PadLeft[list, len, x]
PadRight[list, len, x]
Padding lists.
Here is a list.
In[1]:= t = {a, b, c, d, e, f, g}
Out[1]= a, b, c, d, e, f, g
In[2]:= Partition[t, 2]
In[3]:= Partition[t, 3]
In[4]:= Partition[t, 3, 1]
Out[4]= a, b, c, b, c, d, c, d, e, d, e, f, e, f, g
129
Sort[list]
Min[list]
Ordering[list, n]
Max[list]
,
Ordering[list, -n]
Ordering[list]
Permutations[list]
Ordering in lists.
Here is a list.
In[2]:= Min[t]
In[3]:= Ordering[t, 3]
In[4]:= t[[%]]
Out[2]= 9
Out[3]= 4, 3, 1
Flatten[list]
Flatten[list, n]
Partition[list, {n , n , ... }]
Transpose[list]
RotateLeft[list, {n , n , ... }]
PadLeft[list, {n , n , ... }]
A few functions for rearranging nested lists.
130
Out[1]= a, b, c, d
There are many other operations you can perform on nested lists. We will discuss more of them in
Section 2.4.
131
0.5
-0.5
-1
40
20
-3
-2
-1
-20
-40
132
0.5
-0.5
-1
To get smooth curves, Mathematica has to evaluate functions you plot at a large number of points. As
a result, it is important that you set things up so that each function evaluation is as quick as possible.
When you ask Mathematica to plot an object, say f, as a function of x, there are two possible
approaches it can take. One approach is first to try and evaluate f, presumably getting a symbolic
expression in terms of x, and then subsequently evaluate this expression numerically for the specific
values of x needed in the plot. The second approach is first to work out what values of x are needed,
and only subsequently to evaluate f with those values of x.
If you type Plot[f, {x, xmin, xmax}] it is the second of these approaches that is used. This has
the advantage that Mathematica only tries to evaluate f for specific numerical values of x; it does not
matter whether sensible values are defined for f when x is symbolic.
There are, however, some cases in which it is much better to have Mathematica evaluate f before
it starts to make the plot. A typical case is when f is actually a command that generates a table
of functions. You want to have Mathematica first produce the table, and then evaluate the functions, rather than trying to produce the table afresh for each value of x. You can do this by typing
Plot[Evaluate[f], {x, xmin, xmax}].
This makes a plot of the Bessel
functions Jn x with n running from
to
. The Evaluate tells Mathematica
first to make the table of functions, and
only then to evaluate them for
particular values of x.
10
-0.2
1.9.2 Options
133
2.5
1.5
1.9.2 Options
When Mathematica plots a graph for you, it has to make many choices. It has to work out what the
scales should be, where the function should be sampled, how the axes should be drawn, and so on.
Most of the time, Mathematica will probably make pretty good choices. However, if you want to get
the very best possible pictures for your particular purposes, you may have to help Mathematica in
making some of its choices.
There is a general mechanism for specifying options in Mathematica functions. Each option has
a definite name. As the last arguments to a function like Plot, you can include a sequence of rules
of the form name->value, to specify the values for various options. Any option for which you do not
give an explicit rule is taken to have its default value.
134
A function like Plot has many options that you can set. Usually you will need to use at most a few
of them at a time. If you want to optimize a particular plot, you will probably do best to experiment,
trying a sequence of different settings for various options.
Each time you produce a plot, you can specify options for it. Section 1.9.3 will also discuss how
you can change some of the options, even after you have produced the plot.
option name
default value
AspectRatio
1/GoldenRatio
Axes
Automatic
AxesLabel
None
AxesOrigin
Automatic
TextStyle
$TextStyle
FormatType
StandardForm
DisplayFunction
$DisplayFunction
Frame
False
FrameLabel
None
FrameTicks
Automatic
GridLines
None
PlotLabel
None
PlotRange
Automatic
Ticks
Automatic
Some of the options for Plot. These can also be used in Show.
1.9.2 Options
135
0.5
0.5
1.5
2.5
-0.5
-1
0.5
-0.5
-1
0
0.5
1.5
2.5
0.5
0.5
-0.5
-1
1.5
2.5
x value
136
0.5
-0.5
-1
0
0.5
1.5
2.5
0.5
0.5
1.5
2.5
-0.5
-1
Automatic
None
All
include everything
True
False
do this
do not do this
When Mathematica makes a plot, it tries to set the x and y scales to include only the interesting
parts of the plot. If your function increases very rapidly, or has singularities, the parts where it gets
too large will be cut off. By specifying the option PlotRange , you can control exactly what ranges of
x and y coordinates are included in your plot.
1.9.2 Options
137
Automatic
All
{ymin, ymax}
{xrange, yrange}
1
0.8
0.6
0.4
0.2
0.5
1.5
2.5
Mathematica always tries to plot functions as smooth curves. As a result, in places where your
function wiggles a lot, Mathematica will use more points. In general, Mathematica tries to adapt its
sampling of your function to the form of the function. There is, however, a limit, which you can set,
to how finely Mathematica will ever sample a function.
The function sin x wiggles infinitely
often when x . Mathematica tries to
sample more points in the region
where the function wiggles a lot, but it
can never sample the infinite number
that you would need to reproduce the
function exactly. As a result, there are
slight glitches in the plot.
0.5
-1
-0.5
0.5
-0.5
-1
138
option name
default value
PlotStyle
Automatic
PlotPoints
25
MaxBend
10.
PlotDivision
30.
Compiled
True
It is important to realize that since Mathematica can only sample your function at a limited number
of points, it can always miss features of the function. By increasing PlotPoints , you can make Mathematica sample your function at a larger number of points. Of course, the larger you set PlotPoints
to be, the longer it will take Mathematica to plot any function, even a smooth one.
Since Plot needs to evaluate your function many times, it is important to make each evaluation as quick as possible. As a result, Mathematica usually compiles your function into a low-level
pseudocode that can be executed very efficiently. One potential problem with this, however, is that
the pseudocode allows only machine-precision numerical operations. If the function you are plotting
requires higher-precision operations, you may have to switch off compilation in Plot. You can do this
by setting the option Compiled -> False. Note that Mathematica can only compile inline code; it
cannot for example compile functions that you have defined. As a result, you should, when possible,
use Evaluate as described on page 132 to evaluate any such definitions and get a form that the
Mathematica compiler can handle.
139
Show[plot]
Show[plot, option->value]
Show[plot , plot , ... ]
redraw a plot
redraw with options changed
combine several plots
0.5
-1
-0.5
0.5
0.5
-0.5
-1
In[2]:= Show[%]
0.5
-1
-0.5
-0.5
-1
140
2
1.5
1
0.5
-1
-0.5
0.5
-0.5
-1
A Chebyshev Polynomial
2
1.5
1
0.5
-1
-0.5
0.5
-0.5
-1
By using Show with a sequence of different options, you can look at the same plot in many different
ways. You may want to do this, for example, if you are trying to find the best possible setting of
options.
You can also use Show to combine plots. It does not matter whether the plots have the same scales:
Mathematica will always choose new scales to include the points you want.
This sets gj0 to be a plot of J x from
x to .
1
0.8
0.6
0.4
0.2
2
-0.2
-0.4
10
141
0.4
0.2
2
10
-0.2
-0.4
-0.6
-0.8
1
0.75
0.5
0.25
2
10
-0.25
-0.5
-0.75
Using Show[plot , plot , ... ] you can combine several plots into one. GraphicsArray allows you
to draw several plots in an array.
142
1
0.8
0.6
0.4
0.2
-0.2
-0.4
1
0.75
0.5
0.25
2
10
0.4
0.2
2
10
-0.2
-0.4
-0.6
-0.8
-0.25
-0.5
-0.75
10
10
1
0.75
0.5
0.25
-0.25
-0.5
-0.75
1
0.8
0.6
0.4
0.2
-0.2
-0.4
1
0.75
0.5
0.25
2
10
0.4
0.2
2
-0.2
-0.4
-0.6
-0.8
10
-0.25
-0.5
-0.75
10
10
1
0.75
0.5
0.25
-0.25
-0.5
-0.75
143
GraphicsArray by default puts a narrow border around each of the plots in the array it gives. You
can change the size of this border by setting the option GraphicsSpacing -> {h, v}. The parameters
h and v give the horizontal and vertical spacings to be used, as fractions of the width and height of
the plots.
This increases the horizontal spacing,
but decreases the vertical spacing
between the plots in the array.
When you make a plot, Mathematica saves the list of points it used, together with some other
information. Using what is saved, you can redraw plots in many different ways with Show. However,
you should realize that no matter what options you specify, Show still has the same basic set of points
to work with. So, for example, if you set the options so that Mathematica displays a small portion of
your original plot magnified, you will probably be able to see the individual sample points that Plot
used. Options like PlotPoints can only be set in the original Plot command itself. (Mathematica
always plots the actual points it has; it avoids using smoothed or splined curves, which can give
misleading results in mathematical graphics.)
144
0.5
-3
-2
-1
-0.5
-1
0.05
0.1
0.15
0.2
0.25
0.99
0.98
0.97
0.96
0.95
0.94
0.93
0.92
Options[function]
Options[function, option]
145
The graphics objects that you get from Plot or Show store information on the options they use.
You can get this information by applying the Options function to these graphics objects.
Options[plot]
Options[plot, option]
AbsoluteOptions[plot, option]
1.75
1.5
1.25
1
0.75
0.5
0.25
5
10
15
20
Out[6]= PlotRange
0.499999, 20.5, 0.0462976, 1.89824
146
-1
-2
-2
-1
A contour plot gives you essentially a topographic map of a function. The contours join points on
the surface that have the same height. The default is to have contours corresponding to a sequence
of equally spaced z values. Contour plots produced by Mathematica are by default shaded, in such a
way that regions with higher z values are lighter.
147
option name
default value
ColorFunction
Automatic
Contours
10
PlotRange
Automatic
ContourShading
True
PlotPoints
25
Compiled
True
Some options for ContourPlot. The first set can also be used in Show.
-1
-2
-2
-1
You should realize that if you do not evaluate your function on a fine enough grid, there may be
inaccuracies in your contour plot. One point to notice is that whereas a curve generated by Plot may
be inaccurate if your function varies too quickly in a particular region, the shape of contours can be
inaccurate if your function varies too slowly. A rapidly varying function gives a regular pattern of
contours, but a function that is almost flat can give irregular contours. You can typically overcome
such problems by increasing the value of PlotPoints .
148
-1
-2
-2
-1
-1
-2
-2
-1
option name
default value
ColorFunction
Automatic
Mesh
True
PlotPoints
25
Compiled
True
Some options for DensityPlot. The first set can also be used in Show.
149
1
0.5
0
-0.5
-1
0
1
2
30
There are many options for three-dimensional plots in Mathematica. Some will be discussed in this
section; others will be described in Section 2.10.
The first set of options for three-dimensional plots is largely analogous to those provided in the
two-dimensional case.
150
option name
default value
Axes
True
AxesLabel
None
Boxed
True
ColorFunction
Automatic
TextStyle
$TextStyle
FormatType
StandardForm
DisplayFunction
$DisplayFunction
FaceGrids
None
HiddenSurface
True
Lighting
True
Mesh
True
PlotRange
Automatic
Shading
True
ViewPoint
{1.3, -2.4, 2}
PlotPoints
25
Compiled
True
Some options for Plot3D. The first set can also be used in Show.
151
0.4
0.2
0
-0.2
-0.4
0
1
2
30
In[3]:= Plot3D[10 Sin[x + Sin[y]], {x, -10, 10}, {y, -10, 10},
PlotPoints -> 50]
10
5
10
0
5
-5
-10
-10
10
0
-5
-5
0
5
10 -10
152
10
5
Value
10
0
5
-5
-10
-10
10
Depth
-5
-5
0
Time
5
10 -10
Probably the single most important issue in plotting a three-dimensional surface is specifying where
you want to look at the surface from. The ViewPoint option for Plot3D and Show allows you to specify the point {x, y, z} in space from which you view a surface. The details of how the coordinates
for this point are defined will be discussed in Section 2.10.10. In many versions of Mathematica, there
are ways to choose three-dimensional view points interactively, then get the coordinates to give as
settings for the ViewPoint option.
Here is a surface, viewed from the
default view point {1.3, -2.4, 2}.
This view point is chosen to be
generic, so that visually confusing
coincidental alignments between
different parts of your object are
unlikely.
1
0.5
0
-0.5
-1
0
1
2
30
153
10
1
2
0.5
-0.5
-1
0
{1.3, -2.4, 2}
directly in front
{0, -2, 2}
in front and up
{-2, -2, 0}
left-hand corner
{0, 0, 2}
{0, -2, 0}
{2, -2, 0}
right-hand corner
directly above
The human visual system is not particularly good at understanding complicated mathematical
surfaces. As a result, you need to generate pictures that contain as many clues as possible about the
form of the surface.
View points slightly above the surface usually work best. It is generally a good idea to keep the
view point close enough to the surface that there is some perspective effect. Having a box explicitly
drawn around the surface is helpful in recognizing the orientation of the surface.
154
1
0.75
0.5
1
0.25
0
-2
0
-1
-1
0
1
2 -2
1
0.75
0.5
1
0.25
0
-2
0
-1
-1
0
1
2 -2
155
1
0.75
0.5
1
0.25
0
-2
0
-1
-1
0
1
2 -2
The inclusion of shading and a mesh are usually great assets in understanding the form of a surface.
On some vector graphics output devices, however, you may not be able to get shading. You should
also realize that when shading is included, it may take a long time to render the surface on your
output device.
To add an extra element of realism to three-dimensional graphics, Mathematica by default colors
three-dimensional surfaces using a simulated lighting model. In the default case, Mathematica assumes
that there are three light sources shining on the object from the upper right of the picture. Section
2.10.12 describes how you can set up other light sources, and how you can specify the reflection
properties of an object.
While in most cases, particularly with color output devices, simulated lighting is an asset, it can
sometimes be confusing. If you set the option Lighting -> False, then Mathematica will not use
simulated lighting, but will instead shade all surfaces with gray levels determined by their height.
Plot3D usually colors surfaces using a
simulated lighting model.
1
0.5
0
-0.5
-1
0
1
2
30
156
1
0.5
0
-0.5
-1
0
1
2
30
With Lighting -> False, Mathematica shades surfaces according to height. You can also tell Mathematica explicitly how to shade each element of a surface. This allows you effectively to use shading
to display an extra coordinate at each point on your surface.
1
0.5
0
-0.5
-1
0
1
2
30
157
1
3
0.5
0
2
0
1
1
2
30
2.5
1.5
0.5
0
0
0.5
1.5
2.5
158
Show[ContourGraphics[g]]
Show[DensityGraphics[g]]
Show[SurfaceGraphics[g]]
Show[Graphics[g]]
3
2.5
2
1
0.5
0
1.5
1
3
2
0
1
1
0.5
2
30
0
0
0.5
1.5
2.5
ListPlot[{y , y , ... }]
159
plot y , y , at x values , ,
ListDensityPlot[array]
In[2]:= ListPlot[t]
100
80
60
40
20
10
100
80
60
40
20
10
160
In[5]:= ListPlot[%]
1400
1200
1000
800
600
400
200
20
40
60
80
100
In[7]:= ListPlot3D[t3]
15
20
10
15
5
0
10
10
5
20
30
161
30
10
15
20
20
10
15
10
In[9]:= ListDensityPlot[t3]
20
15
10
0
0
10
15
20
25
30
162
0.5
-1
-0.5
0.5
-0.5
-1
0.5
-1
-0.5
0.5
-0.5
-1
163
0.5
-1
-0.5
0.5
-0.5
-1
164
0.5
0
1-1 -0.5 0
0.5 1
-0.5
.5
-1
ParametricPlot3D[{f x , fy , fz }, {t, tmin, tmax}, {u, umin, umax}] creates a surface, rather than
a curve. The surface is formed from a collection of quadrilaterals. The corners of the quadrilaterals
have coordinates corresponding to the values of the fi when t and u take on values in a regular grid.
Here the x and y coordinates for the
quadrilaterals are given simply by t
and u. The result is a surface plot of
the kind that can be produced by
Plot3D.
165
8
6
4
2
0
1
0.5
0
-0.5
-1
0
1
2
3
0.5
0
1-1 -0.5 0
0.5 1
-0.5
.5
-1
166
0.5
1-1 -0.5
0.5
-0.5
-1
4
1
0
In[9]:= ParametricPlot3D[
{Cos[t] (3 + Cos[u]), Sin[t] (3 + Cos[u]), Sin[u]},
{t, 0, 2Pi}, {u, 0, 2Pi}]
1
0.5
0
-0.5
-1
-4
2
0
-2
-2
0
2
4
-4
167
In[10]:= ParametricPlot3D[
{Cos[t] Cos[u], Sin[t] Cos[u], Sin[u]},
{t, 0, 2Pi}, {u, -Pi/2, Pi/2}]
1
0.5
0
-0.5
-1
1
0.5
0
-0.5
-1
-1
-0.5
0
0.5
1
You should realize that when you draw surfaces with ParametricPlot3D , the exact choice of
parametrization is often crucial. You should be careful, for example, to avoid parametrizations in
which all or part of your surface is covered more than once. Such multiple coverings often lead
to discontinuities in the mesh drawn on the surface, and may make ParametricPlot3D take much
longer to render the surface.
168
<<Graphics`
LogPlot[f, {x, xmin, xmax}]
LogListPlot[list]
LogLogListPlot[list]
PolarPlot[r, {t, tmin, tmax}]
PieChart[list]
In[1]:= <<Graphics`
0.1
0.01
169
In[4]:= TextListPlot[p]
10
25
9
20
8
7
15
6
5
10
4
3
1
10
In[5]:= BarChart[p]
25
20
15
10
5
1
In[6]:= PieChart[p]
4
3
2
1
8
10
9
10
170
<<Graphics`Animation`
Animate[plot, {t, tmin, tmax}]
ShowAnimation[{g , g , ... }]
When you produce a sequence of frames for a movie, it is important that different frames be
consistent. Thus, for example, you should typically give an explicit setting for the PlotRange option,
rather than using the default Automatic setting, in order to ensure that the scales used in different
frames are the same. If you have three-dimensional graphics with different view points, you should
similarly set SphericalRegion -> True in order to ensure that the scaling of different plots is the
same.
This generates a list of graphics objects.
Setting DisplayFunction -> Identity
stops Plot3D from rendering the
graphics it produces. Explicitly setting
PlotRange ensures that the scale is the
same in each piece of graphics.
1.9.12 Sound
171
1.9.12 Sound
On most computer systems, Mathematica can produce not only graphics but also sound. Mathematica
treats graphics and sound in a closely analogous way.
For example, just as you can use Plot[f, {x, xmin, xmax}] to plot a function, so also you can
use Play[f, {t, 0, tmax}] to play a function. Play takes the function to define the waveform for
a sound: the values of the function give the amplitude of the sound as a function of time.
Playing a function.
Sounds produced by Play can have any waveform. They do not, for example, have to consist of
a collection of harmonic pieces. In general, the amplitude function you give to Play specifies the
instantaneous signal associated with the sound. This signal is typically converted to a voltage, and
ultimately to a displacement. Note that amplitude is sometimes defined to be the peak signal associated
with a sound; in Mathematica, it is always the instantaneous signal as a function of time.
This plays a more complex sound.
172
Play is set up so that the time variable that appears in it is always measured in absolute seconds.
When a sound is actually played, its amplitude is sampled a certain number of times every second.
You can specify the sample rate by setting the option SampleRate .
In general, the higher the sample rate, the better high-frequency components in the sound will be
rendered. A sample rate of r typically allows frequencies up to r hertz. The human auditory system
can typically perceive sounds in the frequency range 20 to 22000 hertz (depending somewhat on age
and sex). The fundamental frequencies for the 88 notes on a piano range from 27.5 to 4096 hertz.
The standard sample rate used for compact disc players is 44100. The effective sample rate in a
typical telephone system is around 8000. On most computer systems, the default sample rate used by
Mathematica is around 8000.
You can use Play[{f , f }, ... ] to produce stereo sound. In general, Mathematica supports any
number of sound channels.
The function ListPlay allows you simply to give a list of values which are taken to be sound
amplitudes sampled at a certain rate.
When sounds are actually rendered by Mathematica, only a certain range of amplitudes is allowed.
The option PlayRange in Play and ListPlay specifies how the amplitudes you give should be scaled
to fit in the allowed range. The settings for this option are analogous to those for the PlotRange
graphics option discussed on page 137.
1.9.12 Sound
173
While it is often convenient to use the default setting PlayRange -> Automatic , you should realize
that Play may run significantly faster if you give an explicit PlayRange specification, so it does not
have to derive one.
Show[sound]
Both Play and ListPlay return Sound objects which contain procedures for synthesizing sounds.
You can replay a particular Sound object using the function Show that is also used for redisplaying
graphics.
The internal structure of Sound objects is discussed in Section 2.10.18.
174
\[Alpha]
a or alpha
\alpha
&agr
B C / 0 D E F
1 2 3 4 G 5 6
175
full name
aliases
full name
aliases
[Alpha]
, a , , , alpha ,
[CapitalGamma]
, G , , , Gamma ,
[Beta]
, b , , , beta ,
[CapitalDelta]
, D , , , Delta ,
[Gamma]
, g , , , gamma ,
[CapitalTheta]
, Q , , , Th , , , Theta ,
[Delta]
, d , , , delta ,
[CapitalLambda]
, L , , , Lambda ,
[Epsilon]
, e , , , epsilon ,
[CapitalPi]
, P , , , Pi ,
[Zeta]
, z , , , zeta ,
[CapitalSigma]
, S , , , Sigma ,
[Eta]
, h , , , et , , , eta ,
[CapitalUpsilon]
, U , , , Upsilon ,
[Theta]
, q , , , th , , , theta ,
[CapitalPhi]
, F , , , Ph , , , Phi ,
[Kappa]
, k , , , kappa ,
[CapitalChi]
, C , , , Ch , , , Chi ,
[Lambda]
, l , , , lambda ,
[CapitalPsi]
, Y , , , Ps , , , Psi ,
[Mu]
, m , , , mu ,
[CapitalOmega]
, O , , , W , , , Omega ,
[Nu]
, n , , , nu ,
[Xi]
, x , , , xi ,
[Pi]
, p , , , pi ,
[Rho]
, r , , , rho ,
[Sigma]
, s , , , sigma ,
[Tau]
, t , , , tau ,
[Phi]
, f , , , ph , , , phi ,
[CurlyPhi]
, j , , , cph , , , cphi ,
[Chi]
, c , , , ch , , , chi ,
[Psi]
, y , , , ps , , , psi ,
[Omega]
, o , , , w , , , omega ,
Commonly used Greek letters. In aliases , stands for the key . TEX aliases are not listed explicitly.
Note that in Mathematica the letter stands for Pi. None of the other Greek letters have special
meanings.
stands for Pi.
In[3]:= N[]
Out[3]= 3.14159
In[5]:= Factor[^4 - 1]
Out[4]= R4 4 R3 3 6 R2 32 4 R 33 34
Out[5]= 1 1 1 2
176
In[1]:= x^y
In[2]:= xy
Out[1]= xy
Out[2]= xy
One way to enter a two-dimensional form such as xy into a Mathematica notebook is to copy this
form from a palette by clicking the appropriate button in the palette.
Here is a palette for entering some
common two-dimensional notations.
There are also several ways to enter two-dimensional forms directly from the keyboard.
x ^ y
x 6 y
Ways to enter a superscript directly from the keyboard. stands for CONTROL-SPACE.
You type ^ by holding down the CONTROL key, then hitting the ^ key. As soon as you do this,
your cursor will jump to a superscript position. You can then type anything you want and it will
appear in that position.
When you have finished, press to move back down from the superscript position.
stands for CONTROL-SPACE; you type it by holding down the CONTROL key, then pressing the space bar.
This sequence of keystrokes enters xy .
In[3]:= x ^ y
Out[3]= xy
In[4]:= x ^ y + z
Out[4]= xyz
Out[5]= xy z
You can remember the fact that ^ gives you a superscript by thinking of ^ as just a
more immediate form of ^. When you type x^y, Mathematica will leave this one-dimensional form
177
unchanged until you explicitly process it. But if you type x ^ y then Mathematica will immediately
give you a superscript.
On a standard English-language keyboard, the character ^ appears as the shifted version of 6.
Mathematica therefore accepts 6 as an alternative to ^ . Note that if you are using something
other than a standard English-language keyboard, Mathematica will almost always accept 6 but
may not accept ^ .
This is an alternative input form that
avoids the use of control characters.
In[6]:= \!\( x \^ y \)
In[7]:= \!\( x \^ y + z \)
Out[6]= xy
Out[7]= xy z
Using control characters minimizes the number of keystrokes that you need to type in order to
enter a superscript. But particularly if you want to save your input in a file, or send it to another
program, it is often more convenient to use a form that does not involve control characters. You can
do this using \! sequences.
If you copy a \! sequence into Mathematica, it will automatically jump into two-dimensional form.
But if you enter the sequence directly from the keyboard, you explicitly need to choose the Make 2D
menu item in order to get the two-dimensional form.
When entered from the keyboard
\( . . . \) sequences are shown in literal
form.
\ \ x \ ^ y z \
xy z
x @ y
x - y
Subscripts in Mathematica work very much like superscripts. However, whereas Mathematica automatically interprets xy as x raised to the power y, it has no similar interpretation for xy . Instead, it
just treats xy as a purely symbolic object.
This enters y as a subscript.
In[8]:= x @ y
Out[8]= xy
178
x / y
In[9]:= \!\( x \_ y \)
Out[9]= xy
In[10]:= x / y
x
Out[10]=
y
In[11]:= x / y + z
x
Out[11]=
yz
8888
In[13]:=
2222
Out[13]= 4
@ x
2 x
In[15]:= @ x + y
Out[15]=
xy
In[17]:= \!\( \@ x + y \)
Out[17]=
x y
179
In[18]:= Sqrt[x] + y
Out[18]=
x y
^ or 6
@ or -
@ or 2
% or 5
/
Special input forms based on control characters. The second forms given should work on any keyboard.
Out[19]= xyz
\!\( ... \)
Out[20]= xyz
x \^ y
x \_ y
x \^ y \% z
\@ x
x \/ y
built-up fraction
x
y
Special input forms that generate two-dimensional input with the Make 2D menu item.
In[21]:= \!\(a \/ b + \@ c \) + d
a
Out[21]= c d
b
180
In[22]:= \!\(a \/ \( b + \@ c \) \) + d
a
Out[22]=
d
b c
In addition to subscripts and superscripts, Mathematica also supports the notion of underscripts
and overscriptselements that go directly underneath or above. Among other things, you can use
underscripts and overscripts to enter the limits of sums and products.
create an underscript x
create an underscript x
y
y
create an overscript x
create an overscript x
.
181
12 x
ArcTan
Log
1 x Log
1 x x2 Log
1 x x2 x3
3
3
6
9
3
12 x
ArcTan
Log
1 x Log
1 x x2 Log
1 x x2 x3
3
3
6
9
3
12 x
ArcTan
Log
1 x Log
1 x x2 Log
1 x x2 x3
3
3
6
9
3
12 x
ArcTan
Log
1 x Log
1 x x2 Log
1 x x2 x3
3
3
6
9
3
12 x
ArcTan
Log
1 x Log
1 x x2 Log
1 x x2 x3
3
3
6
9
3
12 x
ArcTan
Log
1 x Log
1 x x2 Log
1 x x2 x3
3
6
9
3
3
SHIFT-ENTER
SHIFT-CONTROL-ENTER or COMMAND-RETURN
In most computations, you will want to go from one step to the next by taking the whole expression
that you have generated, and then evaluating it. But if for example you are trying to manipulate a
single formula to put it into a particular form, you may instead find it more convenient to perform a
sequence of operations separately on different parts of the expression.
You do this by selecting each part you want to operate on, then inserting the operation you want
to perform, then using SHIFT-CONTROL-ENTER or COMMAND-RETURN.
Here is an expression with one part
selected.
182
short form
long form
symbol
,p,
\[Pi]
Pi
, inf ,
\[Infinity]
Infinity
, deg ,
\[Degree]
Degree
Special forms for some common symbols. , stands for the key .
In[1]:= Sin[60]
3
Out[1]=
2
Here is the long form of the input.
3
Out[2]=
2
You can enter the same input like this.
3
Out[3]=
2
Here the angle is in radians.
special characters
short form
long form
ordinary characters
xy
x H <= H y
x \[LessEqual] y
x <= y
xy
x H >= H y
x \[GreaterEqual] y
x >= y
xy
x H != H y
x \[NotEqual] y
x != y
xy
x H el H y
x \[Element] y
Element[x, y]
xy
x H -> H y
x \[Rule] y
x -> y
Special forms for a few operators. Pages 10241029 give a complete list.
183
3y
Out[5]=
4y
3y
Out[6]=
4y
In[7]:= x/(x+1) /. x 3 + y
As does this.
3y
Out[7]=
4y
In[8]:= x/(x+1) /. x , -> , 3 + y
Or this.
3y
Out[8]=
4y
The special arrow form # is by default
also used for output.
In[9]:= Solve[x^2 == 1, x]
Out[9]= x 1, x 1
special characters
short form
long form
ordinary characters
x
y
x H div H y
x \[Divide] y
x/y
xy
x H*H y
x \[Times] y
x*y
xy
x H cross H y
x \[Cross] y
Cross[x, y]
xy
x H == H y
x \[Equal] y
x == y
xy
x H l= H y
x \[LongEqual] y
x == y
xy
x H && H y
x \[And] y
x && y
xy
x H || H y
x \[Or] y
x || y
x
H!H x
\[Not] x
!x
xy
x H => H y
x \[Implies] y
Implies[x, y]
xy
x H un H y
x \[Union] y
Union[x, y]
xy
x H inter H y
x \[Intersection] y
Intersection[x, y]
xy
x H,H y
x \[InvisibleComma] y
x,y
fx
f H@H x
f \[InvisibleApplication] x
f @x or f[x]
Some operators with special forms used for input but not output.
184
In[10]:= x y
x
Out[10]=
y
The forms of input discussed so far in this section use special characters, but otherwise just consist of
ordinary one-dimensional lines of text. Mathematica notebooks, however, also make it possible to use
two-dimensional forms of input.
two-dimensional
xy
one-dimensional
x^y
power
x/y
division
Sqrt[x]
square root
x ^ (1/n)
nth root
sum
product
Integrate[f, x]
indefinite integral
definite integral
8x f
D[f, x]
partial derivative
8x,y f
D[f, x, y]
Part[expr, i, j, ... ]
part extraction
x
y
x
n
x
imax
f
i=imin
imax
( f
i=imin
f 7x
xmax
f 7x
xmin
expr+i,j,,
You can enter two-dimensional forms using any of the mechanisms discussed on pages 176
180. Note that upper and lower limits for sums and products must be entered as overscripts and
underscriptsnot superscripts and subscripts.
This enters an indefinite integral. Note
the use of , dd , to enter the
differential d.
185
1
Out[12]= Erf
x
2
Here is the usual Mathematica input for
this integral.
In[13]:= Integrate[Exp[-x^2], x]
1
Out[13]= Erf
x
2
1
Out[14]= Erf
x
2
short form
long form
, sum ,
\[Sum]
summation sign
, prod ,
\[Product]
product sign
, int ,
\[Integral]
integral sign
, dd ,
\[DifferentialD]
, pd ,
\[PartialD]
, [[ ,, , ]] ,
\[LeftDoubleBracket] , \[RightDoubleBracket]
part brackets
Some special characters used in entering formulas. Section 3.10 gives a complete list.
You should realize that even though a summation sign can look almost identical to a capital sigma
it is treated in a very different way by Mathematica. The point is that a sigma is just a letter; but a
summation sign is an operator which tells Mathematica to perform a Sum operation.
Capital sigma is just a letter.
In[15]:= a + \[CapitalSigma]^2
Out[15]= a I2
1
Out[16]=
f
n
n=0
1
Out[17]=
f
n
n=0
186
Much as Mathematica distinguishes between a summation sign and a capital sigma, it also distinguishes between an ordinary d and the special differential d 7 that is used in the standard notation
for integrals. It is crucial that you use this differential 7entered as ddwhen you type in an
integral. If you try to use an ordinary d, Mathematica will just interpret this as a symbol called dit
will not understand that you are entering the second part of an integration operator.
This computes the derivative of xn .
In[18]:= x xn
Out[18]= n x1n
In[19]:= D[x^n, x]
In[20]:= x,x,x xn
Out[19]= n x1n
In[21]:= D[x^n, x, x, x]
Out[21]= 2 n 1 n n x3n
In[1]:=
In[2]:=
In[3]:= MatrixFormTranspose
a b c
1 2 3
a 1%
"
'
$
$
'
$
b 2'
Out[3]//MatrixForm= $
'
'
$
'
$
c
3
&
#
a b c
1 2 3
,
J (CONTROL-ENTER)
TAB
(CONTROL-SPACE)
187
add a column
add a row
go to the next or element
move out of the table or matrix
Note that you can use , and J to start building up an array, and particularly for small
arrays this is often more convenient than using the Create Table/Matrix/Palette menu item.
Page 449 will describe how to adjust many aspects of the appearance of arrays you create in
Mathematica. The Create Table/Matrix/Palette menu item typically allows you to make basic adjustments,
such as drawing lines between rows or columns.
K
L
In[2]:= Factorx4n 1
188
@ or -
+ or =
^ or 6
& or 7
Special input forms based on control characters. The second forms given should work on any keyboard.
Just as ^ and @ go to superscript and subscript positions, so also & and = can be
used to go to positions directly above and below. With the layout of a standard English-language
keyboard & is directly to the right of ^ while = is directly to the right of @ .
key sequence
displayed form
expression form
x & _
OverBar[x]
x & , vec ,
x
x
OverVector[x]
x & M
OverTilde[x]
x & ^
OverHat[x]
x & .
OverDot[x]
x = _
UnderBar[x]
Here is x .
N
Out[4]= x
You can use x as a variable.
In[5]:= Solve[a^2 == %, a]
Out[5]=
N
N
a
x !, a
x !!
189
key sequence
displayed form
expression form
x \_ y
xy
Subscript[x, y]
x \+ y
Underscript[x, y]
x \^ y
xy
Superscript[x, y] (interpreted as
Power[x, y])
x \& y
Overscript[x, y]
x \&_
OverBar[x]
x \&\[RightVector]
x
x
x \&M
OverTilde[x]
x \&^
OverHat[x]
x \&.
OverDot[x]
x \+_
UnderBar[x]
OverVector[x]
Ways to enter modifiers without control keys. All these forms can be used only inside \!\( . . . \).
190
full name
alias
full name
alias
a`
[AGrave]
, a` ,
[OSlash]
, o/ ,
[ARing]
, ao ,
[ODoubleDot]
, o" ,
[ADoubleDot]
, a" ,
u`
[UGrave]
, u` ,
[CCedilla]
, c, ,
[UDoubleDot]
, u" ,
[CHacek]
, cv ,
[SZ]
, sz , , , ss ,
[EAcute]
, e' ,
[CapitalARing]
, Ao ,
e`
[EGrave]
, e` ,
[CapitalADoubleDot]
, A" ,
[IAcute]
, i' ,
[CapitalODoubleDot]
, O" ,
[NTilde]
, nM ,
[CapitalUDoubleDot]
, U" ,
o`
[OGrave]
, o` ,
In[1]:= Lam\[EAcute][x, y]
Out[1]= Lam
x, y
In[2]:= Lam, e' ,[x, y]
Out[2]= Lam
x, y
You should realize that there is no uniform standard for computer keyboards around the world,
and as a result it is inevitable that some details of what has been said in this chapter may not apply
to your keyboard.
In particular, the identification for example of 6 with ^ is valid only for keyboards on
which ^ appears as SHIFT-6. On other keyboards, Mathematica uses 6 to go to a superscript
position, but not necessarily ^ .
Regardless of how your keyboard is set up you can always use palettes or menu items to set up
superscripts and other kinds of notation. And assuming you have some way to enter characters such
as \, you can always give input using full names such as \[Infinity] and textual forms such as
\(x\/y\).
In[1]:= {17 5, 8 3}
Out[1]= 17 O 5, 8 O 3
191
In[2]:= x_ y_ := Mod[x + y, 2]
In[3]:= {17 5, 8 3}
Out[3]= 0, 1
full name
alias
full name
alias
[CirclePlus]
, c+ ,
[LongRightArrow]
, --> ,
[CircleTimes]
, c* ,
[LeftRightArrow]
, <-> ,
[PlusMinus]
, +- ,
[UpArrow]
[Wedge]
,^,
S
[Equilibrium]
[Vee]
,v,
[RightTee]
[TildeEqual]
, M= ,
[Superset]
[TildeTilde]
, MM ,
[SquareIntersection]
[Tilde]
,M,
U
[Element]
, elem ,
[Proportional]
, prop ,
[NotElement]
, !elem ,
[Congruent]
, === ,
[SmallCircle]
, sc ,
[GreaterTilde]
, >M ,
[Therefore]
[GreaterGreater]
[VerticalSeparator]
,|,
[Succeeds]
[VerticalBar]
, | ,
[RightTriangle]
[Backslash]
,\,
, equi ,
, sup ,
In[4]:= {3 4, 3 4, 3 4, 3 4}
Out[4]= False, False, 3 4, 3 4
There are some forms which look like characters on a standard keyboard, but which are interpreted
in a different way by Mathematica. Thus, for example, \[Backslash] or , \ , displays as \ but is not
interpreted in the same way as a \ typed directly on the keyboard.
The - and characters used here are
different from the \ and ^ you would
type directly on a keyboard.
In[5]:= {a H \ H b, a H ^ H b}
Out[5]= a - b, a . b
Most operators work like O and go in between their operands. But some operators can go in other
places. Thus, for example, , < , and , > , or \[LeftAngleBracket] and \[RightAngleBracket] are
effectively operators which go around their operand.
The elements of the angle bracket
operator go around their operand.
192
full name
alias
full name
alias
[ScriptL]
, scl ,
[Angstrom]
, Ang ,
[ScriptCapitalE]
, scE ,
[HBar]
, hb ,
[GothicCapitalR]
, goR ,
[Sterling]
[DoubleStruckCapitalZ]
, dsZ ,
[Angle]
[Aleph]
, al ,
[Bullet]
, bu ,
[EmptySet]
, es ,
[Dagger]
, dg ,
[Micro]
, mi ,
[Natural]
InputForm
OutputForm
StandardForm
TraditionalForm
y2
Out[1]= x2
z
193
y2
In[2]:= x2
z
y2
Out[2]= x2
z
InputForm is the most general form of input for Mathematica: it works whether you are using a
notebook interface or a text-based interface.
With a notebook interface, output is by
default produced in StandardForm .
1
x
2 y
With a notebook interface, the default form for both input and output is StandardForm .
The basic idea of StandardForm is to provide a precise but elegant representation of Mathematica
expressions, making use of special characters, two-dimensional positioning, and so on.
Both input and output are given here
in StandardForm .
1
In[5]:= x
x3 1
12 x
ArcTan
1
1
3
Out[5]=
Log
1 x Log
1 x x2
3
6
3
12x
ArcTan
Log1 x Log1 x x2
3
In[6]:=
6
3
3
12 x
ArcTan
1
1
3
Out[6]=
Log
1 x Log
1 x x2
3
6
3
The precise nature of StandardForm prevents it from following all of the somewhat haphazard conventions of traditional mathematical notation. Mathematica however also supports TraditionalForm ,
which uses a large collection of rules to give a rather complete rendition of traditional mathematical
notation.
TraditionalForm uses lower-case
names for functions, and puts their
arguments in parentheses rather than
square brackets.
Here are a few transformations made
by TraditionalForm .
1
In[7]:= x TraditionalForm
x3 1
2 x1
tan1 \\\\\\\\\\\\\\\
\
1
1
3
Out[7]//TraditionalForm= \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ \\\\\\\ logx 1 \\\\\\\ logx2 x 1
3
6
3
i
Out[8]//TraditionalForm= x, tan1 x, J0 x,
j
194
TraditionalForm is often useful for generating output that can be inserted directly into documents
which use traditional mathematical notation. But you should understand that TraditionalForm is
intended primarily for output: it does not have the kind of precision that is needed to provide reliable
input to Mathematica.
Thus, for example, in TraditionalForm , Ci(x) is the representation for both Ci[x] and
CosIntegral[x] , so if this form appears on its own as input, Mathematica will have no idea which of
the two interpretations is the correct one.
In StandardForm , these three
expressions are all displayed in a
unique and unambiguous way.
In TraditionalForm , however, the first
two are impossible to distinguish, and
the third differs only in the presence of
an extra space.
The ambiguities of TraditionalForm make it in general unsuitable for specifying input to the
Mathematica kernel. But at least for sufficiently simple cases, Mathematica does include various heuristic rules for trying to interpret TraditionalForm expressions as Mathematica input.
Cells intended for input to the kernel
are assumed by default to contain
StandardForm expressions.
In[1]:=
1
c
x
x
x
Out[1]=
1
c x x /
x
In[1]:=
1
c x x
x
Out[1]=
1
c x Gamma
x
x
195
even if you edit the expression, the tags will often be left sufficiently undisturbed that unambiguous
interpretation will still be possible.
This generates output in
TraditionalForm .
Out[11]//TraditionalForm= x
Out[12]//StandardForm= x
Out[13]//StandardForm= 2 x
If you enter a TraditionalForm expression from scratch, or import it from outside Mathematica,
then Mathematica will still do its best to guess what the expression means. When there are ambiguities,
what it typically does is to assume that you are using notation in whatever way is more common in
elementary mathematical applications.
In TraditionalForm input, this is
interpreted as a derivative.
y x
In[15]:= tan
1 x
StandardForm
Out[15]//StandardForm= ArcTan
x
In[16]:= tan2 x
StandardForm
In[17]:= tan
2 x
StandardForm
Out[16]//StandardForm= Tan x
Out[17]//StandardForm= Cot x
You should realize that TraditionalForm does not provide any kind of precise or complete way of
specifying Mathematica expressions. Nevertheless, for some elementary purposes it may be sufficient,
particularly if you use a few additional tricks.
196
In[18]:= f 1 x
g 1 x
StandardForm
Out[18]//StandardForm= f 1 x g 1 x
( or 9
) or 0
2]x1
tan1 \\\\\\\\\\\\\\\\\
\
logx x1
logx1
1
3
This is a text cell, but it can contain formulas such as \\\\\\\\\\\\\
\ ]( x or \\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ \\\\\\\\\\\\\\\\\\\\
\ . The formulas
x3 1
6
3
3
flow with the text.
2
Mathematica notebooks often contain both formulas that are intended for actual evaluation by
Mathematica, and ones that are intended just to be read in a more passive way.
When you insert a formula in text, you can use the Convert to StandardForm and Convert to
TraditionalForm menu items within the formula to convert it to StandardForm or TraditionalForm .
197
In general, however, you can use exactly the same mechanisms for entering formulas, whether or
not they will ultimately be given as Mathematica input.
You should realize, however, that to make the detailed typography of typical formulas look as good
as possible, Mathematica automatically does things such as inserting spaces around certain operators.
But these kinds of adjustments can potentially be inappropriate if you use notation in very different
ways from the ones Mathematica is expecting.
In such cases, you may have to make detailed typographical adjustments by hand, using the
mechanisms discussed on page 449.
ScreenStyleEnvironment
PrintingStyleEnvironment
Working
Presentation
Condensed
Printout
A Symbolic Sum
Here is the input:
m
1
nn 42
n1
198
A Symbolic Sum
Here is the input:
m
1
nn 42
n1
A Symbolic Sum
Here is the input:
m
1
nn 42
n1
Set up a blank palette using Create Table/Matrix/Palette under the Input menu
Fill in the contents
Make the palette active using Generate Palette from Selection under the File menu
The basic steps in creating a palette.
Create Table/Matrix/Palette will create a
blank palette.
1 2 2
199
1 2 2
Create Table/Matrix/Palette
Generate Palette from Selection
Generate Notebook from Palette
Edit Button
1
x y
2 2
When you are creating a palette, you can use the same mechanisms to add columns and rows as
you can when you are creating any other kind of table, matrix or grid. Thus , will add a new
column of buttons, and J (CONTROL-ENTER) will add a new row.
button contents
X
text containing XY
action
Contents of buttons.
In the simplest case, when you press a button in a palette what will happen is that the contents of
the button will be inserted into your notebook, replacing whatever your current selection was.
Sometimes however you may not simply want to overwrite your current selection, but rather you
may want to modify the selection in some way. As an example, you might want to wrap a function
like Expand around your current selection.
You can do this by setting up a button with contents Expand[]. The can be entered as , spl ,
or \[SelectionPlaceholder] . In general, serves as a placeholder for your current selection. When
you press a button that contains , the is first replaced by your current selection, and only then is
the result inserted into your notebook.
Here is a cell in which the current
selection is part of an expression.
1 1 x4 2 y3
200
Mathematica allows you to associate any action you want with a button. You can set up some
common actions by using the Edit Button menu, having selected either a single button or a whole
palette.
Paste
Evaluate
EvaluateCell
CopyEvaluate
copy the current selection into a new cell, then paste and
evaluate in place
CopyEvaluateCell
copy the current selection into a new cell, then paste and
evaluate the whole cell
With the default Paste setting for a button action, pressing the button modifies the contents of a
cell but does no evaluation. By choosing other button actions, however, you can tell Mathematica to
perform an evaluation every time you press the button.
With the button action Evaluate the result of this evaluation is made to overwrite your current
selection. This is useful if you want to set up a button which modifies parts of an expression in place,
say by applying Expand[] to them.
The button action Evaluate performs evaluation only on whatever was pasted into your current
cell. The button action EvaluateCell , on the other hand, performs evaluation on the whole cell,
generating a new cell to show the result.
Here is an expression with a part
selected.
1 1 x4 2 y3
Sometimes it is useful to be able to extract the current selection from a cell, and then operate on it
in a new cell. You can do this using the button actions CopyEvaluate and CopyEvaluateCell .
201
1 1 x4 2 y3
Create Table/Matrix/Palette
Create Button
1 1 x4 2 y3
In[1]:=
Expand2 y3
Out[1]=
8 12 y 6 y2 y3
Mathematica allows you to set up a wide range of active elements in the notebook front end. In the
most common case, you have a palette which consists of an array of buttons in a separate window.
But you can also have arrays of buttons, or even single buttons, within the cells of an ordinary
notebook.
In addition, you can make a button execute any action you wantperforming computations in
the Mathematica kernel, or changing the configuration of notebooks in the front end. Section 2.11.6
discusses how to do this.
A hyperlink is a special kind of button which jumps to another part of a notebook when it is pressed.
Typically hyperlinks are indicated in Mathematica by blue or underlined text.
To set up a hyperlink, just select the text or other object that you want to be a hyperlink. Then
choose the menu item Create Hyperlink and fill in the specification of where you want the destination
of the hyperlink to be.
202
1. A Section
2. A Section
3. A Section
x
7 x
x1
(1)
Sin
x
7x
x1
(2)
Log
x Exp
x
7x
x1
(3)
203
less of your subject matter, you never have to go back and reexplain your basic notation: it is always
just the notation of the Mathematica language. In addition, if you set up your explanations in terms of
Mathematica expressions, then a reader of your notebook can immediately take what you have given,
and actually execute it as Mathematica input.
If one has spent many years working with traditional mathematical notation, then it takes a little
time to get used to seeing mathematical facts presented as StandardForm Mathematica expressions.
Indeed, at first one often has a tendency to try to use TraditionalForm whenever possible, perhaps
with hidden tags to indicate its interpretation. But quite soon one tends to evolve to a mixture of
StandardForm and TraditionalForm . And in the end it becomes clear that StandardForm alone is
for most purposes the most effective form of presentation.
In traditional mathematical exposition, there are many tricks for replacing chunks of text by fragments of formulas. In StandardForm many of these same tricks can be used. But the fact that
Mathematica expressions can represent not only mathematical objects but also procedures and algorithms increases greatly the extent to which chunks of text can be replaced by shorter and more precise
material.
204
<< name
expr >> name
expr >>> name
!!name
In[2]:= !!tmp
In[3]:= <<tmp
Out[3]= x3 3 x2 y 3 x y2 y3
If you are familiar with Unix or MS-DOS operating systems, you will recognize the Mathematica
redirection operators >>, >>> and << as being analogous to the shell operators >, >> and <.
The redirection operators >> and >>> are convenient for storing results you get from Mathematica.
The function Save["name", f, g, ... ] allows you to save definitions for variables and functions.
Save["name", f, g, ... ]
In[5]:= c = 17
Out[5]= 17
205
In[6]:= Save["ftmp", f]
In[7]:= !!ftmp
In[8]:= Clear[f, c]
In[9]:= <<ftmp
f[x_] := x^2 + c
c = 17
file.m
Out[9]= 17
file.nb
file.mx
If you use a notebook interface to Mathematica, then the Mathematica front end allows you to save
complete notebooks, including not only Mathematica input and output, but also text, graphics and
other material.
It is conventional to give Mathematica notebook files names that end in .nb, and most versions of
Mathematica enforce this convention.
When you open a notebook in the Mathematica front end, Mathematica will immediately display
the contents of the notebook, but it will not normally send any of these contents to the kernel for
evaluation until you explicitly request this to be done.
Within a Mathematica notebook, however, you can use the Cell menu in the front end to identify
certain cells as initialization cells, and if you do this, then the contents of these cells will automatically
be evaluated whenever you open the notebook.
The I in the cell bracket indicates that
the second cell is an initialization cell
that will be evaluated whenever the
notebook is opened.
Implementation
fx_ : Logx Log1 x
206
Directory[ ]
SetDirectory["dir"]
FileNames[ ]
FileNames["form"]
<<name
<<context`
CopyFile["file ", "file "]
DeleteFile["file"]
In[1]:= Directory[ ]
In[2]:= SetDirectory["Examples"]
In[3]:= FileNames["Test*.m"]
Out[1]= /users/sw
Out[2]= /users/sw/Examples
Although you usually want to create files only in your current working directory, you often need
to read in files from other directories. As a result, when you ask Mathematica to read in a file with a
particular name, Mathematica automatically searches a list of directories (specified by the value of the
search path variable $Path) to try and find a file with that name.
One issue in handling files in Mathematica is that the form of file and directory names varies between
computer systems. This means for example that names of files which contain standard Mathematica
packages may be quite different on different systems. Through a sequence of conventions, it is however possible to read in a standard Mathematica package with the same command on all systems. The
way this works is that each package defines a so-called Mathematica context, of the form name`name`.
On each system, all files are named in correspondence with the contexts they define. Then when you
207
use the command <<name`name` Mathematica automatically translates the context name into the file
name appropriate for your particular computer system.
FindList["file", "text"]
FindList[FileNames[ ], "text"]
In[2]:= !!out.dat
Out[1]= out.dat
5.7
-1.2
4.3
7.8
Import["file", "Table"] will handle many kinds of tabular data, automatically deducing the details
of the format whenever possible. Export["file", list, "Table"] writes out data separated by spaces,
with numbers given in C or Fortran-like form, as in 2.3E5 and so on.
Import["name.ext"]
Export["name.ext", expr]
Importing and exporting general data.
208
table formats
matrix formats
"CSV", "TSV"
"MAT", "HDF", "MTX"
"FITS", "SDTS"
Import and Export can handle not only tabular data, but also data corresponding to graphics,
sounds, expressions and even whole documents. Import and Export can often deduce the appropriate format for data simply by looking at the extension of the file name for the file in which the data is
being stored. Sections 2.10.19 and 2.12.7 discuss in more detail how Import and Export work. Note
that you can also use Import and Export to manipulate raw files of binary data.
This imports a graphic in JPEG format.
In[4]:= Import["turtle.jpg"]
Out[4]= AGraphicsA
In[5]:= Show[%]
$ImportFormats
$ExportFormats
209
Export["name.ext", graphics]
Export["file", graphics, "format"]
Export["!command", graphics, "format"]
graphics formats
sound formats
Some common formats for graphics and sounds. Page 568 gives a complete list.
2
1.5
1
0.5
2
10
-0.5
-1
In[2]:= Export["sinplot.eps", %]
Display::pserr:
PostScript language error:
Warning: substituting font Courier for WriCMTT9
Out[2]= sinplot.eps
210
12 x
ArcTan
Log
1 x Log
1 x x2
3
3
6
3
Mathematica allows you to export formulas both textually and visually. You can use Export to tell
Mathematica to write a visual representation of a formula into a file.
Export["file.eps", ToBoxes[expr]]
save the visual form of expr to a file in EPS format
Export["file", ToBoxes[expr], "format"]
save the visual form of expr in the specified format
Exporting expressions in visual form.
TeXForm[expr]
In[2]:= TeXForm[%]
TeXSave["file.tex"]
TeXSave["file.tex", "source.nb"]
Converting complete notebooks to TEX.
x y
Out[1]=
xy
211
In addition to being able to convert individual expressions to TEX, Mathematica also provides capabilities for translating complete notebooks. These capabilities can usually be accessed from the Save As
Special menu in the notebook front end, where various options can be set.
HTMLSave["file.html"]
HTMLSave["file.html", "source.nb"]
HTMLSave has many options that allow you to specify how notebooks should be converted for web
browsers with different capabilities. You can find details in the Additional Information section of the
online Reference Guide entry for HTMLSave .
MathMLForm[expr]
MathMLForm[StandardForm[expr]]
ToExpression["string", MathMLForm]
In[1]:= MathMLForm[x^2/z]
Out[1]//MathMLForm= <math>
<mfrac>
<msup>
<mi>x</mi>
<mn>2</mn>
</msup>
<mi>z</mi>
</mfrac>
</math>
If you paste MathML into a Mathematica notebook, Mathematica will automatically try to convert
it to Mathematica input. You can copy an expression from a notebook as MathML using the Copy As
menu in the notebook front end.
212
Export["file.xml", expr]
Import["file.xml"]
ImportString["string", "XML"]
Somewhat like Mathematica expressions, XML is a general format for representing data. Mathematica
automatically converts certain types of expressions to and from specific types of XML. MathML is one
example. Other examples include NotebookML for notebook expressions, and SVG for graphics.
If you ask Mathematica to import a generic piece of XML, it will produce a SymbolicXML expression. Each XML element of the form <elem attr='val'>data</elem> is translated to a Mathematica
SymbolicXML expression of the form XMLElement["elem", {"attr"->"val"}, {data}]. Once you have
imported a piece of XML as SymbolicXML, you can use Mathematicas powerful symbolic programming capabilities to manipulate the expression you get. You can then use Export to export the result
in XML form.
This generates a SymbolicXML
expression, with an XMLElement
representing the a element in the XML
string.
In[3]:= ImportString[
"<a><b bb='1'>ss</b><b bb='2'>ss</b></a>", "XML"]
Out[5]= ?a>
?b bb='1'>
?c>xx?c>
?b>
?b bb='2'>
?c>xx?c>
?b>
?a>
213
CForm[expr]
FortranForm[expr]
In[2]:= FortranForm[%]
Out[1]= 1 2 x x2 2 y 2 x y y2
In[3]:= CForm[%]
Out[3]//CForm= 1 + 2*x + Power(x,2) + 2*y + 2*x*y + Power(y,2)
You should realize that there are many differences between Mathematica and C or Fortran. As a
result, expressions you translate may not work exactly the same as they do in Mathematica. In addition,
there are so many differences in programming constructs that no attempt is made to translate these
automatically.
Compile[x, expr]
One of the common motivations for converting Mathematica expressions into C or Fortran is to try
to make them faster to evaluate numerically. But the single most important reason that C and Fortran
can potentially be more efficient than Mathematica is that in these languages one always specifies up
front what type each variable one uses will beinteger, real number, array, and so on.
The Mathematica function Compile makes such assumptions within Mathematica, and generates
highly efficient internal code. Usually this code runs not much if at all slower than custom C or
Fortran.
214
Splice["file.mx"]
Splice["infile", "outfile"]
The basic idea is to set up the definitions you need in a particular Mathematica session, then run
Splice to use the definitions you have made to produce the appropriate output to insert into the
external files.
#include "mdefs.h"
double f(x)
double x;
{
double y;
y = <* Integrate[Sin[x]^5, x] *> ;
return(2*y - 1) ;
}
A simple C program containing a Mathematica formula.
#include "mdefs.h"
double f(x)
double x;
{
double y;
y = -5*Cos(x)/8 + 5*Cos(3*x)/48 - Cos(5*x)/80 ;
return(2*y - 1) ;
}
The C program after processing with Splice.
215
<<file
read in a file
<<"!command"
ReadList["!command", Number]
In[2]:= !squares 4
1
2
3
4
1
4
9
16
216
1.11.11 MathLink
The previous section discussed how to exchange plain text with external programs. In many cases,
however, you will find it convenient to communicate with external programs at a higher level, and to
exchange more structured data with them.
On almost all computer systems, Mathematica supports the MathLink communication standard, which
allows higher-level communication between Mathematica and external programs. In order to use MathLink, an external program has to include some special source code, which is usually distributed with
Mathematica.
MathLink allows external programs both to call Mathematica, and to be called by Mathematica. Section 2.13 discusses some of the details of MathLink. By using MathLink, you can, for example, treat
Mathematica essentially like a subroutine embedded inside an external program. Or you can create a
front end that implements your own user interface, and communicates with the Mathematica kernel
via MathLink.
You can also use MathLink to let Mathematica call individual functions inside an external program.
As described in Section 2.13, you can set up a MathLink template file to specify how particular functions
in Mathematica should call functions inside your external program. From the MathLink template file,
you can generate source code to include in your program. Then when you start your program, the appropriate Mathematica definitions are automatically made, and when you call a particular Mathematica
function, code in your external program is executed.
Install["command"]
Uninstall[link]
In[1]:= Install["simul"]
In[2]:= ?srun
In[4]:= Uninstall["simul"]
Out[1]= LinkObject[simul, 5, 4]
Out[3]= 6.78124
Out[4]= simul
1.11.11 MathLink
217
You can use MathLink to communicate with many types of programs, including with Mathematica
itself. There are versions of the MathLink library for a variety of common programming languages.
The J/Link system provides a standard way to integrate Mathematica with Java, based on MathLink.
With J/Link you can take any Java class, and immediately make its methods accessible as functions in
Mathematica.
218
In[2]:= Together[%]
1
Out[1]= Log
x
x
1 x Log
x
Out[2]=
x
219
In numerical computations, a similar phenomenon occurs. Thus, for example, FindRoot gives you
a root of a function. But if there are several roots, which root is actually returned depends on the
details of how FindRoot works inside.
This finds a particular root of
cosx sinx.
Out[3]= x 14.9226
Out[4]= x 11.781
The dependence on the details of internal algorithms can be more significant if you push approximate numerical computations to the limits of their validity.
Thus, for example, if you give NIntegrate a pathological integrand, whether it yields a meaningful
answer or not can depend on the details of the internal algorithm that it uses.
NIntegrate knows that this result is
unreliable, and can depend on the
details of the internal algorithm, so it
prints warning messages.
Out[5]= 0.504894
Traditional numerical computation systems have tended to follow the idea that all computations
should yield results that at least nominally have the same precision. A consequence of this idea is
that it is not sufficient just to look at a result to know whether it is accurate; you typically also have
to analyze the internal algorithm by which the result was found. This fact has tended to make people
believe that it is always important to know internal algorithms for numerical computations.
But with the approach that Mathematica takes, this is rarely the case. For Mathematica can usually
use its arbitrary-precision numerical computation capabilities to give results where every digit that is
generated follows the exact mathematical specification of the operation being performed.
Even though this is an approximate
numerical computation, every digit is
determined by the mathematical
definition for .
Out[6]= 3.14159265358979323846264338328
Out[7]= 0.78967249342931008271
220
In[8]:= Sin[10.^50]
Out[8]= 0.705222
It is a general characteristic that whenever the results you get can be affected by the details of
internal algorithms, you should not depend on these results. For if nothing else, different versions
of Mathematica may exhibit differences in these results, either because the algorithms operate slightly
differently on different computer systems, or because fundamentally different algorithms are used in
versions released at different times.
This is the result for sin on one
type of computer.
In[1]:= Sin[10.^50]
Out[1]= 0.705222
In[1]:= Sin[10.^50]
In[1]:= Sin[10.^50]
Out[1]= -0.0528229
Out[1]= 0.0937538
221
When you type input into Mathematica, a data structure is created in the memory of your computer to
represent the expression you have entered.
In general, different pieces of your expression will be stored at different places in memory. Thus,
for example, for a list such as {2, x, y + z} the backbone of the list will be stored at one place,
while each of the actual elements will be stored at a different place.
The backbone of the list then consists just of three pointers that specify the addresses in computer
memory at which the actual expressions that form the elements of the list are to be found. These
expressions then in turn contain pointers to their subexpressions. The chain of pointers ends when
one reaches an object such as a number or a string, which is stored directly as a pattern of bits in
computer memory.
Crucial to the operation of Mathematica is the notion of symbols such as x. Whenever x appears in
an expression, Mathematica represents it by a pointer. But the pointer is always to the same place in
computer memoryan entry in a central table of all symbols defined in your Mathematica session.
This table is a repository of all information about each symbol. It contains a pointer to a string
giving the symbols name, as well as pointers to expressions which give rules for evaluating the
symbol.
Every piece of memory used by Mathematica maintains a count of how many pointers currently
point to it. When this count drops to zero, Mathematica knows that the piece of memory is no longer
being referenced, and immediately makes the piece of memory available for something new.
This strategy essentially ensures that no memory is ever wasted, and that any piece of memory that
Mathematica uses is actually storing data that you need to access in your Mathematica session.
At the heart of Mathematica is a conceptually simple procedure known as the evaluator which takes
every function that appears in an expression and evaluates that function.
222
When the function is one of the thousand or so that are built into Mathematica, what the evaluator
does is to execute directly internal code in the Mathematica system. This code is set up to perform the
operations corresponding to the function, and then to build a new expression representing the result.
A crucial feature of the built-in functions in Mathematica is that they support universal computation.
What this means is that out of these functions you can construct programs that perform absolutely
any kinds of operation that are possible for a computer.
As it turns out, small subsets of Mathematicas built-in functions would be quite sufficient to support
universal computation. But having the whole collection of functions makes it in practice easier to
construct the programs one needs.
The underlying point, however, is that because Mathematica supports universal computation you
never have to modify its built-in functions: all you have to do to perform a particular task is to
combine these functions in an appropriate way.
Universal computation is the basis for all standard computer languages. But many of these languages rely on the idea of compilation. If you use C or Fortran, for example, you first write your
program, then you compile it to generate machine code that can actually be executed on your
computer.
Mathematica does not require you to go through the compilation step: once you have input an
expression, the functions in the expression can immediately be executed.
Often Mathematica will preprocess expressions that you enter, arranging things so that subsequent
execution will be as efficient as possible. But such preprocessing never affects the results that are
generated, and can rarely be seen explicitly.
223
But in Mathematica symbolic integration is performed by a fairly small number of very systematic
procedures. For indefinite integration, the idea of these procedures is to find the most general form
of the integral, then to differentiate this and try to match up undetermined coefficients.
Often this procedure produces at an intermediate stage immensely complicated algebraic expressions, and sometimes very sophisticated kinds of mathematical functions. But the great advantage of
the procedure is that it is completely systematic, and its operation requires no special cleverness of
the kind that only a human could be expected to provide.
In having Mathematica do integrals, therefore, one can be confident that it will systematically get
results, but one cannot expect that the way these results are derived will have much at all to do with
the way they would be derived by hand.
The same is true with most of the mathematical algorithms in Mathematica. One striking feature
is that even for operations that are simple to describe, the systematic algorithms to perform these
operations in Mathematica involve fairly advanced mathematical or computational ideas.
Thus, for example, factoring a polynomial in x is first done modulo a prime such as 17 by finding
the null space of a matrix obtained by reducing high powers of x modulo the prime and the original
polynomial. Then factorization over the integers is achieved by lifting modulo successive powers
of the prime using a collection of intricate theorems in algebra and analysis.
The use of powerful systematic algorithms is important in making the built-in functions in Mathematica able to handle difficult and general cases. But for easy cases that may be fairly common in
practice it is often possible to use simpler and more efficient algorithms.
As a result, built-in functions in Mathematica often have large numbers of extra pieces that handle
various kinds of special cases. These extra pieces can contribute greatly to the complexity of the
internal code, often taking what would otherwise be a five-page algorithm and making it hundreds
of pages long.
Most of the algorithms in Mathematica, including all their special cases, were explicitly constructed
by hand. But some algorithms were instead effectively created automatically by computer.
Many of the algorithms used for machine-precision numerical evaluation of mathematical functions
are examples. The main parts of such algorithms are formulas which are as short as possible but
which yield the best numerical approximations.
Most such formulas used in Mathematica were actually derived by Mathematica itself. Often many
months of computation were required, but the result was a short formula that can be used to evaluate
functions in an optimal way.
224
225
Despite these changes in internal code, however, the user-level design of Mathematica has remained compatible from Version 1 on. Much functionality has been added, but programs created for
Mathematica Version 1 will almost always run absolutely unchanged under Version 5.
226
Even with all this testing, however, it is inevitable in a system as complex as Mathematica that errors
will remain.
The standards of correctness for Mathematica are certainly much higher than for typical mathematical proofs. But just as long proofs will inevitably contain errors that go undetected for many years, so
also a complex software system such as Mathematica will contain errors that go undetected even after
millions of people have used it.
Nevertheless, particularly after all the testing that has been done on it, the probability that you will
actually discover an error in Mathematica in the course of your work is extremely low.
Doubtless there will be times when Mathematica does things you do not expect. But you should
realize that the probabilities are such that it is vastly more likely that there is something wrong with
your input to Mathematica or your understanding of what is happening than with the internal code of
the Mathematica system itself.
If you do believe that you have found a genuine error in Mathematica, then you should contact
Wolfram Research Technical Support, so that the error can be corrected in future versions.
Part 2
Part 1 introduced Mathematica by showing you how to use some of its
more common features. This part looks at Mathematica in a different way.
Instead of discussing individual features, it concentrates on the global
structure of Mathematica, and describes the framework into which all
the features fit.
When you first start doing calculations with Mathematica, you
will probably find it sufficient just to read the relevant parts of Part 1.
However, once you have some general familiarity with the Mathematica
system, you should make a point of reading this part.
This part describes the basic structure of the Mathematica language,
with which you can extend Mathematica, adding your own functions,
objects or other constructs. This part shows how Mathematica uses a
fairly small number of very powerful symbolic programming methods
to allow you to build up many different kinds of programs.
Most of this part assumes no specific prior knowledge of computer
science. Nevertheless, some of it ventures into some fairly complicated
issues. You can probably ignore these issues unless they specifically affect
programs you are writing.
If you are an expert on computer languages, you may be able to glean
some understanding of Mathematica by looking at the Reference Guide
at the end of this book. Nevertheless, to get a real appreciation for the
principles of Mathematica, you will have to read this part.
Part 2
Principles of Mathematica
2.1
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 230
2.2
2.3
Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
2.4
2.5
2.6
2.7
2.8
2.9
2.10
2.11
2.12
2.13
2.14
230
2.1 Expressions
2.1.1 Everything Is an Expression
Mathematica handles many different kinds of things: mathematical formulas, lists and graphics, to
name a few. Although they often look very different, Mathematica represents all of these things in one
uniform way. They are all expressions.
A prototypical example of a Mathematica expression is f[x, y]. You might use f[x, y] to represent
a mathematical function fx y. The function is named f, and it has two arguments, x and y.
You do not always have to write expressions in the form f [x, y, ... ]. For example, x + y is also
an expression. When you type in x + y, Mathematica converts it to the standard form Plus[x, y].
Then, when it prints it out again, it gives it as x + y.
The same is true of other operators, such as ^ (Power) and / (Divide).
In fact, everything you type into Mathematica is treated as an expression.
x+y+z
xyz
x^n
{a, b, c}
Plus[x, y, z]
Times[x, y, z]
Power[x, n]
List[a, b, c]
a -> b
Rule[a, b]
a=b
Set[a, b]
You can see the full form of any expression by using FullForm[expr] .
Here is an expression.
In[1]:= x + y + z
Out[1]= x y z
In[2]:= FullForm[%]
Out[2]//FullForm= Plus
x, y, z
Out[3]= 1 x2 y z
In[4]:= FullForm[%]
Out[4]//FullForm= Plus
1, Power
x, 2, Power
Plus
y, z, 2
231
The object f in an expression f [x, y, ... ] is known as the head of the expression. You can extract it
using Head[expr]. Particularly when you write programs in Mathematica, you will often want to test
the head of an expression to find out what kind of thing the expression is.
Head gives the function name f.
In[6]:= Head[a + b + c]
Out[6]= Plus
Out[7]= List
In[8]:= Head[23432]
Out[8]= Integer
Head[expr]
FullForm[expr]
In[9]:= Head[345.6]
Out[9]= Real
232
meaning of f
meaning of x, y,
examples
Function
arguments or parameters
Sin[x], f[x, y]
Command
arguments or parameters
Expand[(x + 1)^2]
Operator
operands
x + y, a = b
Head
elements
{a, b, c}
Object type
contents
RGBColor[r, g, b]
Expressions in Mathematica are often used to specify operations. So, for example, typing in 2 + 3
causes 2 and 3 to be added together, while Factor[x^6 - 1] performs factorization.
Perhaps an even more important use of expressions in Mathematica, however, is to maintain a structure, which can then be acted on by other functions. An expression like {a, b, c} does not specify
an operation. It merely maintains a list structure, which contains a collection of three elements. Other
functions, such as Reverse or Dot, can act on this structure.
The full form of the expression {a, b, c} is List[a, b, c]. The head List performs no operations.
Instead, its purpose is to serve as a tag to specify the type of the structure.
You can use expressions in Mathematica to create your own structures. For example, you might
want to represent points in three-dimensional space, specified by three coordinates. You could give
each point as point[x, y, z]. The function point again performs no operation. It serves merely
to collect the three coordinates together, and to label the resulting object as a point.
You can think of expressions like point[x, y, z] as being packets of data, tagged with a particular head. Even though all expressions have the same basic structure, you can distinguish different
types of expressions by giving them different heads. You can then set up transformation rules and
programs which treat different types of expressions in different ways.
233
a higher precedence than +. In general, the arguments of operators with higher precedence are grouped
before those of operators with lower precedence.
You should realize that absolutely every special input form in Mathematica is assigned a definite
precedence. This includes not only the traditional mathematical operators, but also forms such as ->,
:= or the semicolons used to separate expressions in a Mathematica program.
The table on pages 10241029 gives all the operators of Mathematica in order of decreasing precedence. The precedence is arranged, where possible, to follow standard mathematical usage, and to
minimize the number of parentheses that are usually needed.
You will find, for example, that relational operators such as < have lower precedence than arithmetic operators such as +. This means that you can write expressions such as x + y > 7 without using
parentheses.
There are nevertheless many cases where you do have to use parentheses. For example, since ; has
a lower precedence than =, you need to use parentheses to write x = ( a ; b ). Mathematica interprets
the expression x = a ; b as (x = a) ; b. In general, it can never hurt to include extra parentheses,
but it can cause a great deal of trouble if you leave parentheses out, and Mathematica interprets your
input in a way you do not expect.
f [x, y]
f@x
x // f
xMfMy
There are several common types of operators in Mathematica. The + in x + y is an infix operator. The - in -p is a prefix operator. Even when you enter an expression such as f [x, y, ... ]
Mathematica allows you to do it in ways that mimic infix, prefix and postfix forms.
This postfix form is exactly
equivalent to f[x + y].
In[1]:= x + y //f
Out[1]= f x y
Out[2]= 2.31607
Out[3]= a, b, c, d, e
234
You should notice that // has very low precedence. If you put //f at the end of any expression
containing arithmetic or logical operators, the f is applied to the whole expression. So, for example,
x+y //f means f[x+y], not x+f[y].
The prefix form @ has a much higher precedence. f @ x + y is equivalent to f[x] + y, not f[x + y].
You can write f[x + y] in prefix form as f @ (x + y).
Out[2]= y
In[3]:= (x + y + z)[[-1]]
In[2]:= (x + y + z)[[2]]
Out[3]= z
In[4]:= (x + y + z)[[0]]
Out[4]= Plus
You can refer to parts of an expression such as f [g[a], g[b]] just as you refer to parts of nested
lists.
This is part 1.
Out[7]= x
You should realize that the assignment of indices to parts of expressions is done on the basis of
the internal Mathematica forms of the expression, as shown by FullForm . These forms do not always
correspond directly with what you see printed out. This is particularly true for algebraic expressions,
where Mathematica uses a standard internal form, but prints the expressions in special ways.
Here is the internal form of x / y.
In[9]:= FullForm[x / y]
Out[9]//FullForm= Times
x, Power
y, 1
235
In[10]:= (x / y)[[2]]
1
Out[10]=
y
You can manipulate parts of expressions just as you manipulate parts of lists.
This replaces the third part of
a + b + c + d by x^2. Note that the
sum is automatically rearranged when
the replacement is done.
Here is an expression.
In[12]:= t = 1 + (3 + x)^2 / y
Out[11]= a b d x2
3 x
Out[12]= 1
y
This is the full form of t.
In[13]:= FullForm[ t ]
Out[13]//FullForm= Plus
1, Times
Power
Plus
3, x, 2, Power
y, 1
In[15]:= t
x2
Out[15]= 1
y
Part[expr, n] or expr[[n]]
Section 1.2.4 discussed how you can use lists of indices to pick out several elements of a list at a
time. You can use the same procedure to pick out several parts in an expression at a time.
This picks out elements 2 and 4 in the
list, and gives a list of these elements.
Out[16]= b, d
Out[17]= b d
Any part in an expression can be viewed as being an argument of some function. When you pick
out several parts by giving a list of indices, the parts are combined using the same function as in the
expression.
236
In[2]:= Take[t, 2]
In[3]:= Length[t]
In[4]:= FreeQ[t, x]
In[5]:= Position[t, x]
Out[1]= 1 x x2 y2
Out[2]= 1 x
Out[3]= 4
Out[4]= False
You should remember that all functions which manipulate the structure of expressions act on the
internal forms of these expressions. You can see these forms using FullForm[expr]. They may not be
what you would expect from the printed versions of the expressions.
Here is a function with four
arguments.
In[6]:= f[a, b, c, d]
In[7]:= Append[%, e]
In[8]:= Reverse[%]
Out[6]= f a, b, c, d
Out[7]= f a, b, c, d, e
Out[8]= f e, d, c, b, a
There are a few extra functions that can be used with expressions, as discussed in Section 2.2.10.
237
You can think of any Mathematica expression as a tree. In the expression above, the top node in the
tree consists of a Plus. From this node come two branches, x^3 and (1 + x)^2. From the x^3 node,
there are then two branches, x and 3, which can be viewed as leaves of the tree.
This matrix is a simple tree with just
two levels.
Out[3]//TreeForm= List
,
List
a, b List
c, d
In[5]:= TreeForm[%]
Out[5]//TreeForm= List
List
,
Times
a, b Timesc,
Power
d, 2
List
Times
,
Power
x, 3 Power
y, 4
The indices that label each part of an expression have a simple interpretation in terms of trees.
Descending from the top node of the tree, each index specifies which branch to take in order to reach
the part you want.
In[2]:= Position[t, x, 1]
Out[1]//TreeForm= Listx,
, y
List
x, y
Out[2]= 1
238
In[3]:= Position[t, x, 2]
Position[expr, form, n]
Position[expr, form, {n}]
You can think of levels in expressions in terms of trees. The level of a particular part in an expression is simply the distance down the tree at which that part appears, with the top of the tree
considered as level 0.
It is equivalent to say that the parts which appear at level n are those that can be specified by a
sequence of exactly n indices.
Infinity
{n}
{n , n }
levels 1 through n
all levels (except 0)
level n only
levels n through n
include heads
exclude heads
Level specifications.
f
g
a
, a,
, f
h
a
, a
Out[7]= 4
Level[expr, lev]
Depth[expr]
239
In[9]:= Level[u, 2]
Out[10]= g a, a, a
When you have got the hang of ordinary levels, you can try thinking about negative levels. Negative
levels label parts of expressions starting at the bottom of the tree. Level -1 contains all the leaves of
the tree: objects like symbols and numbers.
This shows the parts of u at level .
You can think of expressions as having a depth, which is equal to the maximum number of levels
shown by TreeForm . In general, level -n in an expression is defined to consist of all subexpressions
whose depth is n.
The depth of g[a] is 2.
240
In[4]:= pf[Log, q]
Out[1]= g 1 x g x
Out[2]= p2 x, y
The ability to treat the names of functions just like other kinds of expressions is an important
consequence of the symbolic nature of the Mathematica language. It makes possible the whole range
of functional operations discussed in the sections that follow.
Ordinary Mathematica functions such as Log or Integrate typically operate on data such as numbers and algebraic expressions. Mathematica functions that represent functional operations, however,
can operate not only on ordinary data, but also on functions themselves. Thus, for example, the functional operation InverseFunction takes a Mathematica function name as an argument, and represents
the inverse of that function.
InverseFunction is a functional
operation: it takes a Mathematica
function as an argument, and returns
another function which represents its
inverse.
In[5]:= InverseFunction[ArcSin]
In[6]:= %[x]
Out[5]= Sin
Out[6]= Sin x
Out[7]= f1 x
There are many kinds of functional operations in Mathematica. Some represent mathematical operations; others represent various kinds of procedures and algorithms.
Unless you are familiar with advanced symbolic languages, you will probably not recognize most
of the functional operations discussed in the sections that follow. At first, the operations may seem
241
difficult to understand. But it is worth persisting. Functional operations provide one of the most
conceptually and practically efficient ways to use Mathematica.
Nest[f, x, n]
NestList[f, x, n]
In[1]:= Nest[f, x, 4]
In[2]:= NestList[f, x, 4]
In[4]:= Nest[recip, x, 3]
Out[1]= f f f f x
1
Out[4]=
1
1
1
1
1x
Nest and NestList allow you to apply functions a fixed number of times. Often you may
want to apply functions until the result no longer changes. You can do this using FixedPoint and
FixedPointList .
FixedPoint[f, x]
FixedPointList[f, x]
242
Out[7]= 1.73205
NestWhile[f, x, test]
NestWhileList[f, x, test]
Out[12]= 1, 5, 4, 6, 2, 3, 1
Operations such as Nest take a function f of one argument, and apply it repeatedly. At each step,
they use the result of the previous step as the new argument of f.
It is important to generalize this notion to functions of two arguments. You can again apply the
function repeatedly, but now each result you get supplies only one of the new arguments you need.
A convenient approach is to get the other argument at each step from the successive elements of a list.
243
create the list {x, f [x, a], f [f [x, a], b], ... }
give the last element of the list produced by
FoldList[f, x, {a, b, ... }]
Out[15]= 0, a, a b, a b c
Using Fold and FoldList you can write many elegant and efficient programs in Mathematica. In
some cases, you may find it helpful to think of Fold and FoldList as producing a simple nesting of
a family of functions indexed by their second argument.
This defines a function nextdigit .
Out[1]= f a, b, c
Out[2]= a b c
244
In[4]:= Apply[List, a + b + c]
Here is a matrix.
Out[4]= a, b, c
In[6]:= Apply[f, m]
245
What Map[f, expr] effectively does is to wrap the function f around each element of the expression
expr. You can use Map on any expression, not just a list.
This applies f to each element in the
sum.
In[4]:= Map[f, a + b + c]
Out[4]= f a f b f c
Map[f, expr] applies f to the first level of parts in expr. You can use MapAll[f, expr] to apply f to
all the parts of expr.
This defines a matrix m.
In[7]:= Map[f, m]
In[8]:= MapAll[f, m]
In general, you can use level specifications as described on page 238 to tell Map to which parts of
an expression to apply your function.
This applies f only to the parts of m at
level 2.
Level specifications allow you to tell Map to which levels of parts in an expression you want a
function applied. With MapAt, however, you can instead give an explicit list of parts where you want
a function applied. You specify each part by giving its indices, as discussed in Section 2.1.4.
Here is a
matrix.
246
In[13]:= Position[mm, b]
Here is an expression.
In[16]:= t = 1 + (3 + x)^2 / x
2
3 x
Out[16]= 1
x
This is the full form of t.
In[17]:= FullForm[ t ]
Out[17]//FullForm= Plus
1, Times
Power
x, 1, Power
Plus
3, x, 2
MapIndexed[f, expr]
MapIndexed[f, expr, lev]
f3 x
Out[18]= 1
f
x
247
Map allows you to apply a function of one argument to parts of an expression. Sometimes, however,
you may instead want to apply a function of several arguments to corresponding parts of several
different expressions. You can do this using MapThread .
Functions like Map allow you to create expressions with parts modified. Sometimes you simply
want to go through an expression, and apply a particular function to some parts of it, without building
a new expression. A typical case is when the function you apply has certain side effects, such as
making assignments, or generating output.
Scan[f, expr]
Scan[f, expr, lev]
1
x
2
2
x
248
Pure functions.
When you use functional operations such as Nest and Map, you always have to specify a function to
apply. In all the examples above, we have used the name of a function to specify the function. Pure
functions allow you to give functions which can be applied to arguments, without having to define
explicit names for the functions.
This defines a function h.
There are several equivalent ways to write pure functions in Mathematica. The idea in all cases is to
construct an object which, when supplied with appropriate arguments, computes a particular function.
Thus, for example, if fun is a pure function, then fun[a] evaluates the function with argument a.
Here is a pure function which
represents the operation of squaring.
In[5]:= %[n]
Out[4]= Function x, x2
Out[5]= n2
You can use a pure function wherever you would usually give the name of a function.
You can use a pure function in Map.
Or in Nest.
1
Out[7]=
1
1
1
1
1x
249
If you are going to use a particular function repeatedly, then you can define the function using
f [x_] := body, and refer to the function by its name f. On the other hand, if you only intend to use
a function once, you will probably find it better to give the function in pure function form, without
ever naming it.
If you are familiar with formal logic or the LISP programming language, you will recognize Mathematica pure functions as being like expressions or anonymous functions. Pure functions are also
close to the pure mathematical notion of operators.
#n
##
##n
Just as the name of a function is irrelevant if you do not intend to refer to the function again, so
also the names of arguments in a pure function are irrelevant. Mathematica allows you to avoid using
explicit names for the arguments of pure functions, and instead to specify the arguments by giving
slot numbers #n. In a Mathematica pure function, #n stands for the nth argument you supply. #
stands for the first argument.
#^2 & is a short form for a pure
function that squares its argument.
When you use short forms for pure functions, it is very important that you do not forget the
ampersand. If you leave the ampersand out, Mathematica will not know that the expression you give
is to be used as a pure function.
When you use the ampersand notation for pure functions, you must be careful about the grouping
of pieces in your input. As shown on page 1029 the ampersand notation has fairly low precedence,
which means that you can type expressions like #1 + #2 & without parentheses. On the other hand,
if you want, for example, to set an option to be a pure function, you need to use parentheses, as in
option -> (fun &).
250
Pure functions in Mathematica can take any number of arguments. You can use ## to stand for all
the arguments that are given, and ##n to stand for the nth and subsequent arguments.
## stands for all arguments.
NestList[f, x, n]
generate a list of the form {x, f [x, a], f [f [x, a], b], ... }
ComposeList[{f , f , ... }, x]
In[1]:= Array[p, 5]
NestList and FoldList were discussed in Section 2.2.2. Particularly by using them with pure
functions, you can construct some very elegant and efficient Mathematica programs.
This gives a list of results obtained by
successively differentiating xn with
respect to x.
251
Select[list, f] selects elements of list using the function f as a criterion. Select applies f to each
element of list in turn, and keeps only those for which the result is True.
This selects the elements of the list for
which the pure function yields True,
i.e., those numerically greater than 4.
You can use Select to pick out pieces of any expression, not just elements of a list.
This gives a sum of terms involving x,
y and z.
Select[expr, f]
Select[expr, f, n]
Out[2]= x2 2 x y y2 2 x z 2 y z z2
Out[3]= y2 2 y z z2
Section 2.3.5 discusses some predicates that are often used as criteria in Select.
This gives the first element which
satisfies the criterion you specify.
In[1]:= f[3][x, y]
In[2]:= (a + b)[x]
Out[1]= f 3 x, y
Out[2]= a b x
252
One case where we have already encountered the use of complicated expressions as heads is in
working with pure functions in Section 2.2.5. By giving Function[vars, body] as the head of an
expression, you specify a function of the arguments to be evaluated.
With the head Function[x, x^2], the
value of the expression is the square of
the argument.
Out[3]= a b
There are several constructs in Mathematica which work much like pure functions, but which represent specific kinds of functions, typically numerical ones. In all cases, the basic mechanism involves
giving a head which contains complete information about the function you want to use.
Function[vars, body][args]
InterpolatingFunction[data][args]
pure function
approximate numerical function (generated by
Interpolation and NDSolve)
CompiledFunction[data][args]
LinearSolveFunction[data][vec]
In[5]:= y /. First[%]
Another important use of more complicated expressions as heads is in implementing functionals and
functional operators in mathematics.
As one example, consider the operation of differentiation. As will be discussed in Section 3.5.4, an
expression like f' represents a derivative function, obtained from f by applying a functional operator to
it. In Mathematica, f' is represented as Derivative[1][f] : the functional operator Derivative[1]
is applied to f to give another function, represented as f'.
This expression has a head which
represents the application of the
functional operator Derivative[1]
to the function f.
253
Composition[f, g, ... ]
InverseFunction[f]
Identity
In[1]:= Composition[f, g, h]
In[3]:= %[x]
Out[1]= Composition f, g, h
You can get the sum of two expressions in Mathematica just by typing x + y. Sometimes it is also
worthwhile to consider performing operations like addition on operators.
You can think of this as containing a
sum of two operators f and g.
In[4]:= (f + g)[x]
In[7]:= % [x^2]
Out[4]= f g x
Out[5]= f x g x
Out[8]= 2 x x2
254
Identity[expr]
Through[p[f , f ][x], q]
Operate[p, f [x]]
Operate[p, f [x], n]
MapAll[p, expr, Heads->True]
In[10]:= Expand[%]
In[12]:= t /. a->1
In[13]:= Operate[p, t]
Out[11]= 1 a b a b x
Out[12]= 2 1 b x
Out[13]= p 1 a 1 b x
Sort[expr]
Sort[expr, pred]
,
Ordering[expr]
Ordering[expr, n]
Ordering[expr, n, pred]
255
OrderedQ[expr]
Order[expr , expr ]
Flatten[expr]
Flatten[expr, n]
Flatten[expr, n, h]
FlattenAt[expr, i]
Out[2]= 8, 5, 2, 1
Out[3]= y, 2 y, x y, x2
flatten out all nested functions with the same head as expr
flatten at most n levels of nesting
flatten functions with head h
flatten only the ith element of expr
Out[4]= f a, b, c, d
Out[5]= a, b, c, a, b, d
You can use Flatten to implement the mathematical property of associativity. The function
Distribute allows you to implement properties such as distributivity and linearity.
256
Distribute[f [args], g]
Distribute[expr, g, f]
In general, if f is distributive over Plus, then an expression like f [a + b] can be expanded to give
f [a] + f [b]. The function Expand does this kind of expansion for standard algebraic operators such
as Times. Distribute allows you to perform the same kind of expansion for arbitrary operators.
Expand uses the distributivity of Times
over Plus to perform algebraic
expansions.
In[8]:= Expand[ (a + b) (c + d) ]
Out[8]= a c b c a d b d
Related to Distribute is the function Thread. What Thread effectively does is to apply a function
in parallel to all the elements of a list or other expression.
257
In[13]:= Thread[%]
As mentioned in Section 1.8.1, and discussed in more detail in Section 2.6.3, many built-in Mathematica functions have the property of being listable, so that they are automatically threaded over
any lists that appear as arguments.
Built-in mathematical functions such as
Log are listable, so that they are
automatically threaded over lists.
In[16]:= Log[x == y]
Out[16]= Log x y
Outer[f, list , list ] takes all possible combinations of elements from list and list , and combines
them with f. Outer can be viewed as a generalization of a Cartesian product for tensors, as discussed
in Section 3.7.11.
Outer forms all possible combinations
of elements, and applies f to them.
Outer, like Distribute , constructs all possible combinations of elements. On the other hand,
Inner, like Thread, constructs only combinations of elements that have corresponding positions in the
expressions it acts on.
258
2.2.11 Sequences
The function Flatten allows you to
explicitly flatten out all sublists.
Sequence[e , e , ... ]
Out[1]= a, b, c, d, e
Out[3]= a, b, c, d, e
In[5]:= a == Sequence[b, c]
Out[5]= a b c
In[6]:= {a, b, f[x, y], g[w], f[z, y]} /. f->Sequence
Out[6]= a, b, x, y, g
w, z, y
2.3.1 Introduction
259
2.3 Patterns
2.3.1 Introduction
Patterns are used throughout Mathematica to represent classes of expressions. A simple example of
a pattern is the expression f[x_]. This pattern represents the class of expressions with the form
f[anything].
The main power of patterns comes from the fact that many operations in Mathematica can be done
not only with single expressions, but also with patterns that represent whole classes of expressions.
You can use patterns in transformation
rules to specify how classes of
expressions should be transformed.
Out[1]= a2 b2
The basic object that appears in almost all Mathematica patterns is _ (traditionally called blank by
Mathematica programmers). The fundamental rule is simply that _ stands for any expression. On most
keyboards the _ underscore character appears as the shifted version of the - dash character.
Thus, for example, the pattern f[_] stands for any expression of the form f[anything]. The pattern
f[x_] also stands for any expression of the form f[anything], but gives the name x to the expression
anything, allowing you to refer to it on the right-hand side of a transformation rule.
You can put blanks anywhere in an expression. What you get is a pattern which matches all
expressions that can be made by filling in the blanks in any way.
f[n_]
f[n_, m_]
x^n_
x_^n_
a_ + b_
{a1_, a2_}
f[n_, n_]
Some examples of patterns.
260
One of the most common uses of patterns is for destructuring function arguments. If you make
a definition for f[list_] , then you need to use functions like Part explicitly in order to pick out
elements of the list. But if you know for example that the list will always have two elements, then it
is usually much more convenient instead to give a definition instead for f[{x_, y_}]. Then you can
refer to the elements of the list directly as x and y. In addition, Mathematica will not use the definition
you have given unless the argument of f really is of the required form of a list of two expressions.
Here is one way to define a function
which takes a list of two elements, and
evaluates the first element raised to the
power of the second element.
A crucial point to understand is that Mathematica patterns represent classes of expressions with a
given structure. One pattern will match a particular expression if the structure of the pattern is the
same as the structure of the expression, in the sense that by filling in blanks in the pattern you can get
the expression. Even though two expressions may be mathematically equal, they cannot be represented
by the same Mathematica pattern unless they have the same structure.
Thus, for example, the pattern (1 + x_)^2 can stand for expressions like (1 + a)^2 or (1 + b^3)^2
that have the same structure. However, it cannot stand for the expression 1 + 2 a + a^2. Although
this expression is mathematically equal to (1 + a)^2, it does not have the same structure as the pattern
(1 + x_)^2.
The fact that patterns in Mathematica specify the structure of expressions is crucial in making it
possible to set up transformation rules which change the structure of expressions, while leaving them
mathematically equal.
It is worth realizing that in general it would be quite impossible for Mathematica to match patterns
by mathematical, rather than structural, equivalence. In the case of expressions like (1 + a)^2 and
1 + 2 a + a^2, you can determine equivalence just by using functions like Expand and Factor. But, as
discussed on page 327 there is no general way to find out whether an arbitrary pair of mathematical
expressions are equal.
As another example, the pattern x^_ will match the expression x^2. It will not, however, match the
expression 1, even though this could be considered as x^0. Section 2.3.9 will discuss how to construct
a pattern for which this particular case will match. But you should understand that in all cases pattern
matching in Mathematica is fundamentally structural.
The x^n_ matches only x^2 and x^3. 1
and x can mathematically be written as
xn , but do not have the same structure.
261
Another point to realize is that the structure Mathematica uses in pattern matching is the full form
of expressions printed by FullForm . Thus, for example, an object such as 1/x, whose full form is
Power[x, -1] will be matched by the pattern x_^n_, but not by the pattern x_/y_, whose full form is
Times[x_, Power[y_, -1]]. Again, Section 2.3.9 will discuss how you can construct patterns which
can match all these cases.
The expressions in the list contain
explicit powers of b, so the
transformation rule can be applied.
Although Mathematica does not use mathematical equivalences such as x x when matching
patterns, it does use certain structural equivalences. Thus, for example, Mathematica takes account of
properties such as commutativity and associativity in pattern matching.
To apply this transformation rule,
Mathematica makes use of the
commutativity and associativity of
addition.
The discussion so far has considered only pattern objects such as x_ which can stand for any single
expression. In later subsections, we discuss the constructs that Mathematica uses to extend and restrict
the classes of expressions represented by patterns.
Count[list, form]
Out[1]= x2 , x3
Out[2]= 2
You can apply functions like Cases not only to lists, but to expressions of any kind. In addition, you
can specify the level of parts at which you want to look.
262
Cases[expr, lhs->rhs]
Cases[expr, lhs->rhs, lev]
Count[expr, form, lev]
Position[expr, form, lev]
find elements of expr that match lhs, and give a list of the
results of applying the transformation rule to them
test parts of expr at levels specified by lev
give the total number of parts that match form at levels
specified by lev
give the positions of parts that match form at levels specified
by lev
DeleteCases[expr, form]
DeleteCases[expr, form, lev]
Out[7]= 3, 4, x
Out[8]= x, x, x
263
Out[10]= b, b, c
Mathematica allows you to give names not just to single blanks, but to any piece of a pattern. The
object x:pattern in general represents a pattern which is assigned the name x. In transformation rules,
you can use this mechanism to name exactly those pieces of a pattern that you need to refer to on the
right-hand side of the rule.
_
x_
x:pattern
Patterns with names.
any expression
any expression, to be named x
an expression to be named x, matching pattern
264
Out[2]= p ab
Out[3]= p ab , b
When you give the same name to two pieces of a pattern, you constrain the pattern to match only
those expressions in which the corresponding pieces are identical.
Here the pattern matches both cases.
x_h
x_Integer
x_Real
x_Complex
x_List
x_Symbol
You can think of making an assignment for f[x_Integer] as like defining a function f that must
take an argument of type Integer.
This defines a value for the function
gamma when its argument is an integer.
265
In[4]:= gamma[4.]
Out[3]= 6 gamma x
pattern /; condition
You can use /; on whole definitions and transformation rules, as well as on individual patterns. In
general, you can put /; condition at the end of any := definition or :> rule to tell Mathematica that the
definition or rule applies only when the specified condition holds. Note that /; conditions should not
usually be put at the end of = definitions or -> rules, since they will then be evaluated immediately,
as discussed in Section 2.5.8.
Here is another way to give a
definition which applies only when its
argument n is positive.
266
You can use the /; operator to implement arbitrary mathematical constraints on the applicability
of rules. In typical cases, you give patterns which structurally match a wide range of expressions, but
then use mathematical constraints to reduce the range of expressions to a much smaller set.
This rule applies only to expressions
that have the structure v[x_, 1 - x_].
Out[7]= p a2
Out[8]= v 4, 3
Out[10]= p 4
In setting up patterns and transformation rules, there is often a choice of where to put /; conditions. For example, you can put a /; condition on the right-hand side of a rule in the form
lhs :> rhs /; condition, or you can put it on the left-hand side in the form lhs /; condition -> rhs. You
may also be able to insert the condition inside the expression lhs. The only constraint is that all the
names of patterns that you use in a particular condition must appear in the pattern to which the
condition is attached. If this is not the case, then some of the names needed to evaluate the condition
may not yet have been bound in the pattern-matching process. If this happens, then Mathematica
uses the global values for the corresponding variables, rather than the values determined by pattern
matching.
Thus, for example, the condition in f[x_, y_] /; (x + y < 2) will use values for x and y that are
found by matching f[x_, y_], but the condition in f[x_ /; x + y < 2, y_] will use the global value
for y, rather than the one found by matching the pattern.
As long as you make sure that the appropriate names are defined, it is usually most efficient to
put /; conditions on the smallest possible parts of patterns. The reason for this is that Mathematica
matches pieces of patterns sequentially, and the sooner it finds a /; condition which fails, the sooner
it can reject a match.
Putting the /; condition around the x_
is slightly more efficient than putting it
around the whole pattern.
In[11]:= Cases[{z[1, 1], z[-1, 1], z[-2, 2]}, z[x_ /; x < 0, y_]]
Out[11]= z
1, 1, z
2, 2
267
It is common to use /; to set up patterns and transformation rules that apply only to expressions
with certain properties. There is a collection of functions built into Mathematica for testing the properties of expressions. It is a convention that functions of this kind have names that end with the letter
Q, indicating that they ask a question.
IntegerQ[expr]
integer
EvenQ[expr]
even number
OddQ[expr]
odd number
PrimeQ[expr]
NumberQ[expr]
NumericQ[expr]
PolynomialQ[expr, {x , x , ... }]
prime number
explicit number of any kind
numeric quantity
polynomial in x , x ,
VectorQ[expr]
MatrixQ[expr]
ArrayQ[expr, d]
49
Out[13]= 5.29, 16, , a, b
64
268
An important feature of all the Mathematica property-testing functions whose names end in Q is that
they always return False if they cannot determine whether the expression you give has a particular
property.
4561 is an integer, so this returns True.
In[16]:= IntegerQ[4561]
Out[16]= True
In[17]:= IntegerQ[x]
Out[17]= False
In some cases, you can explicitly specify the results that property-testing functions should give.
Thus, with a definition such as x /: IntegerQ[x] = True, as discussed in Section 2.5.10, Mathematica
will assume that x is an integer. This means that if you explicitly ask for IntegerQ[x] , you will now
get True, rather than False. However, Mathematica does not automatically propagate assertions, so it
cannot determine for example that IntegerQ[x^2] is True. You must load an appropriate Mathematica
package to make this possible.
SameQ[x, y] or x === y
UnsameQ[x, y] or x =!= y
OrderedQ[{a, b, ... }]
MemberQ[expr, form]
FreeQ[expr, form]
MatchQ[expr, form]
ValueQ[expr]
AtomQ[expr]
In[18]:= {x == y, x === y}
Out[18]= x y, False
Out[19]= False
Out[20]= False
pattern ? test
269
The construction pattern /; condition allows you to evaluate a condition involving pattern names to
determine whether there is a match. The construction pattern ? test instead applies a function test to
the whole expression matched by pattern to determine whether there is a match. Using ? instead of
/; sometimes leads to more succinct definitions.
With this definition matches for x_ are
tested with the function NumberQ .
Out[24]= 22.5 p u
In[1]:= h[a | b] := p
Out[3]= p, p, c, d
Out[4]= 1, q, q, q, y2
270
When you use alternatives in patterns, you should make sure that the same set of names appear in
each alternative. When a pattern like (a[x_] | b[x_]) matches an expression, there will always be a
definite expression that corresponds to the object x. On the other hand, if you try to match a pattern
like (a[x_] | b[y_]), then there will be a definite expression corresponding either to x, or to y, but
not to both. As a result, you cannot use x and y to refer to definite expressions, for example on the
right-hand side of a transformation rule.
Here f is used to name the head,
which can be either a or b.
Out[1]= p a, b
Out[2]= p b, a
As discussed in Section 2.6.3, Mathematica allows you to assign certain attributes to functions,
which specify how those functions should be treated in evaluation and pattern matching. Functions
can for example be assigned the attribute Orderless , which specifies that they should be treated as
commutative or symmetric, and allows their arguments to be rearranged in trying to match patterns.
Orderless
Flat
271
OneIdentity
Attributes[f]
SetAttributes[f, attr]
ClearAttributes[f, attr]
In[5]:= Attributes[Plus]
In[7]:= q[b, a, c]
Out[7]= q a, b, c
Out[8]= p b, a, c
In addition to being orderless, functions like Plus and Times also have the property of being flat
or associative. This means that you can effectively parenthesize their arguments in any way, so that,
for example, x + (y + z) is equivalent to x + y + z, and so on.
Mathematica takes account of flatness in matching patterns. As a result, a pattern like g[x_ + y_]
can match g[a + b + c], with x # a and y # (b + c).
The argument of g is written as
a + (b + c) so as to match the pattern.
Out[9]= p a, b c
Out[10]= p a, b c d
272
Mathematica can usually apply a transformation rule to a function only if the pattern in the rule
covers all the arguments in the function. However, if you have a flat function, it is sometimes possible
to apply transformation rules even though not all the arguments are covered.
This rule applies even though it does
not cover all the terms in the sum.
In[13]:= a + b + c /. a + c -> p
Out[13]= b p
Out[14]= u a b v c v d
Functions like Plus and Times are both flat and orderless. There are, however, some functions,
such as Dot, which are flat, but not orderless.
Both x_ and y_ can match any
sequence of terms in the dot product.
Out[17]= rp r a, b
Out[18]= r a, rp r b, c
In an ordinary function that is not flat, a pattern such as x_ matches an individual argument of
the function. But in a function f [a, b, c, ... ] that is flat, x_ can match objects such as f [b, c] which
effectively correspond to a sequence of arguments. However, in the case where x_ matches a single
argument in a flat function, the question comes up as to whether the object it matches is really just
the argument a itself, or f [a]. Mathematica chooses the first of these cases if the function carries the
attribute OneIdentity , and chooses the second case otherwise.
This adds the attribute OneIdentity to
the function r.
The functions Plus, Times and Dot all have the attribute OneIdentity , reflecting the fact that
Plus[x] is equivalent to x, and so on. However, in representing mathematical objects, it is often
convenient to deal with flat functions that do not have the attribute OneIdentity .
273
In[3]:= h[2, 3, 2, 4, 5, 3]
Out[1]= p a, b, c, a, b, c, a, b, c
Out[3]= h 4, 5 hh 2 hh 3
Double blanks __ stand for sequences of one or more expressions. Triple blanks ___ stand
for sequences of zero or more expressions. You should be very careful whenever you use triple
blank patterns. It is easy to make a mistake that can lead to an infinite loop. For example, if you
define p[x_, y___] := p[x] q[y], then typing in p[a] will lead to an infinite loop, with y repeatedly
matching a sequence with zero elements. Unless you are sure you want to include the case of zero
elements, you should always use double blanks rather than triple blanks.
x_
__
x__
x__h
___
x___
x___h
sequence named x
sequence of expressions, all of whose heads are h
any sequence of zero or more expressions
sequence of zero or more expressions named x
sequence of zero or more expressions, all of whose heads
are h
Notice that with flat functions such as Plus and Times, Mathematica automatically handles variable
numbers of arguments, so you do not explicitly need to use double or triple blanks, as discussed in
Section 2.3.7.
274
When you use multiple blanks, there are often several matches that are possible for a particular
expression. In general, Mathematica tries first those matches that assign the shortest sequences of
arguments to the first multiple blanks that appear in the pattern.
This gives a list of all the matches that
Mathematica tries.
In[2]:= j[a, b]
Out[2]= jp
a, b, 2
x_:v
x_h:v
x_.
In[3]:= j[a]
Out[3]= jp
a, 1, 2
Some common Mathematica functions have built-in default values for their arguments. In such cases,
you need not explicitly give the default value in x_:v, but instead you can use the more convenient
notation x_. in which a built-in default value is assumed.
x_ + y_.
default for y is 0
x_ y_.
default for y is 1
x_^y_.
default for y is 1
275
Because Plus is a flat function, a pattern such as x_ + y_ can match a sum with any number of
terms. This pattern cannot, however, match a single term such as a. However, the pattern x_ + y_.
contains an optional piece, and can match either an explicit sum of terms in which both x_ and y_
appear, or a single term x_, with y taken to be 0.
Using constructs such as x_., you can easily construct single patterns that match expressions with
several different structures. This is particularly useful when you want to match several mathematically
equal forms that do not have the same structure.
The pattern matches g[a^2], but not
g[a + b].
In this case, b # 1.
In[8]:= lin[1 + x, x]
Out[8]= p 1, 1
Here b # 1 and a # 0.
In[9]:= lin[y, y]
Out[9]= p
0, 1
Standard Mathematica functions such as Plus and Times have built-in default values for their
arguments. You can also set up defaults for your own functions, as described in Section A.5.1.
276
The first method is to have the meaning of each argument determined by its position, and then
to allow one to drop arguments, replacing them by default values. Almost all built-in Mathematica
functions that use this method drop arguments from the end. For example, the built-in function
Flatten[list, n] allows you to drop the second argument, which is taken to have a default value of
Infinity.
You can implement this kind of positional argument using _: patterns.
In[3]:= fx[k, m]
Out[3]= fx0
k, m, 2
The second method that built-in Mathematica functions use for dealing with optional arguments is
to give explicit names to the optional arguments, and then to allow their values to be given using
transformation rules. This method is particularly convenient for functions like Plot which have a very
large number of optional parameters, only a few of which usually need to be set in any particular
instance.
The typical arrangement is that values for named optional arguments can be specified by including the appropriate transformation rules at the end of the arguments to a particular function. Thus,
for example, the rule PlotJoined->True , which specifies the setting for the named optional argument
PlotJoined , could appear as ListPlot[list, PlotJoined->True] .
When you set up named optional arguments for a function f, it is conventional to store the default
values of these arguments as a list of transformation rules assigned to Options[f] .
277
Named arguments.
Out[5]= 1
In[8]:= fn[4]
Out[6]= 3
Out[8]= k 4, 2
Out[9]= k 4, 7
expr...
Repeated patterns.
Multiple blanks such as x__ allow you to give patterns in which sequences of arbitrary expressions
can occur. The Mathematica pattern repetition operators .. and ... allow you to construct patterns in
which particular forms can be repeated any number of times. Thus, for example, f[a..] represents
any expression of the form f[a], f[a, a], f[a, a, a] and so on.
The pattern f[a..] allows the
argument a to be repeated any number
of times.
278
You can use .. and ... to represent repetitions of any pattern. If the pattern contains named parts,
then each instance of these parts must be identical.
This defines a function whose
argument must consist of a list of
pairs.
Verbatim patterns.
279
Especially for some common kinds of expressions, the standard output format used by Mathematica
is not particularly close to the full internal form. But it is the internal form that you must use in
setting up patterns.
n_Integer
x_Real
z_Complex
Complex[x_, y_]
Complex[x_Integer, y_Integer]
(r_Rational | r_Integer)
Rational[n_, d_]
(x_ /; NumberQ[x] && Im[x]==0)
(x_ /; NumberQ[x])
an integer n
an approximate real number x
a complex number z
a complex number x iy
a complex number where both real and imaginary
parts are integers
rational number or integer r
a rational number
n
d
Out[4]= 2, 3 , 2 2
As discussed in Section 1.4.1, Mathematica puts all algebraic expressions into a standard form, in
which they are written essentially as a sum of products of powers. In addition, ratios are converted
into products of powers, with denominator terms having negative exponents, and differences are
converted into sums with negated terms. To construct patterns for algebraic expressions, you must
use this standard form. This form often differs from the way Mathematica prints out the algebraic
expressions. But in all cases, you can find the full internal form using FullForm[expr] .
280
1
z
2 x2 y z2
Out[5]=
z2
y
This is the full internal form of the
expression.
x_ + y_
x_ + y_.
n_Integer x_
a_. + b_. x_
x_ ^ n_
x_ ^ n_.
a_. + b_. x_ + c_. x_^2
In[6]:= FullForm[%]
Out[6]//FullForm= Plus
Times
1, Power
z, 2,
Times
1, Power
y, 1, z,
Times
2, Power
x, 2, y, Power
z, 2
In[7]:= % /. x_^n_ -> e[x, n]
Out[7]= z e
y, 1 e
z, 2 2 y e
x, 2 e
z, 2
xn with n ^
xn with n ^
a quadratic expression with non-zero linear term
x_List or x:{___}
x_List /; VectorQ[x]
a list
a vector containing no sublists
a vector of numbers
x:{___List} or x:{{___}...}
a list of lists
x_List /; MatrixQ[x]
x_List /; MatrixQ[x, NumberQ]
x:{{_, _}...}
Some typical patterns for lists.
281
mathematical form
y z dx y dx z dx
c y dx c y dx (c independent of x)
c dx c x
n
x dx
axb
xn
n
, n ^
dx
logaxb
a
axb
dx
e
axb
a e
Mathematica definition
282
In[11]:= integrate[1/x, x]
Out[2]= integrate
3, x
integrate
a x, x integrate
b x2 , x
Out[4]= integrate
3, x
a integrate
x, x b integrate
x2 , x
a x2
b x3
Out[8]= 3 x
2
3
a x2
b x3
Out[9]= 3 x
2
3
Out[11]= Log x
Log
1 2 p x
Out[12]=
2p
283
Lists are widely used in Mathematica, and there are many ways to construct them.
Range[n]
Table[expr, {i, n}]
Array[f, n]
NestList[f, x, n]
,
Out[4]= 0, 0, x, y, 0
Often you will know in advance how long a list is supposed to be, and how each of its elements
should be generated. And often you may get one list from another.
284
Map[f, list]
MapIndexed[f, list]
Cases[list, form]
Select[list, test]
Sometimes you may want to accumulate a list of results during the execution of a program. You
can do this using Sow and Reap.
Sow[val]
Reap[expr]
In[8]:= Nest[#^2&, 2, 5]
Out[8]= 4294967296
An alternative but less efficient approach involves introducing a temporary variable, then starting
with t = {}, and successively using AppendTo[t, elem].
-n
{i , i , ... }
All
Out[4]= a, f
Out[6]= b, e, g
You can always reset one or more pieces of a list by doing an assignment like m[[... ]] = value.
This resets part 1,2 of m.
In[8]:= m
Out[8]= a, x, c, d, e, f, g, h
285
286
It is sometimes useful to think of a nested list as being laid out in space, with each element being
at a coordinate position given by its indices. There is then a direct geometrical interpretation for
list[[spec , spec , ... ]]. If a given speck is a single integer, then it represents extracting a single slice
in the kth dimension, while if it is a list, it represents extracting a list of parallel slices. The final result
for list[[spec , spec , ... ]] is then the collection of elements obtained by slicing in each successive
dimension.
Here is a nested list laid out as a
two-dimensional array.
a
Out[14]//TableForm= d
g
Out[15]//TableForm=
a
g
b
e
h
c
f
i
b
h
Part is set up to make it easy to pick out structured slices of nested lists. Sometimes, however,
you may want to pick out arbitrary collections of individual parts. You can do this conveniently with
Extract.
An important feature of Extract is that it takes lists of part positions in the same form as they are
returned by functions like Position .
287
In[19]:= Extract[m, %]
Out[19]= b
1, b
2, b
3
Take[list, spec]
Drop[list, spec]
-n
{n}
{m, n}
{m, n, s}
element n only
elements m through n (inclusive)
elements m through n in steps of s
All
all parts
None
no parts
Out[20]= b, d, f
Out[21]= a, c, e, g
Much like Part, Take and Drop can be viewed as picking out sequences of slices at successive
levels in a nested list. You can use Take and Drop to work with blocks of elements in arrays.
Here is a
array.
a
Out[22]//TableForm= d
g
Here is the first subarray.
b
e
h
c
f
i
a
d
b
e
288
Prepend[list, elem]
Append[list, elem]
Insert[list, elem, i]
Insert[list, elem, {i, j, ... }]
Delete[list, i]
Delete[list, {i, j, ... }]
a
Out[24]//TableForm= d
g
b
e
h
c
Out[25]//TableForm= f
i
ReplacePart[list, new, i]
289
In[30]:= IdentityMatrix[3]
Out[29]= x, b, c, x
list of lists
Functions like Array, SparseArray and Outer always generate full arrays, in which all sublists at a
particular level are the same length.
290
Dimensions[list]
,
ArrayQ[list]
ArrayDepth[list]
Mathematica can handle arbitrary nested lists. There is no need for the lists to form a full array.
You can easily generate ragged arrays using Table.
This generates a triangular array.
Flatten[list]
Flatten[list, n]
Transpose[list]
Transpose[list, {n , n , ... }]
In[7]:= Flatten[%]
Out[7]= a
1, 1, a
1, 2, a
1, 3, a
2, 1, a
2, 2, a
2, 3
291
In[11]:= m = {{{a, b}, {c, d}}, {{e, f}, {g, h}, {i}}};
292
Partition in effect goes through a list, grouping successive elements into sublists. By default it does
not include any sublists that would overhang the original list.
This stops before any overhang occurs.
You can tell Partition to include sublists that overhang the ends of the original list. By default, it
fills in additional elements by treating the original list as cyclic. It can also treat it as being padded
with elements that you specify.
This includes additional sublists,
treating the original list as cyclic.
Out[8]= a, b, c, b, c, d, c, d, e, d, e, a, e, a, b
Out[9]= a, b, c, b, c, d, c, d, e, d, e, x, e, x, x
293
Out[10]= a, b, c, b, c, d, c, d, e, d, e, y, e, y, x
Out[11]= a, b, c, b, c, d, c, d, e, d, e, e
You can think of Partition as extracting sublists by sliding a template along and picking out
elements from the original list. You can tell Partition where to start and stop this process.
This gives all sublists that overlap the
original list.
Partition[list, n, d, {kL , kR }]
Partition[list, n, d, spec]
Partition[list, n, d, spec, x]
use no padding
An alignment specification {kL , kR } tells Partition to give the sequence of sublists in which the
first element of the original list appears at position kL in the first sublist, and the last element of the
original list appears at position kR in the last sublist.
This makes a appear at position 1 in
the first sublist.
294
Out[15]= x, a, b, a, b, c, b, c, d, c, d, x, d, x, x
Functions like ListConvolve use the same alignment and padding specifications as Partition .
In some cases it may be convenient to insert explicit padding into a list. You can do this using
PadLeft and PadRight .
PadLeft[list, n]
PadLeft[list, n, x]
PadLeft[list, n, {x , x , ... }]
PadLeft[list, n, list]
PadLeft[list, n, padding, m]
PadRight[list, n]
Padding a list.
Out[19]= x, y, x, a, b, c
Out[20]= y, x, y, x, a, b, c, x, y, x
295
If you give a nested list as a padding specification, its elements are picked up cyclically at each
level.
This cyclically fills in copies of the
padding list.
In[23]:= PadLeft[{{a, b}, {e}, {f}}, {4, 4}, {{x, y}, {z, w}}]
Lists are normally specified in Mathematica just by giving explicit lists of their elements. But particularly in working with large arrays, it is often useful instead to be able to say what the values of
elements are only at certain positions, with all other elements taken to have a default value, usually
zero. You can do this in Mathematica using SparseArray objects.
ordinary lists
sparse arrays
In[2]:= Normal[%]
Out[2]= 0, a, 0, 0, b
In[4]:= Normal[%]
296
,
,
SparseArray[list]
Normal[array]
ArrayRules[array]
In[6]:= Normal[%]
Out[6]= a, b, c, d
In[8]:= Normal[%]
Out[8]= x, x, a, x, b, x, x
In[9]:= ArrayRules[%%]
Out[9]= 3 a, 5 b, _ x
An important feature of SparseArray is that the positions you specify can be patterns.
This specifies a
sparse array with
1 at every position matching {i_, i_}.
The result is a
identity matrix.
In[11]:= Normal[%]
297
You can think of SparseArray[rules] as taking all possible position specifications, then applying
rules to determine values in each case. As usual, rules given earlier in the list will be tried first.
This generates a random diagonal
matrix.
Out[18]= 0, 0, 0, p, p, p, 0, 0, 0, 0
For many purposes, Mathematica treats SparseArray objects just like the ordinary lists to which
they correspond. Thus, for example, if you ask for parts of a sparse array object, Mathematica will
operate as if you had asked for parts in the corresponding ordinary list.
This generates a sparse array object.
In[21]:= Normal[s]
Out[21]= 0, a, 0, b, c, 0, 0, 0, 0, 0
In[22]:= s[[2]]
In[23]:= s[[3]]
Out[22]= a
Out[23]= 0
Many operations treat SparseArray objects just like ordinary lists. When possible, they give sparse
arrays as results.
This gives a sparse array.
In[24]:= 3 s + x
Out[24]= SparseArray
?3>, 10, x
In[25]:= Normal[%]
Out[25]= x, 3 a x, x, 3 b x, 3 c x, x, x, x, x, x
298
In[26]:= s . s
In[27]:= s . Range[10]
Out[26]= a2 b2 c2
Out[27]= 2 a 4 b 5 c
Mathematica represents sparse arrays as expressions with head SparseArray . Whenever a sparse
array is evaluated, it is automatically converted to an optimized standard form with structure
SparseArray[Automatic, dims, val, ... ].
This structure is, however, rarely evident, since even operations like Length are set up to give
results for the corresponding ordinary list, not for the raw SparseArray expression structure.
This generates a sparse array.
In[29]:= InputForm[%]
Out[29]//InputForm= SparseArray[Automatic, {10}, 0,
{1, {{0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2}, {}}, {a, b}}]
In[30]:= Length[t]
Out[30]= 10
299
In[1]:= x + y /. x -> 3
Out[1]= 3 y
Out[2]= a b
In[5]:= x^2 + 6 /. %
Out[3]= 3, 6
When you use expr /. rules, each rule is tried in turn on each part of expr. As soon as a rule applies,
the appropriate transformation is made, and the resulting part is returned.
The rule for x^3 is tried first; if it does
not apply, the rule for x^n_ is used.
Out[7]= x h y
The replacement expr /. rules tries each rule just once on each part of expr.
300
Out[8]= y2 , x3
Out[9]= 1 b
Sometimes you may need to go on applying rules over and over again, until the expression
you are working on no longer changes. You can do this using the repeated replacement operation
expr //. rules (or ReplaceRepeated[expr, rules]).
expr /. rules
expr //. rules
Out[10]= 2 a y6
Out[11]= 25 y6
When you use //. (pronounced slash-slash-dot), Mathematica repeatedly passes through your
expression, trying each of the rules given. It goes on doing this until it gets the same result on two
successive passes.
If you give a set of rules that is circular, then //. can keep on getting different results forever. In
practice, the maximum number of passes that //. makes on a particular expression is determined by
the setting for the option MaxIterations . If you want to keep going for as long as possible, you can
use ReplaceRepeated[expr, rules, MaxIterations -> Infinity] . You can always stop by explicitly
interrupting Mathematica.
By setting the option MaxIterations ,
you can explicitly tell
ReplaceRepeated how many times to
try the rules you give.
Out[14]= 1000 x
301
The replacement operators /. and //. share the feature that they try each rule on every subpart of
your expression. On the other hand, Replace[expr, rules] tries the rules only on the whole of expr,
and not on any of its subparts.
You can use Replace, together with functions like Map and MapAt, to control exactly which
parts of an expression a replacement is applied to. Remember that you can use the function
ReplacePart[expr, new, pos] to replace part of an expression with a specific object.
The operator /. applies rules to all
subparts of an expression.
Out[15]= a2
Out[16]= b
Out[17]= x2
expr /. rules
Replace[expr, rules]
Replace[expr, rules, levspec]
Out[19]= u2
Out[20]= u2 , u3
302
Replace[expr, rules]
ReplaceList[expr, rules]
You can use lists of rules to represent mathematical and other relations. Typically you will find it
convenient to give names to the lists, so that you can easily specify the list you want in a particular
case.
In most situations, it is only one rule from any given list that actually applies to a particular
expression. Nevertheless, the /. operator tests each of the rules in the list in turn. If the list is very
long, this process can take a long time.
Mathematica allows you to preprocess lists of rules so that /. can operate more quickly on them.
You can take any list of rules and apply the function Dispatch to them. The result is a representation
of the original list of rules, but including dispatch tables which allow /. to dispatch to potentially
applicable rules immediately, rather than testing all the rules in turn.
Here is a list of rules for the first five
factorials.
Out[4]= Dispatch
f
1 1, f
2 2, f
3 6,
f
4 24, f
5 120, DispatchTables
Out[5]= 24
303
Dispatch[rules]
expr /. drules
For long lists of rules, you will find that setting up dispatch tables makes replacement operations
much faster. This is particularly true when your rules are for individual symbols or other expressions
that do not involve pattern objects. Once you have built dispatch tables in such cases, you will find
that the /. operator takes a time that is more or less independent of the number of rules you have.
Without dispatch tables, however, /. will take a time directly proportional to the total number of
rules.
In[2]:= x = 3 - a
In[3]:= (1 + x)^7
Out[1]= 4 a
Out[2]= 3 a
Out[3]= 4 a
You should realize that except inside constructs like Module and Block, all assignments you make
in a Mathematica session are permanent. They continue to be used for the duration of the session,
unless you explicitly clear or overwrite them.
304
The fact that assignments are permanent means that they must be made with care. Probably the
single most common mistake in using Mathematica is to make an assignment for a variable like x at
one point in your session, and then later to use x having forgotten about the assignment you made.
There are several ways to avoid this kind of mistake. First, you should avoid using assignments
whenever possible, and instead use more controlled constructs such as the /. replacement operator.
Second, you should explicitly use the deassignment operator =. or the function Clear to remove
values you have assigned when you have finished with them.
Another important way to avoid mistakes is to think particularly carefully before assigning values
to variables with common or simple names. You will often want to use a variable such as x as a
symbolic parameter. But if you make an assignment such as x = 3, then x will be replaced by 3
whenever it occurs, and you can no longer use x as a symbolic parameter.
In general, you should be sure not to assign permanent values to any variables that you might
want to use for more than one purpose. If at one point in your session you wanted the variable c to
stand for the speed of light, you might assign it a value such as 3.*10^8 . But then you cannot use
c later in your session to stand, say, for an undetermined coefficient. One way to avoid this kind of
problem is to make assignments only for variables with more explicit names, such as SpeedOfLight .
x =.
Clear[x, y, ... ]
Removing assignments.
In[5]:= Clear[x]
Out[6]= 1 x 1 x
305
i++
i--
decrement i
++i
pre-increment i
--i
pre-decrement i
i += di
i -= di
subtract di from i
x *= c
multiply x by c
x /= c
divide x by c
In[1]:= t = 7x
In[2]:= t += 18x
Out[1]= 7 x
Out[2]= 25 x
In[3]:= t
Out[3]= 25 x
In[4]:= t = 8; t *= 7; t
x = y = value
Out[4]= 56
5
6
6
6
{x, y} = {y, x}
306
In[9]:= x
Out[8]= 8, 5
Out[9]= 8
In[10]:= y
Out[10]= 5
When you write programs in Mathematica, you will sometimes find it convenient to take a list, and
successively add elements to it. You can do this using the functions PrependTo and AppendTo .
PrependTo[v, elem]
AppendTo[v, elem]
v = {v, elem}
In[12]:= v = {5, 7, 9}
In[14]:= v
Out[12]= 5, 7, 9
In[16]:= Flatten[w]
307
In[1]:= a[1] = 9
Out[1]= 9
In[2]:= a[2] = 7
Out[2]= 7
In[3]:= ?a
Global`a
a[1] = 9
a[2] = 7
In[4]:= a[5] = 0
Out[4]= 0
You can think of the expression a[i] as being like an indexed or subscripted variable.
a[i] = value
a[i]
a[i] =.
?a
Clear[a]
308
When you have an expression of the form a[i], there is no requirement that the index i be a
number. In fact, Mathematica allows the index to be any expression whatsoever. By using indices that
are symbols, you can for example build up simple databases in Mathematica.
This defines the object area with
index square to have value 1.
In[6]:= area[square] = 1
In[8]:= ?area
Out[6]= 1
1
Out[7]=
2
Global`area
area[square] = 1
area[triangle] = 1/2
f[x] = value
f[x_] = value
309
Making definitions for f[2] or f[a] can be thought of as being like giving values to various
elements of an array named f. Making a definition for f[x_] is like giving a value for a set of
array elements with arbitrary indices. In fact, you can actually think of any function as being like
an array with an arbitrarily variable index.
In mathematical terms, you can think of f as a mapping. When you define values for, say, f[1]
and f[2], you specify the image of this mapping for various discrete points in its domain. Defining
a value for f[x_] specifies the image of f on a continuum of points.
This defines a transformation rule for
the specific expression f[x].
In[1]:= f[x] = u
In[5]:= Clear[f]
Out[1]= u
Out[2]= u f y
Out[3]= x2
Out[4]= u y2
Mathematica allows you to define transformation rules for any expression or pattern. You can mix
definitions for specific expressions such as f[1] or f[a] with definitions for patterns such as f[x_].
Many kinds of mathematical functions can be set up by mixing specific and general definitions in
Mathematica. As an example, consider the factorial function. This particular function is in fact built
into Mathematica (it is written n!). But you can use Mathematica definitions to set up the function for
yourself.
The standard mathematical definition for the factorial function can be entered almost directly into
Mathematica, in the form: f[n_] := n f[n-1]; f[1] = 1. This definition specifies that for any n, f[n]
should be replaced by n f[n-1], except that when n is 1, f[1] should simply be replaced by 1.
Here is the value of the factorial
function with argument 1.
In[6]:= f[1] = 1
In[8]:= f[10]
In[9]:= 10!
Out[6]= 1
Out[8]= 3628800
Out[9]= 3628800
310
If Mathematica did not follow the principle of putting special rules before more general ones, then
the special rules would always be shadowed by more general ones. In the factorial example, if the
rule for f[n_] was ahead of the rule for f[1], then even when Mathematica tried to evaluate f[1], it
would use the general f[n_] rule, and it would never find the special f[1] rule.
Here is a general definition for f[n_].
In[2]:= f[1] = 1
In[3]:= ?f
Out[2]= 1
Global`f
f[1] = 1
f[n_] := n*f[n - 1]
In the factorial function example used above, it is clear which rule is more general. Often, however,
there is no definite ordering in generality of the rules you give. In such cases, Mathematica simply
tries the rules in the order you give them.
These rules have no definite ordering
in generality.
In[5]:= ?log
Global`log
log[(x_)*(y_)] := log[x] + log[y]
log[(x_)^(n_)] := n*log[x]
311
In[7]:= ?log
Global`log
log[2*(x_)] := log[x] + log2
log[(x_)*(y_)] := log[x] + log[y]
log[(x_)^(n_)] := n*log[x]
Although in many practical cases, Mathematica can recognize when one rule is more general than
another, you should realize that this is not always possible. For example, if two rules both contain
complicated /; conditions, it may not be possible to work out which is more general, and, in fact,
there may not be a definite ordering. Whenever the appropriate ordering is not clear, Mathematica
stores rules in the order you give them.
In[2]:= ?ex
Global`ex
ex[x_] := Expand[(1 + x)^2]
In[4]:= ?iex
Out[3]= 1 2 x x2
Global`iex
iex[x_] = 1 + 2*x + x^2
In[5]:= ex[y + 2]
Out[5]= 9 6 y y2
312
In[6]:= iex[y + 2]
2
Out[6]= 1 2 2 y 2 y
As you can see from the example above, both = and := can be useful in defining functions, but
they have different meanings, and you must be careful about which one to use in a particular case.
One rule of thumb is the following. If you think of an assignment as giving the final value of an
expression, use the = operator. If instead you think of the assignment as specifying a command for
finding the value, use the := operator. If in doubt, it is usually better to use the := operator than the
= one.
lhs = rhs
lhs := rhs
Although := is probably used more often than = in defining functions, there is one important case
in which you must use = to define a function. If you do a calculation, and get an answer in terms of
a symbolic parameter x, you often want to go on and find results for various specific values of x. One
way to do this is to use the /. operator to apply appropriate rules for x in each case. It is usually
more convenient however, to use = to define a function whose argument is x.
Here is an expression involving x.
In[7]:= D[Log[Sin[x]]^2, x]
Out[7]= 2 Cot
x Log
Sin
x
In[8]:= dlog[x_] = %
In[9]:= dlog[1 + a]
An important point to notice in the example above is that there is nothing special about the name
x that appears in the x_ pattern. It is just a symbol, indistinguishable from an x that appears in any
other expression.
f [x_] = expr
313
You can use = and := not only to define functions, but also to assign values to variables. If you
type x = value, then value is immediately evaluated, and the result is assigned to x. On the other
hand, if you type x := value, then value is not immediately evaluated. Instead, it is maintained in an
unevaluated form, and is evaluated afresh each time x is used.
This evaluates Random[ ] to find a
pseudorandom number, then assigns
this number to r1.
In[10]:= r1 = Random[ ]
In[11]:= r2 := Random[ ]
Out[10]= 0.0560708
The distinction between immediate and delayed assignments is particularly important when you
set up chains of assignments.
This defines a to be 1.
In[14]:= a = 1
Out[14]= 1
In[15]:= ri = a + 2
Here a + 2 is maintained in an
unevaluated form, to be evaluated
every time the value of rd is
requested.
In[16]:= rd := a + 2
In[18]:= a = 2
Out[15]= 3
Out[17]= 3, 3
Out[18]= 2
You can use delayed assignments such as t := rhs to set up variables whose values you can find in
a variety of different environments. Every time you ask for t, the expression rhs is evaluated using
the current values of the objects on which it depends.
The right-hand side of the delayed
assignment is maintained in an
unevaluated form.
314
In[21]:= a = 4; t
Here a is 6.
In[22]:= a = 6; t
In the example above, the symbol a acts as a global variable, whose value affects the value of
t. When you have a large number of parameters, many of which change only occasionally, you may
find this kind of setup convenient. However, you should realize that implicit or hidden dependence
of one variable on others can often become quite confusing. When possible, you should make all
dependencies explicit, by defining functions which take all necessary parameters as arguments.
Just as you can make immediate and delayed assignments in Mathematica, so you can also set up
immediate and delayed transformation rules.
The right-hand side of this rule is
evaluated when you give the rule.
Out[23]= f x_ 1 2 x x2
Out[24]= f x_ x
Out[26]= 1 2 p p2
In analogy with assignments, you should typically use -> when you want to replace an expression
with a definite value, and you should use :> when you want to give a command for finding the
value.
315
In[3]:= ?f
Out[2]= 1
Global`f
f[1] = 1
f[0] = 1
f[x_] := f[x] = f[x - 1] + f[x - 2]
In[4]:= f[5]
In[5]:= ?f
Out[4]= 8
Global`f
f[1] = 1
f[0] = 1
f[2] = 2
f[3] = 3
f[4] = 5
f[5] = 8
f[x_] := f[x] = f[x - 1] + f[x - 2]
In[6]:= f[5]
Out[6]= 8
You can see how a definition like f[x_] := f[x] = f[x-1] + f[x-2] works. The function f[x_] is
defined to be the program f[x] = f[x-1] + f[x-2]. When you ask for a value of the function f,
the program is executed. The program first calculates the value of f[x-1] + f[x-2], then saves the
result as f[x].
It is often a good idea to use functions that remember values when you implement mathematical
recursion relations in Mathematica. In a typical case, a recursion relation gives the value of a function f
with an integer argument x in terms of values of the same function with arguments x , x , etc.
The Fibonacci function definition fx fx fx used above is an example of this kind of
recursion relation. The point is that if you calculate say f by just applying the recursion relation
over and over again, you end up having to recalculate quantities like f many times. In a case like
316
this, it is therefore better just to remember the value of f, and look it up when you need it, rather
than having to recalculate it.
There is of course a trade-off involved in remembering values. It is faster to find a particular value,
but it takes more memory space to store all of them. You should usually define functions to remember
values only if the total number of different values that will be produced is comparatively small, or
the expense of recomputing them is very great.
f [args] := rhs
f [g[args], ... ] ^:= rhs
In[2]:= ?f
Global`f
f[g[x_]] := fg[x]
In[4]:= ?g
Global`g
Exp[g[x_]] ^:= expg[x]
317
In[5]:= ??Exp
Exp[z] is the exponential function.
Attributes[Exp] = {Listable, NumericFunction, Protected,
ReadProtected}
In[6]:= Exp[g[5]]
Out[6]= expg
5
In simple cases, you will get the same answers to calculations whether you give a definition for
f [g[x]] as a downvalue for f or an upvalue for g. However, one of the two choices is usually much
more natural and efficient than the other.
A good rule of thumb is that a definition for f [g[x]] should be given as an upvalue for g in cases
where the function f is more common than g. Thus, for example, in the case of Exp[g[x]], Exp is a
built-in Mathematica function, while g is presumably a function you have added. In such a case, you
will typically think of definitions for Exp[g[x]] as giving relations satisfied by g. As a result, it is
more natural to treat the definitions as upvalues for g than as downvalues for Exp.
This gives the definition as an upvalue
for g.
In[8]:= ?g
Global`g
Exp[g[x_]] ^:= expg[x]
g[x_] + g[y_] ^:= gplus[x, y]
Since the full form of the pattern g[x_] + g[y_] is Plus[g[x_], g[y_]], a definition for this
pattern could be given as a downvalue for Plus. It is almost always better, however, to give the
definition as an upvalue for g.
In general, whenever Mathematica encounters a particular function, it tries all the definitions you
have given for that function. If you had made the definition for g[x_] + g[y_] a downvalue for Plus,
then Mathematica would have tried this definition whenever Plus occurs. The definition would thus
be tested every time Mathematica added expressions together, making this very common operation
slower in all cases.
However, by giving a definition for g[x_] + g[y_] as an upvalue for g, you associate the definition
with g. In this case, Mathematica only tries the definition when it finds a g inside a function such
as Plus. Since g presumably occurs much less frequently than Plus, this is a much more efficient
procedure.
318
In[10]:= area[square] ^= 1
In[11]:= perimeter[square] ^= 4
In[12]:= ?square
Out[10]= 1
Out[11]= 4
Global`square
area[square] ^= 1
perimeter[square] ^= 4
In general, you can associate definitions for an expression with any symbol that occurs at a sufficiently high level in the expression. With an expression of the form f [args], you can define an upvalue
for a symbol g so long as either g itself, or an object with head g, occurs in args. If g occurs at a lower
level in an expression, however, you cannot associate definitions with it.
g occurs as the head of an argument,
so you can associate a definition with
it.
Out[14]= $Failed
f [ ... ] := rhs
downvalue for f
downvalue for f
upvalue for g
upvalue for g
319
As discussed in Section 2.1.2, you can use Mathematica symbols as tags, to indicate the type of
an expression. For example, complex numbers in Mathematica are represented internally in the form
Complex[x, y], where the symbol Complex serves as a tag to indicate that the object is a complex
number.
Upvalues provide a convenient mechanism for specifying how operations act on objects that are
tagged to have a certain type. For example, you might want to introduce a class of abstract mathematical objects of type quat. You can represent each object of this type by a Mathematica expression
of the form quat[data].
In a typical case, you might want quat objects to have special properties with respect to arithmetic
operations such as addition and multiplication. You can set up such properties by defining upvalues
for quat with respect to Plus and Times.
This defines an upvalue for quat with
respect to Plus.
When you define an upvalue for quat with respect to an operation like Plus, what you are effectively doing is to extend the domain of the Plus operation to include quat objects. You are telling
Mathematica to use special rules for addition in the case where the things to be added together are
quat objects.
In defining addition for quat objects, you could always have a special addition operation, say
quatPlus , to which you assign an appropriate downvalue. It is usually much more convenient, however, to use the standard Mathematica Plus operation to represent addition, but then to overload
this operation by specifying special behavior when quat objects are encountered.
You can think of upvalues as a way to implement certain aspects of object-oriented programming.
A symbol like quat represents a particular type of object. Then the various upvalues for quat specify
methods that define how quat objects should behave under certain operations, or on receipt of
certain messages.
320
If you make a definition such as f[x_] := value, Mathematica will use the value you give for any f
function it encounters. In some cases, however, you may want to define a value that is to be used
specifically when you ask for numerical values.
expr = value
N[expr] = value
In[3]:= N[%]
Out[2]= f 2 f 5
Out[3]= 0.793244
You can define numerical values for both functions and symbols. The numerical values are used
by all numerical Mathematica functions, including NIntegrate , FindRoot and so on.
N[expr] = value
,
Mathematica treats numerical values essentially like upvalues. When you define a numerical value
for f, Mathematica effectively enters your definition as an upvalue for f with respect to the numerical
evaluation operation N.
321
Unprotect[f]
Protect[f]
remove protection
add protection
In[1]:= Log[7] = 2
Set::write: Tag Log in Log[7] is Protected.
Out[1]= 2
In[2]:= Unprotect[Log]
Out[2]= Log
In[3]:= Log[7] = 2
In[5]:= Log[7] =.
In[6]:= Protect[Log]
Out[3]= 2
Out[4]= 2 Log 3
Out[6]= Log
Definitions you give can override built-in features of Mathematica. In general, Mathematica tries to
use your definitions before it uses built-in definitions.
322
The rules that are built into Mathematica are intended to be appropriate for the broadest range of
calculations. In specific cases, however, you may not like what the built-in rules do. In such cases,
you can give your own rules to override the ones that are built in.
There is a built-in rule for simplifying
Exp[Log[expr]] .
In[7]:= Exp[Log[y]]
In[8]:= (
Out[7]= y
Unprotect[Exp] ;
Exp[Log[expr_]] := explog[expr] ;
Protect[Exp] ;
)
In[9]:= Exp[Log[y]]
Out[9]= explog
y
Mathematica effectively stores all definitions you give as lists of transformation rules. When a particular
symbol is encountered, the lists of rules associated with it are tried.
Under most circumstances, you do not need direct access to the actual transformation rules associated with definitions you have given. Instead, you can simply use lhs = rhs and lhs =. to add and
remove rules. In some cases, however, you may find it useful to have direct access to the actual rules.
Here is a definition for f.
In[2]:= DownValues[f]
Out[2]= HoldPattern
f
x_
x2
Notice that the rules returned by DownValues and UpValues are set up so that neither their leftnor right-hand sides get evaluated. The left-hand sides are wrapped in HoldPattern , and the rules
are delayed, so that the right-hand sides are not immediately evaluated.
As discussed in Section 2.5.6, Mathematica tries to order definitions so that more specific ones appear
before more general ones. In general, however, there is no unique way to make this ordering, and
323
you may want to choose a different ordering from the one that Mathematica chooses by default. You
can do this by reordering the list of rules obtained from DownValues or UpValues .
Here are some definitions for the
object g.
In[4]:= DownValues[g]
324
Computation
5+6
Simplification
x - 3x + 1
Execution
x=5
11
1 - 2x
5
Mathematica is an infinite evaluation system. When you enter an expression, Mathematica will keep
on using definitions it knows until it gets a result to which no definitions apply.
This defines x1 in terms of x2, and
then defines x2.
In[1]:= x1 = x2 + 2 ; x2 = 7
Out[1]= 7
In[2]:= x1
In[4]:= fac[10]
Out[2]= 9
Out[4]= 3628800
325
When Mathematica has used all the definitions it knows, it gives whatever expression it has obtained
as the result. Sometimes the result may be an object such as a number. But usually the result is an
expression in which some objects are represented in a symbolic form.
Mathematica uses its built-in definitions
for simplifying sums, but knows no
definitions for f[3], so leaves this in
symbolic form.
Mathematica follows the principle of applying definitions until the result it gets no longer changes.
This means that if you take the final result that Mathematica gives, and enter it as Mathematica input,
you will get back the same result again. (There are some subtle cases discussed in Section 2.6.13 in
which this does not occur.)
If you type in a result from
Mathematica, you get back the same
expression again.
In[6]:= 1 + 5 f[3]
Out[6]= 1 5 f
3
At any given time, Mathematica can only use those definitions that it knows at that time. If you
add more definitions later, however, Mathematica will be able to use these. The results you get from
Mathematica may change in this case.
Here is a new definition for the
function f.
In[8]:= 1 + 5 f[3]
Out[7]= x2
Out[8]= 46
The simplest examples of evaluation involve using definitions such as f[x_] = x^2 which transform one expression directly into another. But evaluation is also the process used to execute programs
written in Mathematica. Thus, for example, if you have a procedure consisting of a sequence of Mathematica expressions, some perhaps representing conditionals and loops, the execution of this procedure
corresponds to the evaluation of these expressions. Sometimes the evaluation process may involve
evaluating a particular expression several times, as in a loop.
The expression Print[zzzz] is
evaluated three times during the
evaluation of the Do expression.
326
forms to be reduced to the single standard form a + b + c. The built-in definitions for Plus are set
up to do this.
Through the built-in definitions for
Plus, this expression is reduced to a
standard unparenthesized form.
In[1]:= (a + b) + c
Out[1]= a b c
Whenever Mathematica knows that a function is associative, it tries to remove parentheses (or nested
invocations of the function) to get the function into a standard flattened form.
A function like addition is not only associative, but also commutative, which means that expressions
like a + c + b and a + b + c with terms in different orders are equal. Once again, Mathematica tries to
put all such expressions into a standard form. The standard form it chooses is the one in which all
the terms are in a definite order, corresponding roughly to alphabetical order.
Mathematica sorts the terms in this sum
into a standard order.
flat (associative)
orderless (commutative)
In[2]:= c + a + b
Out[2]= a b c
Two important properties that Mathematica uses in reducing certain functions to standard form.
There are several reasons to try to put expressions into standard forms. The most important is that
if two expressions are really in standard form, it is obvious whether or not they are equal.
When the two sums are put into
standard order, they are immediately
seen to be equal, so that two fs
cancel, leaving the result 0.
You could imagine finding out whether a + c + b was equal to c + a + b by testing all possible
orderings of each sum. It is clear that simply reducing both sums to standard form is a much more
efficient procedure.
One might think that Mathematica should somehow automatically reduce all mathematical expressions to a single standard canonical form. With all but the simplest kinds of expressions, however, it
is quite easy to see that you do not want the same standard form for all purposes.
For polynomials, for example, there are two obvious standard forms, which are good for different
purposes. The first standard form for a polynomial is a simple sum of terms, as would be generated
in Mathematica by applying the function Expand. This standard form is most appropriate if you need
to add and subtract polynomials.
2.6.3 Attributes
327
There is, however, another possible standard form that you can use for polynomials. By applying
Factor, you can write any polynomial as a product of irreducible factors. This canonical form is
useful if you want to do operations like division.
Expanded and factored forms are in a sense both equally good standard forms for polynomials.
Which one you decide to use simply depends on what you want to use it for. As a result, Mathematica
does not automatically put polynomials into one of these two forms. Instead, it gives you functions
like Expand and Factor that allow you explicitly to put polynomials in whatever form you want.
Here is a list of two polynomials that
are mathematically equal.
In[5]:= Expand[t]
In[6]:= Factor[t]
Out[5]= 1 x2 , 1 x2
Although it is clear that you do not always want expressions reduced to the same standard form,
you may wonder whether it is at least possible to reduce all expressions to some standard form.
There is a basic result in the mathematical theory of computation which shows that this is, in fact,
not always possible. You cannot guarantee that any finite sequence of transformations will take any
two arbitrarily chosen expressions to a standard form.
In a sense, this is not particularly surprising. If you could in fact reduce all mathematical expressions to a standard form, then it would be quite easy to tell whether any two expressions were equal.
The fact that so many of the difficult problems of mathematics can be stated as questions about the
equality of expressions suggests that this can in fact be difficult.
2.6.3 Attributes
Definitions such as f[x_] = x^2 specify values for functions. Sometimes, however, you need to specify
general properties of functions, without necessarily giving explicit values.
Mathematica provides a selection of attributes that you can use to specify various properties of
functions. For example, you can use the attribute Flat to specify that a particular function is flat,
so that nested invocations are automatically flattened, and it behaves as if it were associative.
328
Attributes like Flat can affect not only evaluation, but also operations such as pattern matching.
If you give definitions or transformation rules for a function, you must be sure to have specified the
attributes of the function first.
Here is a definition for the flat
function f.
In[4]:= f[a, a, a, b, b, b, c, c]
Out[4]= f
a, b, c
Attributes[f]
Attributes[f] = {attr , attr , ... }
Attributes[f] = {}
SetAttributes[f, attr]
ClearAttributes[f, attr]
In[5]:= Attributes[f]
Out[5]= Flat
In[6]:= Attributes[f] = { }
Out[6]=
2.6.3 Attributes
329
Orderless
Flat
OneIdentity
Listable
Constant
NumericFunction
Protected
Locked
ReadProtected
HoldFirst
HoldRest
HoldAll
HoldAllComplete
NHoldFirst
NHoldRest
NHoldAll
SequenceHold
Temporary
Stub
In[7]:= Attributes[Plus]
Out[7]= Flat, Listable, NumericFunction,
OneIdentity, Orderless, Protected
330
Many of the attributes you can assign to functions in Mathematica directly affect the evaluation
of those functions. Some attributes, however, affect only other aspects of the treatment of functions. For example, the attribute OneIdentity affects only pattern matching, as discussed in Section
2.3.7. Similarly, the attribute Constant is only relevant in differentiation, and operations that rely on
differentiation.
The Protected attribute affects assignments. Mathematica does not allow you to make any definition associated with a symbol that carries this attribute. The functions Protect and Unprotect
discussed in Section 2.5.12 can be used as alternatives to SetAttributes and ClearAttributes to set
and clear this attribute. As discussed in Section 2.5.12 most built-in Mathematica objects are initially
protected so that you do not make definitions for them by mistake.
Here is a definition for the function g.
In[11]:= g[x_] = x + 1
Out[11]= 1 x
In[12]:= Protect[g]
Out[12]= g
In[13]:= g[x_] = x
Set::write: Tag g in g[x_] is Protected.
Out[13]= x
You can usually see the definitions you have made for a particular symbol by typing ?f, or by
using a variety of built-in Mathematica functions. However, if you set the attribute ReadProtected ,
Mathematica will not allow you to look at the definition of a particular symbol. It will nevertheless
continue to use the definitions in performing evaluation.
Although you cannot modify it, you
can still look at the definition of g.
In[14]:= ?g
Global`g
Attributes[g] = {Protected}
g[x_] = 1 + x
In[16]:= ?g
Global`g
Attributes[g] = {Protected, ReadProtected}
2.6.3 Attributes
331
Functions like SetAttributes and ClearAttributes usually allow you to modify the attributes of
a symbol in any way. However, if you once set the Locked attribute on a symbol, then Mathematica
will not allow you to modify the attributes of that symbol for the remainder of your Mathematica
session. Using the Locked attribute in addition to Protected or ReadProtected , you can arrange for
it to be impossible for users to modify or read definitions.
Clear[f]
ClearAll[f]
In[17]:= ClearAll[p]
By defining attributes for a function you specify properties that Mathematica should assume whenever that function appears. Often, however, you want to assume the properties only in a particular
instance. In such cases, you will be better off not to use attributes, but instead to call a particular
function to implement the transformation associated with the attributes.
By explicitly calling Thread, you can
implement the transformation that
would be done automatically if p were
listable.
Orderless
Flat
Sort[f [args]]
Flatten[f [args]]
Listable
Thread[f [args]]
Constant
Dt[expr, Constants->f]
Attributes in Mathematica can only be permanently defined for single symbols. However, Mathematica also allows you to set up pure functions which behave as if they carry attributes.
332
In[2]:= ps = Plus
Out[2]= Plus
As soon as Mathematica has evaluated the head of an expression, it sees whether the head is
a symbol that has attributes. If the symbol has the attributes Orderless , Flat or Listable , then
immediately after evaluating the elements of the expression Mathematica performs the transformations
associated with these attributes.
The next step in the standard evaluation procedure is to use definitions that Mathematica knows for
the expression it is evaluating. Mathematica first tries to use definitions that you have made, and if
there are none that apply, it tries built-in definitions.
If Mathematica finds a definition that applies, it performs the corresponding transformation on the
expression. The result is another expression, which must then in turn be evaluated according to the
standard evaluation procedure.
333
As discussed in Section 2.6.1, Mathematica follows the principle that each expression is evaluated
until no further definitions apply. This means that Mathematica must continue re-evaluating results
until it gets an expression which remains unchanged through the evaluation procedure.
Here is an example that shows how the standard evaluation procedure works on a simple expression. We assume that a = 7.
2 a x + a^2 + 1
Times[2, 7, x]
a is evaluated to give 7
Times[14, x]
Power[a, 2]
Power[7, 2]
49
Plus[Times[14, x], 49, 1]
Plus[50, Times[14, x]]
50 + 14 x
A simple example of evaluation in Mathematica.
334
Mathematica provides various ways to trace the evaluation process, as discussed in Section 2.6.11.
The function Trace[expr] gives a nested list showing each subexpression generated during evaluation. (Note that the standard evaluation traverses the expression tree in a depth-first way, so that the
smallest subparts of the expression appear first in the results of Trace.)
First set a to 7.
In[4]:= a = 7
Out[4]= 7
The order in which Mathematica applies different kinds of definitions is important. The fact that
Mathematica applies definitions you have given before it applies built-in definitions means that you
can give definitions which override the built-in ones, as discussed in Section 2.5.12.
This expression is evaluated using the
built-in definition for ArcSin.
In[6]:= ArcSin[1]
Out[6]=
2
In[8]:= ArcSin[1]
5
Out[8]=
2
As discussed in Section 2.5.10, you can associate definitions with symbols either as upvalues or
downvalues. Mathematica always tries upvalue definitions before downvalue ones.
If you have an expression like f [g[x]], there are in general two sets of definitions that could
apply: downvalues associated with f, and upvalues associated with g. Mathematica tries the definitions
associated with g before those associated with f.
This ordering follows the general strategy of trying specific definitions before more general ones.
By applying upvalues associated with arguments before applying downvalues associated with a function, Mathematica allows you to make definitions for special arguments which override the general
definitions for the function with any arguments.
This defines a rule for f[g[x_]] , to be
associated with f.
In[11]:= f[g[2]]
Out[11]= grule
2
335
Definitions associated with g are applied before definitions associated with f in the expression
f [g[x]].
The order in which definitions are applied.
Most functions such as Plus that are built into Mathematica have downvalues. There are, however,
some objects in Mathematica which have built-in upvalues. For example, SeriesData objects, which
represent power series, have built-in upvalues with respect to various mathematical operations.
For an expression like f [g[x]], the complete sequence of definitions that are tried in the standard
evaluation procedure is:
Definitions you have given associated with g;
Built-in definitions associated with g;
Definitions you have given associated with f;
Built-in definitions associated with f.
The fact that upvalues are used before downvalues is important in many situations. In a typical
case, you might want to define an operation such as composition. If you give upvalues for various objects with respect to composition, these upvalues will be used whenever such objects appear.
However, you can also give a general procedure for composition, to be used if no special objects are
present. You can give this procedure as a downvalue for composition. Since downvalues are tried
after upvalues, the general procedure will be used only if no objects with upvalues are present.
Here is a definition associated with q
for composition of q objects.
Out[15]= qcomp 1, 2
Out[16]= gencomp r, 1, 2
In general, there can be several objects that have upvalues in a particular expression. Mathematica
first looks at the head of the expression, and tries any upvalues associated with it. Then it successively
looks at each element of the expression, trying any upvalues that exist. Mathematica performs this
procedure first for upvalues that you have explicitly defined, and then for upvalues that are built in.
336
The procedure means that in a sequence of elements, upvalues associated with earlier elements take
precedence over those associated with later elements.
This defines an upvalue for p with
respect to c.
x=y
If[p, a, b]
Do[expr, {n}]
Plot[f, {x, ... }]
Function[{x}, body]
When you give a definition such as a = 1, Mathematica does not evaluate the a that appears on the
left-hand side. You can see that there would be trouble if the a was evaluated. The reason is that if
you had previously set a = 7, then evaluating a in the definition a = 1 would put the definition into
the nonsensical form 7 = 1.
In the standard evaluation procedure, each argument of a function is evaluated in turn. This is prevented by setting the attributes HoldFirst , HoldRest and HoldAll. These attributes make Mathematica
hold particular arguments in an unevaluated form.
HoldFirst
337
HoldRest
HoldAll
In[1]:= f[1 + 1, 2 + 4]
In[3]:= h[1 + 1, 2 + 4]
In[5]:= Attributes[Set]
Out[1]= f 2, 6
Out[3]= h 1 1, 6
Out[4]= 64
Even though a function may have attributes which specify that it should hold certain arguments
unevaluated, you can always explicitly tell Mathematica to evaluate those arguments by giving the
arguments in the form Evaluate[arg] .
Evaluate effectively overrides the
HoldFirst attribute, and causes the
first argument to be evaluated.
f [Evaluate[arg]]
By holding its arguments, a function can control when those arguments are evaluated. By using
Evaluate , you can force the arguments to be evaluated immediately, rather than being evaluated
under the control of the function. This capability is useful in a number of circumstances.
One example discussed on page 132 occurs when plotting graphs of expressions. The Mathematica
Plot function holds unevaluated the expression you are going to plot, then evaluates it at a sequence
of numerical positions. In some cases, you may instead want to evaluate the expression immediately,
and have Plot work with the evaluated form. For example, if you want to plot a list of functions
338
generated by Table, then you will want the Table operation done immediately, rather than being
done every time a point is to be plotted.
Evaluate causes the list of functions to
be constructed immediately, rather than
being constructed at each value of x
chosen by Plot.
In[7]:= Plot[
Evaluate[Table[Sin[n x], {n, 1, 3}]],
{x, 0, 2Pi} ]
1
0.5
-0.5
-1
There are a number of built-in Mathematica functions which, like Plot, are set up to hold some of
their arguments. You can always override this behavior using Evaluate .
The Mathematica Set function holds its
first argument, so the symbol a is not
evaluated in this case.
In[8]:= a = b
In[9]:= Evaluate[a] = 6
In[10]:= b
Out[8]= b
Out[9]= 6
Out[10]= 6
In most cases, you want all expressions you give to Mathematica to be evaluated. Sometimes,
however, you may want to prevent the evaluation of certain expressions. For example, if you want
to manipulate pieces of a Mathematica program symbolically, then you must prevent those pieces from
being evaluated while you are manipulating them.
You can use the functions Hold and HoldForm to keep expressions unevaluated. These functions
work simply by carrying the attribute HoldAll, which prevents their arguments from being evaluated.
The functions provide wrappers inside which expressions remain unevaluated.
The difference between Hold[expr] and HoldForm[expr] is that in standard Mathematica output
format, Hold is printed explicitly, while HoldForm is not. If you look at the full internal Mathematica
form, you can however see both functions.
Hold maintains expressions in an
unevaluated form.
In[11]:= Hold[1 + 1]
Out[11]= Hold
1 1
339
In[12]:= HoldForm[1 + 1]
In[13]:= FullForm[%]
Out[12]= 1 1
Hold[expr]
HoldComplete[expr]
HoldForm[expr]
ReleaseHold[expr]
Extract[expr, index, Hold]
In[14]:= ReleaseHold[%]
Out[14]= 2
Out[15]= 5
Out[16]= Hold
2 3
In[17]:= ReplacePart[ Hold[1 + 1, 2 + 3], Hold[7 + 8], 2, 1]
Out[17]= Hold
1 1, 7 8
In[18]:= Length[1 + 1]
Out[18]= 0
340
SequenceHold
HoldAllComplete
By setting the attribute HoldAll, you can prevent Mathematica from evaluating the arguments of a
function. But even with this attribute set, Mathematica will still do some transformations on the arguments. By setting SequenceHold you can prevent it from flattening out Sequence objects that appear in
the arguments. And by setting HoldAllComplete you can also inhibit the stripping of Unevaluated ,
and prevent Mathematica from using any upvalues it finds associated with the arguments.
Out[1]= p k
Out[2]= a2 , b2
There are some cases, however, where you may want to keep all or part of a pattern unevaluated.
You can do this by wrapping the parts you do not want to evaluate with HoldPattern . In general,
whenever HoldPattern[patt] appears within a pattern, this form is taken to be equivalent to patt for
the purpose of pattern matching, but the expression patt is maintained unevaluated.
HoldPattern[patt]
Preventing evaluation in patterns.
341
One application for HoldPattern is in specifying patterns which can apply to unevaluated expressions, or expressions held in an unevaluated form.
HoldPattern keeps the 1 + 1 from
being evaluated, and allows it to match
the 1 + 1 on the left-hand side of the
/. operator.
Notice that while functions like Hold prevent evaluation of expressions, they do not affect the
manipulation of parts of those expressions with /. and other operators.
This defines values for r whenever its
argument is not an atomic object.
In[5]:= r[3]
In[6]:= r[x_]
Out[5]= r 3
Out[6]= x_2
Out[7]= 3, 5
As illustrated above, the left-hand sides of transformation rules such as lhs -> rhs are usually
evaluated immediately, since the rules are usually applied to expressions which have already been
evaluated. The right-hand side of lhs -> rhs is also evaluated immediately. With the delayed rule
lhs :> rhs, however, the expression rhs is not evaluated.
The right-hand side is evaluated
immediately in -> but not :> rules.
While the left-hand sides of transformation rules are usually evaluated, the left-hand sides of definitions are usually not. The reason for the difference is as follows. Transformation rules are typically
applied using /. to expressions that have already been evaluated. Definitions, however, are used
during the evaluation of expressions, and are applied to expressions that have not yet been completely
342
evaluated. To work on such expressions, the left-hand sides of definitions must be maintained in a
form that is at least partially unevaluated.
Definitions for symbols are the simplest case. As discussed in the previous section, a symbol on
the left-hand side of a definition such as x = value is not evaluated. If x had previously been assigned
a value y, then if the left-hand side of x = value were evaluated, it would turn into the quite unrelated
definition y = value.
Here is a definition. The symbol on
the left-hand side is not evaluated.
In[10]:= k = w[3]
In[11]:= k = w[4]
Out[10]= w 3
Out[11]= w 4
In[13]:= w[4]
Out[12]= w 5
Out[13]= w 5
Although individual symbols that appear on the left-hand sides of definitions are not evaluated,
more complicated expressions are partially evaluated. In an expression such as f [args] on the left-hand
side of a definition, the args are evaluated.
The 1 + 1 is evaluated, so that a value
is defined for g[2].
In[14]:= g[1 + 1] = 5
In[15]:= ?g
Out[14]= 5
Global`g
g[2] = 5
You can see why the arguments of a function that appears on the left-hand side of a definition
must be evaluated by considering how the definition is used during the evaluation of an expression.
As discussed in Section 2.6.1, when Mathematica evaluates a function, it first evaluates each of the
arguments, then tries to find definitions for the function. As a result, by the time Mathematica applies
any definition you have given for a function, the arguments of the function must already have been
evaluated. An exception to this occurs when the function in question has attributes which specify that
it should hold some of its arguments unevaluated.
symbol = value
343
symbol := value
f [args] = value
f [HoldPattern[arg]] = value
Evaluate[lhs] = value
Evaluation in definitions.
While in most cases it is appropriate for the arguments of a function that appears on the left-hand
side of a definition to be evaluated, there are some situations in which you do not want this to happen.
In such cases, you can wrap HoldPattern around the parts that you do not want to be evaluated.
In most cases, it is convenient for the function f in an expression like Table[f, {i, imax}] to be
maintained in an unevaluated form until specific values have been assigned to i. This is true in
particular if a complete symbolic form for f valid for any i cannot be found.
This defines fac to give the factorial
when it has an integer argument, and
to give NaN (standing for Not a
Number) otherwise.
344
In cases where a complete symbolic form for f with arbitrary i in expressions such as
Table[f, {i, imax}] can be found, it is often more efficient to compute this form first, and then feed
it to Table. You can do this using Table[Evaluate[f], {i, imax}].
The Sum in this case is evaluated
separately for each value of i.
Out[7]= i i2 i3 i4
As discussed on page 132, it is convenient to use Evaluate when you plot a graph of a function or
a list of functions. This causes the symbolic form of the function or list to be found first, before the
iteration begins.
2.6.8 Conditionals
345
2.6.8 Conditionals
Mathematica provides various ways to set up conditionals, which specify that particular expressions
should be evaluated only if certain conditions hold.
Out[1]= y
When you write programs in Mathematica, you will often have a choice between making a single
definition whose right-hand side involves several branches controlled by If functions, or making
several definitions, each controlled by an appropriate /; condition. By using several definitions, you
can often produce programs that are both clearer, and easier to modify.
This defines a step function, with value
1 for x > 0, and -1 otherwise.
In[6]:= ?g
Global`g
g[x_] := 1 /; x > 0
g[x_] := -1 /; x <= 0
The function If provides a way to choose between two alternatives. Often, however, there will be
more than two alternatives. One way to handle this is to use a nested set of If functions. Usually,
however, it is instead better to use functions like Which and Switch.
346
In[8]:= h[-5]
Out[8]= 25
In[9]:= h[2]
Out[9]= 0
In[11]:= r[7]
In[12]:= Switch[17, 0, a, 1, b, _, q]
Out[11]= b
Out[12]= q
An important point about symbolic systems such as Mathematica is that the conditions you give
may yield neither True nor False. Thus, for example, the condition x == y does not yield True or
False unless x and y have specific values, such as numerical ones.
In this case, the test gives neither True
nor False, so both branches in the If
remain unevaluated.
In[13]:= If[x == y, a, b]
In[14]:= If[x == y, a, b, c]
Out[13]= If x y, a, b
Out[14]= c
give True if lhs and rhs are not identical, and False
otherwise
MatchQ[expr, form]
In[15]:= x == y
Out[15]= x y
2.6.8 Conditionals
347
In[16]:= TrueQ[x == y]
In[17]:= x === y
Out[16]= False
Out[17]= False
The main difference between lhs === rhs and lhs == rhs is that === always returns True or False,
whereas == can leave its input in symbolic form, representing a symbolic equation, as discussed in
Section 1.5.5. You should typically use === when you want to test the structure of an expression, and
== if you want to test mathematical equality. The Mathematica pattern matcher effectively uses === to
determine when one literal expression matches another.
You can use === to test the structure of
expressions.
Out[18]= False
In setting up conditionals, you will often need to use combinations of tests, such as
test && test && ... . An important point is that the result from this combination of tests will be False
if any of the testi yield False. Mathematica always evaluates the testi in turn, stopping if any of the
testi yield False.
In[21]:= t[2]
Out[21]= True
In[22]:= t[0]
Out[22]= False
The way that Mathematica evaluates logical expressions allows you to combine sequences of tests
where later tests may make sense only if the earlier ones are satisfied. The behavior, which is analogous to that found in languages such as C, is convenient in constructing many kinds of Mathematica
programs.
348
1
4
9
16
1
Out[2]=
6
1
4
1
12 x
The way iteration is specified in Do is exactly the same as in functions like Table and Sum. Just as
in those functions, you can set up several nested loops by giving a sequence of iteration specifications
to Do.
This loops over values of i from 1 to
4, and for each value of i, loops over
j from 1 to i-1.
1}
1}
2}
1}
2}
3}
Sometimes you may want to repeat a particular operation a certain number of times, without
changing the value of an iteration variable. You can specify this kind of repetition in Do just as you
can in Table and other iteration functions.
This repeats the assignment
t = 1/(1+t) three times.
1
Out[4]=
1
1
1
1
1x
Nest[f, expr, n]
FixedPoint[f, expr]
NestWhile[f, expr, test]
349
Do allows you to repeat operations by evaluating a particular expression many times with different
values for iteration variables. Often, however, you can make more elegant and efficient programs
using the functional programming constructs discussed in Section 2.2.2. Nest[f, x, n], for example,
allows you to apply a function repeatedly to an expression.
This nests f three times.
In[6]:= Nest[f, x, 3]
Out[6]= f
f
f
x
1
Out[7]=
1
1
1
1
1x
Nest allows you to apply a function a specified number of times. Sometimes, however, you may
simply want to go on applying a function until the results you get no longer change. You can do this
using FixedPoint[f, x].
FixedPoint goes on applying a
function until the result no longer
changes.
You can use FixedPoint to imitate the evaluation process in Mathematica, or the operation of
functions such as expr //. rules. FixedPoint goes on until two successive results it gets are the same.
NestWhile allows you to go on until an arbitrary function no longer yields True.
350
Catch[expr]
Catch[expr, form]
Catch[expr, form, f]
Throw and Catch provide a flexible way to control the process of evaluation in Mathematica. The
basic idea is that whenever a Throw is encountered, the evaluation that is then being done is stopped,
and Mathematica immediately returns to the nearest appropriate enclosing Catch.
Scan applies the function Print to
each successive element in the list, and
in the end just returns Null.
In[11]:= Catch[Scan[(Print[#];
If[# < 6, Throw[#]])&, {7, 6, 5, 4}]]
7
6
5
4
7
6
5
Out[11]= 5
In[12]:= Catch[Map[(Print[#];
If[# < 6, Throw[#]])&, {7, 6, 5, 4}]]
7
6
5
Out[12]= 5
You can use Throw and Catch to divert the operation of functional programming constructs, allowing for example the evaluation of such constructs to continue only until some condition has been met.
Note that if you stop evaluation using Throw, then the structure of the result you get may be quite
different from what you would have got if you had allowed the evaluation to complete.
Here is a list generated by repeated
application of a function.
351
Out[15]= 3.
Throw and Catch operate in a completely global way: it does not matter how or where a Throw is
generatedit will always stop evaluation and return to the enclosing Catch.
The Throw stops the evaluation of f,
and causes the Catch to return just a,
with no trace of f left.
Out[16]= a
Out[18]= 24
In small programs, it is often adequate to use Throw[value] and Catch[expr] in their simplest form.
But particularly if you write larger programs that contain many separate pieces, it is usually much
better to use Throw[value, tag] and Catch[expr, form]. By keeping the expressions tag and form local
to a particular piece of your program, you can then ensure that your Throw and Catch will also
operate only within that piece.
Here the Throw is caught by the inner
Catch.
Out[20]= f x
Out[21]= x
Out[22]= x
Out[23]= x
You should realize that there is no need for the tag that appears in Throw to be a constant; in
general it can be any expression.
Here the inner Catch catches all throws
with tags less than 4, and continues
the Do. But as soon as the tag reaches
4, the outer Catch is needed.
352
When you use Catch[expr, form] with Throw[value, tag], the value returned by Catch is simply
the expression value given in the Throw. If you use Catch[expr, form, f], however, then the value
returned by Catch is instead f [value, tag].
Here f is applied to the value and tag
in the Throw.
In[26]:= Catch[ x, a, f ]
Out[25]= f x, a
Out[26]= x
While[test, body]
For[start, test, incr, body]
Functions like Do, Nest and FixedPoint provide structured ways to make loops in Mathematica
programs, while Throw and Catch provide opportunities for modifying this structure. Sometimes,
however, you may want to create loops that even from the outset have less structure. And in such
cases, you may find it convenient to use the functions While and For, which perform operations
repeatedly, stopping when a specified condition fails to be true.
The While loop continues until the
condition fails.
The functions While and For in Mathematica are similar to the control structures while and for in
languages such as C. Notice, however, that there are a number of important differences. For example,
the roles of comma and semicolon are reversed in Mathematica For loops relative to C language ones.
This is a very common form for a For
loop. i++ increments the value of i.
1
2
3
2
1 + x
2 2
2 + (1 + x )
2 2 2
3 + (2 + (1 + x ) )
In Mathematica, both While and For always evaluate the loop test before evaluating the body of
the loop. As soon as the loop test fails to be True, While and For terminate. The body of the loop is
thus only evaluated in situations where the loop test is True.
353
In a While or For loop, or in general in any Mathematica procedure, the Mathematica expressions
you give are evaluated in a definite sequence. You can think of this sequence as defining the flow of
control in the execution of a Mathematica program.
In most cases, you should try to keep the flow of control in your Mathematica programs as simple
as possible. The more the flow of control depends for example on specific values generated during
the execution of the program, the more difficult you will typically find it to understand the structure
and operation of the program.
Functional programming constructs typically involve very simple flow of control. While and For
loops are always more complicated, since they are set up to make the flow of control depend on the
values of the expressions given as tests. Nevertheless, even in such loops, the flow of control does
not usually depend on the values of expressions given in the body of the loop.
In some cases, however, you may need to construct Mathematica programs in which the flow of
control is affected by values generated during the execution of a procedure or of the body of a loop.
One way to do this, which fits in with functional programming ideas, is to use Throw and Catch.
But Mathematica also provides various functions for modifying the flow of control which work like in
languages such as C.
Break[ ]
Continue[ ]
Return[expr]
Goto[name]
Throw[value]
354
Return[expr] allows you to exit a particular function, returning a value. You can think of Throw
as a kind of non-local return which allows you to exit a whole sequence of nested functions. Such
behavior can be convenient for handling certain error conditions.
Here is an example of the use of
Return. This particular procedure
could equally well have been written
without using Return .
In[33]:= f[x_] :=
(If[x > 5, Return[big]]; t = x^3; Return[t - 7])
In[34]:= f[10]
Out[34]= big
Out[37]= error
Functions like Continue[ ] and Break[ ] allow you to transfer control to the beginning or end of
a loop in a Mathematica program. Sometimes you may instead need to transfer control to a particular
element in a Mathematica procedure. If you give a Label as an element in a procedure, you can use
Goto to transfer control to this element.
This goes on looping until q exceeds 6.
Note that you can use Goto in a particular Mathematica procedure only when the Label it specifies
occurs as an element of the same Mathematica procedure. In general, use of Goto reduces the degree
of structure that can readily be perceived in a program, and therefore makes the operation of the
program more difficult to understand.
355
In many computations one is concerned only with the final result of evaluating the expression given
as input. But sometimes one also wants to collect expressions that were generated in the course of
the evaluation. You can do this using Sow and Reap.
Sow[val]
Reap[expr]
Like Throw and Catch, Sow and Reap can be used anywhere in a computation.
This defines a function that can do a
Sow.
Sow[val, tag]
Reap[expr, form]
Out[5]= 0.868312,
0.415332, 0.446472, 0.408785, 0.456285
356
In[9]:= Reap[Sow[1, {x, x}]; Sow[2, y]; Sow[3, x], {x, x, y}]
3
4
Out[11]= Null, 1, 2, 3, , 4,
, 1, 2, 1, 1
2
3
Trace[expr]
Trace[expr, form]
In[1]:= Trace[1 + 1]
In[2]:= Trace[2^3 + 4]
Out[1]= 1 1, 2
Trace[expr] gives a list which includes all the intermediate expressions involved in the evaluation
of expr. Except in rather simple cases, however, the number of intermediate expressions generated in
this way is typically very large, and the list returned by Trace is difficult to understand.
357
Trace[expr, form] allows you to filter the expressions that Trace records, keeping only those
which match the pattern form.
Here is a recursive definition of a
factorial function.
In[5]:= Trace[fac[3]]
Out[4]= 1
Out[5]= fac
3, 3 fac
3 1, 3 1, 2, fac
2, 2 fac
2 1,
2 1, 1, fac
1, 1, 2 1, 2, 3 2, 6
Out[7]= fac 10, fac 9, fac 8, fac 7, fac 6
Trace[expr, form] effectively works by intercepting every expression that is about to be evaluated
during the evaluation of expr, and picking out those that match the pattern form.
If you want to trace calls to a function like fac, you can do so simply by telling Trace to pick
out expressions of the form fac[n_]. You can also use patterns like f[n_, 2] to pick out calls with
particular argument structure.
A typical Mathematica program, however, consists not only of function calls like fac[n], but
also of other elements, such as assignments to variables, control structures, and so on. All of these
elements are represented as expressions. As a result, you can use patterns in Trace to pick out any
kind of Mathematica program element. Thus, for example, you can use a pattern like k = _ to pick out
all assignments to the symbol k.
This shows the sequence of
assignments made for k.
1
3
Out[8]= k = 2, k =
, k = 4, k =
2
4
Trace[expr, form] can pick out expressions that occur at any time in the evaluation of expr. The
expressions need not, for example, appear directly in the form of expr that you give. They may instead
occur, say, during the evaluation of functions that are called as part of the evaluation of expr.
Here is a function definition.
3
2
Out[10]= k =
, k =
, k = 3, k = 1
2
3
Trace allows you to monitor intermediate steps in the evaluation not only of functions that you
define, but also of some functions that are built into Mathematica. You should realize, however, that the
specific sequence of intermediate steps followed by built-in Mathematica functions depends in detail
on their implementation and optimization in a particular version of Mathematica.
358
Trace[expr, f [___]]
Trace[expr, i = _]
show assignments to i
Trace[expr, _ = _]
Trace[expr, Message[___]]
The function Trace returns a list that represents the history of a Mathematica computation. The
expressions in the list are given in the order that they were generated during the computation. In
most cases, the list returned by Trace has a nested structure, which represents the structure of the
computation.
The basic idea is that each sublist in the list returned by Trace represents the evaluation chain
for a particular Mathematica expression. The elements of this chain correspond to different forms of
the same expression. Usually, however, the evaluation of one expression requires the evaluation of
a number of other expressions, often subexpressions. Each subsidiary evaluation is represented by a
sublist in the structure returned by Trace.
Here is a sequence of assignments.
In[12]:= Trace[a[1]]
Out[12]= a
1, a
2, a
3, a
4
In[13]:= Trace[y + x + y]
Out[13]= y x y, x y y, x 2 y
In[15]:= Trace[x x + y y]
Out[15]= x x, x2 , y y, y2 , x2 y2
In[16]:= Trace[f[f[f[1 + 1]]]]
Out[16]= 1 1, 2, f
2, f
f
2, f
f
f
2
There are two basic ways that subsidiary evaluations can be required during the evaluation of
a Mathematica expression. The first way is that the expression may contain subexpressions, each of
which has to be evaluated. The second way is that there may be rules for the evaluation of the expression that involve other expressions which themselves must be evaluated. Both kinds of subsidiary
evaluations are represented by sublists in the structure returned by Trace.
In[19]:= Trace[fe[6]]
359
You often get nested lists when you trace the evaluation of functions that are defined recursively
in terms of other instances of themselves. The reason is typically that each new instance of the
function appears as a subexpression in the expressions obtained by evaluating previous instances of
the function.
Thus, for example, with the definition fac[n_] := n fac[n-1] , the evaluation of fac[6] yields the
expression 6 fac[5], which contains fac[5] as a subexpression.
The successive instances of fac
generated appear in successively nested
sublists.
Out[24]= 1
Each step in the evaluation of any Mathematica expression can be thought of as the result of applying
a particular transformation rule. As discussed in Section 2.5.10, all the rules that Mathematica knows
are associated with specific symbols or tags. You can use Trace[expr, f] to see all the steps in
the evaluation of expr that are performed using transformation rules associated with the symbol f. In
this case, Trace gives not only the expressions to which each rule is applied, but also the results of
applying the rules.
360
In general, Trace[expr, form] picks out all the steps in the evaluation of expr where form matches
either the expression about to be evaluated, or the tag associated with the rule used.
Trace[expr, f]
Trace[expr, f | g]
Trace[expr, form] allows you to trace expressions matching form generated at any point in the
evaluation of expr. Sometimes, you may want to trace only expressions generated during certain parts
of the evaluation of expr.
By setting the option TraceOn -> oform, you can specify that tracing should be done only during
the evaluation of forms which match oform. Similarly, by setting TraceOff -> oform, you can specify
that tracing should be switched off during the evaluation of forms which match oform.
This shows all steps in the evaluation.
361
Out[32]= fac 2, 2, 2 x, log 2 x, log 2 log x
A powerful aspect of the Mathematica Trace function is that the object it returns is basically a
standard Mathematica expression which you can manipulate using other Mathematica functions. One
important point to realize, however, is that Trace wraps all expressions that appear in the list it
produces with HoldForm to prevent them from being evaluated. The HoldForm is not displayed in
standard Mathematica output format, but it is still present in the internal structure of the expression.
This shows the expressions generated
at intermediate stages in the evaluation
process.
In[37]:= InputForm[%]
For sophisticated computations, the list structures returned by Trace can be quite complicated.
When you use Trace[expr, form], Trace will include as elements in the lists only those expressions
362
which match the pattern form. But whatever pattern you give, the nesting structure of the lists remains
the same.
This shows all occurrences of fib[_]
in the evaluation of fib[3] .
Out[39]= fib 3, fib 2, fib 1, fib 0, fib 1
You can set the option TraceDepth -> n to tell Trace to include only lists nested at most n levels
deep. In this way, you can often pick out the big steps in a computation, without seeing the
details. Note that by setting TraceDepth or TraceOff you can avoid looking at many of the steps in
a computation, and thereby significantly speed up the operation of Trace for that computation.
This shows only steps that appear in
lists nested at most two levels deep.
When you use Trace[expr, form], you get a list of all the expressions which match form produced during the evaluation of expr. Sometimes it is useful to see not only these expressions, but
also the results that were obtained by evaluating them. You can do this by setting the option
TraceForward -> True in Trace.
This shows not only expressions which
match fac[_], but also the results of
evaluating those expressions.
Expressions picked out using Trace[expr, form] typically lie in the middle of an evaluation chain.
By setting TraceForward -> True, you tell Trace to include also the expression obtained at the end
of the evaluation chain. If you set TraceForward -> All, Trace will include all the expressions that
occur after the expression matching form on the evaluation chain.
With TraceForward->All , all elements
on the evaluation chain after the one
that matches fac[_] are included.
By setting the option TraceForward , you can effectively see what happens to a particular form of
expression during an evaluation. Sometimes, however, you want to find out not what happens to a
particular expression, but instead how that expression was generated. You can do this by setting the
363
option TraceBackward . What TraceBackward does is to show you what preceded a particular form of
expression on an evaluation chain.
This shows that the number 120 came
from the evaluation of fac[5] during
the evaluation of fac[10] .
TraceForward and TraceBackward allow you to look forward and backward in a particular evaluation chain. Sometimes, you may also want to look at the evaluation chains within which the particular
evaluation chain occurs. You can do this using TraceAbove . If you set the option TraceAbove -> True,
then Trace will include the initial and final expressions in all the relevant evaluation chains. With
TraceAbove -> All, Trace includes all the expressions in all these evaluation chains.
This includes the initial and final
expressions in all evaluation chains
which contain the chain that contains
120.
Out[46]= fac 7, fac 6, fac 5, 120, 720, 5040
364
The basic way that Trace[expr, ... ] works is to intercept each expression encountered during the
evaluation of expr, and then to use various criteria to determine whether this expression should be
recorded. Normally, however, Trace intercepts expressions only after function arguments have been
evaluated. By setting TraceOriginal -> True, you can get Trace also to look at expressions before
function arguments have been evaluated.
This includes expressions which match
fac[_] both before and after argument
evaluation.
The list structure produced by Trace normally includes only expressions that constitute steps in
non-trivial evaluation chains. Thus, for example, individual symbols that evaluate to themselves are
not normally included. Nevertheless, if you set TraceOriginal -> True, then Trace looks at absolutely every expression involved in the evaluation process, including those that have trivial evaluation
chains.
In this case, Trace includes absolutely
all expressions, even those with trivial
evaluation chains.
option name
default value
TraceForward
False
TraceBackward
False
TraceAbove
False
TraceOriginal
False
When you use Trace to study the execution of a program, there is an issue about how local variables in the program should be treated. As discussed in Section 2.7.3, Mathematica scoping constructs
such as Module create symbols with new names to represent local variables. Thus, even if you called
a variable x in the original code for your program, the variable may effectively be renamed x$nnn
when the program is executed.
Trace[expr, form] is set up so that by default a symbol x that appears in form will match all
symbols with names of the form x$nnn that arise in the execution of expr. As a result, you can
for example use Trace[expr, x = _] to trace assignment to all variables, local and global, that were
named x in your original program.
365
In some cases, you may want to trace only the global variable x, and not any local variables that
were originally named x. You can do this by setting the option MatchLocalNames -> False.
This traces assignments to all variables
with names of the form x$nnn.
Out[51]=
The function Trace performs a complete computation, then returns a structure which represents the
history of the computation. Particularly in very long computations, it is however sometimes useful to
see traces of the computation as it proceeds. The function TracePrint works essentially like Trace,
except that it prints expressions when it encounters them, rather than saving up all of the expressions
to create a list structure.
This prints expressions encountered in
the evaluation of fib[3] .
366
Trace[expr, ... ]
TracePrint[expr, ... ]
TraceDialog[expr, ... ]
Out[54]= fac 5
In[55]:= Stack[ ]
Out[55]= TraceDialog, Times,
Times, Times, Times, Times, fac
In[56]:= Return[ ]
TraceDialog::dgend: Exiting Dialog.
Out[53]= 3628800
The function TraceDialog effectively allows you to stop in the middle of a computation, and
interact with the Mathematica environment that exists at that time. You can for example find values of
intermediate variables in the computation, and even reset those values. There are however a number
of subtleties, mostly associated with pattern and module variables.
What TraceDialog does is to call the function Dialog on a sequence of expressions. The Dialog
function is discussed in detail in Section 2.14.2. When you call Dialog, you are effectively starting a
subsidiary Mathematica session with its own sequence of input and output lines.
In general, you may need to apply arbitrary functions to the expressions you get while tracing
an evaluation. TraceScan[f, expr, ... ] applies f to each expression that arises. The expression is
wrapped with HoldForm to prevent it from evaluating.
In TraceScan[f, expr, ... ], the function f is applied to expressions before they are evaluated.
TraceScan[f, expr, patt, fp] applies f before evaluation, and fp after evaluation.
367
{f[g[Print[Stack[_]]]]; , f[g[Print[Stack[_]]]],
g[Print[Stack[_]]], Print[Stack[_]]}
{CompoundExpression, f, g, Print}
In general, you can think of the evaluation stack as showing what functions called what other
functions to get to the point Mathematica is at in your computation. The sequence of expressions
corresponds to the first elements in the successively nested lists returned by Trace with the option
TraceAbove set to True.
Stack[ ]
Stack[_]
Stack[form]
It is rather rare to call Stack directly in your main Mathematica session. More often, you will want
to call Stack in the middle of a computation. Typically, you can do this from within a dialog, or
subsidiary session, as discussed in Section 2.14.2.
Here is the standard recursive
definition of the factorial function.
Out[5]= fac 4
368
In[6]:= Stack[ ]
Out[6]= TraceDialog, Times, Times,
Times, Times, Times, Times, fac
In[7]:= Return[ ]
TraceDialog::dgend: Exiting Dialog.
Out[4]= 3628800
In the simplest cases, the Mathematica evaluation stack is set up to record all expressions currently being evaluated. Under some circumstances, however, this may be inconvenient. For example,
executing Print[Stack[ ]] will always show a stack with Print as the last function.
The function StackInhibit allows you to avoid this kind of problem. StackInhibit[expr] evaluates expr without modifying the stack.
StackInhibit prevents Print from
being included on the stack.
Functions like TraceDialog automatically call StackInhibit each time they start a dialog. This
means that Stack does not show functions that are called within the dialog, only those outside.
StackInhibit[expr]
StackBegin[expr]
StackComplete[expr]
By using StackInhibit and StackBegin , you can control which parts of the evaluation process
are recorded on the stack. StackBegin[expr] evaluates expr, starting a fresh stack. This means that
during the evaluation of expr, the stack does not include anything outside the StackBegin . Functions
like TraceDialog[expr, ... ] call StackBegin before they begin evaluating expr, so that the stack
shows how expr is evaluated, but not how TraceDialog was called.
StackBegin[expr] uses a fresh stack in
the evaluation of expr.
Stack normally shows you only those expressions that are currently being evaluated. As a result,
it includes only the latest form of each expression. Sometimes, however, you may find it useful also
to see earlier forms of the expressions. You can do this using StackComplete .
What StackComplete[expr] effectively does is to keep on the stack the complete evaluation chain
for each expression that is currently being evaluated. In this case, the stack corresponds to the
sequence of expressions obtained from Trace with the option TraceBackward -> All as well as
TraceAbove -> True.
369
In[1]:= x = x + 1
In[2]:= ReleaseHold[%]
$RecursionLimit
$IterationLimit
The variables $RecursionLimit and $IterationLimit control the two basic ways that an evaluation can become infinite in Mathematica. $RecursionLimit limits the maximum depth of the evaluation
stack, or equivalently, the maximum nesting depth that would occur in the list structure produced
by Trace. $IterationLimit limits the maximum length of any particular evaluation chain, or the
maximum length of any single list in the structure produced by Trace.
$RecursionLimit and $IterationLimit are by default set to values that are appropriate for most
computations, and most computer systems. You can, however, reset these variables to any integer
(above a lower limit), or to Infinity . Note that on most computer systems, you should never set
$RecursionLimit = Infinity , as discussed on page 715.
This resets $RecursionLimit and
$IterationLimit to 20.
In[5]:= t = {t}
Out[4]= 20
370
In[7]:= fn[10]
$RecursionLimit::reclim: Recursion depth of 20 exceeded.
In[9]:= fm[0]
$IterationLimit::itlim: Iteration limit of 20 exceeded.
It is important to realize that infinite loops can take up not only time but also computer memory.
Computations limited by $IterationLimit do not normally build up large intermediate structures.
But those limited by $RecursionLimit often do. In many cases, the size of the structures produced is
a linear function of the value of $RecursionLimit . But in some cases, the size can grow exponentially,
or worse, with $RecursionLimit .
An assignment like x = x + 1 is obviously circular. When you set up more complicated recursive
definitions, however, it can be much more difficult to be sure that the recursion terminates, and that
you will not end up in an infinite loop. The main thing to check is that the right-hand sides of your
transformation rules will always be different from the left-hand sides. This ensures that evaluation will
always make progress, and Mathematica will not simply end up applying the same transformation
rule to the same expression over and over again.
Some of the trickiest cases occur when you have rules that depend on complicated /; conditions
(see Section 2.3.5). One particularly awkward case is when the condition involves a global variable.
Mathematica may think that the evaluation is finished because the expression did not change. However,
a side effect of some other operation could change the value of the global variable, and so should lead
to a new result in the evaluation. The best way to avoid this kind of difficulty is not to use global
variables in /; conditions. If all else fails, you can type Update[s] to tell Mathematica to update all
expressions involving s. Update[ ] tells Mathematica to update absolutely all expressions.
Interrupt[ ]
Abort[ ]
CheckAbort[expr, failexpr]
AbortProtect[expr]
371
interrupt a computation
abort a computation
evaluate expr and return the result, or failexpr if an abort
occurs
evaluate expr, masking the effect of aborts until the
evaluation is complete
The function Abort[ ] has the same effect as interrupting a computation, and selecting the abort
option in the interrupt menu.
You can use Abort[ ] to implement an emergency stop in a program. In almost all cases,
however, you should try to use functions like Return and Throw, which lead to more controlled
behavior.
Abort terminates the computation, so
only the first Print is executed.
If you abort at any point during the evaluation of a Mathematica expression, Mathematica normally
abandons the evaluation of the whole expression, and returns the value $Aborted .
You can, however, catch aborts using the function CheckAbort . If an abort occurs during the
evaluation of expr in CheckAbort[expr, failexpr], then CheckAbort returns failexpr, but the abort propagates no further. Functions like Dialog use CheckAbort in this way to contain the effect of aborts.
CheckAbort catches the abort, prints c
and returns the value aborted .
When you construct sophisticated programs in Mathematica, you may sometimes want to guarantee
that a particular section of code in a program cannot be aborted, either interactively or by calling
Abort. The function AbortProtect allows you to evaluate an expression, saving up any aborts until
after the evaluation of the expression is complete.
372
Even inside AbortProtect , CheckAbort will see any aborts that occur, and will return the appropriate failexpr. Unless this failexpr itself contains Abort[ ], the aborts will be absorbed by the
CheckAbort .
373
Compile is useful in situations where you have to evaluate a particular numerical or logical expression many times. By taking the time to call Compile, you can get a compiled function which can be
executed more quickly than an ordinary Mathematica function.
For simple expressions such as x Sin[x], there is usually little difference between the execution
speed for ordinary and compiled functions. However, as the size of the expressions involved increases,
the advantage of compilation also increases. For large expressions, compilation can speed up execution
by a factor as large as 20.
Compilation makes the biggest difference for expressions containing a large number of simple, say
arithmetic, functions. For more complicated functions, such as BesselK or Eigenvalues , most of the
computation time is spent executing internal Mathematica algorithms, on which compilation has no
effect.
This creates a compiled function for
finding values of the tenth Legendre
polynomial. The Evaluate tells
Mathematica to construct the polynomial
explicitly before doing compilation.
In[5]:= pc[0.4]
63
3465 x2
15015 x4
45045 x6
256
256
128
128
46189 x10
109395 x8
, CompiledCode
256
256
Out[5]= 0.0968391
Out[6]= 0.0968391
Even though you can use compilation to speed up numerical functions that you write, you should
still try to use built-in Mathematica functions whenever possible. Built-in functions will usually run
faster than any compiled Mathematica programs you can create. In addition, they typically use more
extensive algorithms, with more complete control over numerical precision and so on.
You should realize that built-in Mathematica functions quite often themselves use Compile. Thus, for
example, NIntegrate by default automatically uses Compile on the expression you tell it to integrate.
Similarly, functions like Plot and Plot3D use Compile on the expressions you ask them to plot.
Built-in functions that use Compile typically have the option Compiled. Setting Compiled -> False
tells the functions not to use Compile .
374
machine-size integer
machine-precision approximate real number
machine-precision approximate complex number
logical variable
Compile works by making assumptions about the types of objects that occur in evaluating the
expression you give. The default assumption is that all variables in the expression are approximate
real numbers.
Compile nevertheless also allows integers, complex numbers and logical variables (True or False),
as well as arrays of numbers. You can specify the type of a particular variable by giving a pattern
which matches only values that have that type. Thus, for example, you can use the pattern _Integer
to specify the integer type. Similarly, you can use True | False to specify a logical variable that must
be either True or False.
This compiles the expression 5 i + j
with the assumption that i and j are
integers.
In[8]:= %[8, 7]
Out[8]= 47
Out[10]= 30
375
The types that Compile handles correspond essentially to the types that computers typically handle
at a machine-code level. Thus, for example, Compile can handle approximate real numbers that have
machine precision, but it cannot handle arbitrary-precision numbers. In addition, if you specify that
a particular variable is an integer, Compile generates code only for the case when the integer is of
machine size, typically between M
.
When the expression you ask to compile involves only standard arithmetic and logical operations,
Compile can deduce the types of objects generated at every step simply from the types of the input
variables. However, if you call other functions, Compile will typically not know what type of value
they return. If you do not specify otherwise, Compile assumes that any other function yields an
approximate real number value. You can, however, also give an explicit list of patterns, specifying
what type to assume for an expression that matches a particular pattern.
This defines a function which yields an
integer result when given an integer
argument.
In[13]:= %[5.6, 1]
Out[13]= 31.36
The idea of Compile is to create a function which is optimized for certain types of arguments.
Compile is nevertheless set up so that the functions it creates work with whatever types of arguments
they are given. When the optimization cannot be used, a standard Mathematica expression is evaluated
to find the value of the function.
Here is a compiled function for taking
the square root of a variable.
In[15]:= sq[4.5]
In[16]:= sq[1 + u]
Out[15]= 2.12132
CompiledFunction::cfsa:
Argument 1 + u at position 1 should be a
machine-size real number.
Out[16]=
1u
The compiled code generated by Compile must make assumptions not only about the types of
arguments you will supply, but also about the types of all objects that arise during the execution of
the code. Sometimes these types depend on the actual values of the arguments you specify. Thus, for
example, Sqrt[x] yields a real number result for real x if x is not negative, but yields a complex
number if x is negative.
376
Compile always makes a definite assumption about the type returned by a particular function. If
this assumption turns out to be invalid in a particular case when the code generated by Compile is
executed, then Mathematica simply abandons the compiled code in this case, and evaluates an ordinary
Mathematica expression to get the result.
The compiled code does not expect a
complex number, so Mathematica has to
revert to explicitly evaluating the
original symbolic expression.
In[17]:= sq[-4.5]
CompiledFunction::cfn:
Numerical error encountered at instruction 2;
proceeding with uncompiled evaluation.
Out[17]= 0. 2.12132
An important feature of Compile is that it can handle not only mathematical expressions, but
also various simple Mathematica programs. Thus, for example, Compile can handle conditionals and
control flow structures.
In all cases, Compile[vars, expr] holds its arguments unevaluated. This means that you can explicitly give a program as the expression to compile.
This creates a compiled version of a
Mathematica program which implements
Newtons approximation to square
roots.
1
x
Modulet, t = x; Dot = t , n; t,
2
t
CompiledCode
This executes the compiled code.
In[19]:= newt[2.4, 6]
Out[19]= 1.54919
377
The instruction stream in a CompiledFunction object consists of a list of instructions for a simple
idealized computer. The computer is assumed to have numbered registers, on which operations
can be performed. There are five basic types of registers: logical, integer, real, complex and tensor.
For each of these basic types it is then possible to have either a single scalar register or an array
of registers of any rank. A list of the total number of registers of each type required to evaluate a
particular CompiledFunction object is given as the second element of the object.
The actual instructions in the compiled code object are given as lists. The first element is an integer
opcode which specifies what operation should be performed. Subsequent elements are either the
numbers of registers of particular types, or literal constants. Typically the last element of the list is
the number of a destination register, into which the result of the operation should be put.
378
In[1]:= t = 17
In[3]:= t
Out[1]= 17
Out[3]= 17
The most common way that modules are used is to set up temporary or intermediate variables
inside functions you define. It is important to make sure that such variables are kept local. If they
are not, then you will run into trouble whenever their names happen to coincide with the names of
other variables.
The intermediate variable t is specified
to be local to the module.
In[5]:= f[a + b]
Out[5]= 1 2 a a2 2 b 2 a b b2
In[6]:= t
Out[6]= 17
You can treat local variables in modules just like other symbols. Thus, for example, you can use
them as names for local functions, you can assign attributes to them, and so on.
379
In[7]:= gfac10[k_] :=
Module[{f, n}, f[1] = 1; f[n_] := k + n f[n-1]; f[10]]
In[8]:= gfac10[0]
In[9]:= gfac10[2]
Out[8]= 3628800
Out[9]= 8841802
When you set up a local variable in a module, Mathematica initially assigns no value to the variable.
This means that you can use the variable in a purely symbolic way, even if there was a global value
defined for the variable outside the module.
This uses the global value of t defined
above, and so yields a number.
Out[10]= 5832
Out[11]= 0
Out[12]= 4
In[14]:= g[a]
a
Out[14]= a
1a
You can define initial values for any of the local variables in a module. The initial values are always
evaluated before the module is executed. As a result, even if a variable x is defined as local to the
module, the global x will be used if it appears in an expression for an initial value.
The initial value of u is taken to be the
global value of t.
380
When you set up /; conditions for definitions, you often need to introduce temporary variables.
In many cases, you may want to share these temporary variables with the body of the right-hand side
of the definition. Mathematica allows you to enclose the whole right-hand side of your definition in a
module, including the condition.
This defines a function with a
condition attached.
In[17]:= h[10]
Out[17]= 35
Module allows you to set up local variables, to which you can assign any sequence of values. Often, however, all you really need are local constants, to which you assign a value only once. The
Mathematica With construct allows you to set up such local constants.
This defines a global value for t.
In[1]:= t = 17
Out[1]= 17
In[3]:= w[a]
3
Out[3]= 1 a 1 a
In[4]:= t
Out[4]= 17
Just as in Module, the initial values you define in With are evaluated before the With is executed.
The expression t + 1 which gives the
value of the local constant t is
evaluated using the global t.
The way With[{x = x , ... }, body] works is to take body, and replace every occurrence of x, etc.
in it by x , etc. You can think of With as a generalization of the /. operator, suitable for application
to Mathematica code instead of other expressions.
This replaces x with a.
381
In[7]:= a
In[8]:= Clear[a]
Out[7]= 5
In some respects, With is like a special case of Module, in which each local variable is assigned a
value exactly once.
One of the main reasons for using With rather than Module is that it typically makes the Mathematica
programs you write easier to understand. In a module, if you see a local variable x at a particular
point, you potentially have to trace through all of the code in the module to work out the value of
x at that point. In a With construct, however, you can always find out the value of a local constant
simply by looking at the initial list of values, without having to trace through specific code.
If you have several With constructs, it is always the innermost one for a particular variable that is
in effect. You can mix Module and With. The general rule is that the innermost one for a particular
variable is the one that is in effect.
With nested With constructs, the
innermost one is always the one in
effect.
Out[9]= 81
Out[10]= 81
Out[11]= a b
Except for the question of when x and body are evaluated, With[{x = x }, body] works essentially
like body /. x -> x . However, With behaves in a special way when the expression body itself contains
With or Module constructs. The main issue is to prevent the local constants in the various With
constructs from conflicting with each other, or with global objects. The details of how this is done are
discussed in Section 2.7.3.
The y in the inner With is renamed to
prevent it from conflicting with the
global y.
382
Module generates symbols with names of the form x$nnn to represent each local variable.
The basic principle of modules in Mathematica.
t$1
t$2
u$2
For most purposes, you will never have to deal directly with the actual symbols generated inside
modules. However, if for example you start up a dialog while a module is being executed, then
you will see these symbols. The same is true whenever you use functions like Trace to watch the
evaluation of modules.
You see the symbols that are generated
inside modules when you use Trace.
In[5]:= Stack[_]
In[6]:= t$4 + 1
Out[6]= 7
In[7]:= Return[t$4 ^ 2]
Out[4]= 36
Under some circumstances, it is convenient explicitly to return symbols that are generated inside
modules.
You can explicitly return symbols that
are generated inside modules.
In[5]:= Module[{t}, t]
In[6]:= %^2 + 1
Unique[x]
Unique[{x, y, ... }]
Generating new symbols with unique names.
Out[5]= t$6
Out[6]= 1 t$6
383
The function Unique allows you to generate new symbols in the same way as Module does.
Each time you call Unique, $ModuleNumber is incremented, so that the names of new symbols are
guaranteed to be unique.
This generates a unique new symbol
whose name starts with x.
In[7]:= Unique[x]
Out[7]= x$7
You can use the standard Mathematica ?name mechanism to get information on symbols that were
generated inside modules or by the function Unique.
Executing this module generates the
symbol q$nnn.
In[11]:= ?q*
Out[10]= 1 q$12
q$12
Symbols generated by Module behave in exactly the same way as other symbols for the purposes of
evaluation. However, these symbols carry the attribute Temporary , which specifies that they should
be removed completely from the system when they are no longer used. Thus most symbols that are
generated inside modules are removed when the execution of those modules is finished. The symbols
survive only if they are explicitly returned.
This shows a new q variable generated
inside a module.
In[13]:= ?q*
q$13
q$12
You should realize that the use of names such as x$nnn for generated symbols is purely a convention. You can in principle give any symbol a name of this form. But if you do, the symbol may
collide with one that is produced by Module.
An important point to note is that symbols generated by Module are in general unique only within
a particular Mathematica session. The variable $ModuleNumber which determines the serial numbers
for these symbols is always reset at the beginning of each session.
This means in particular that if you save expressions containing generated symbols in a file, and
then read them into another session, there is no guarantee that conflicts will not occur.
One way to avoid such conflicts is explicitly to set $ModuleNumber differently at the beginning
of each session. In particular, if you set $ModuleNumber = 10^10 $SessionID , you should avoid any
conflicts. The global variable $SessionID should give a unique number which characterizes a partic-
384
ular Mathematica session on a particular computer. The value of this variable is determined from such
quantities as the absolute date and time, the ID of your computer, and, if appropriate, the ID of the
particular Mathematica process.
$ModuleNumber
$SessionID
Having generated appropriate symbols to represent the local variables you have specified,
Module[vars, body] then has to evaluate body using these symbols. The first step is to take the actual
expression body as it appears inside the module, and effectively to use With to replace all occurrences
of each local variable name with the appropriate generated symbol. After this is done, Module actually
performs the evaluation of the resulting expression.
An important point to note is that Module[vars, body] inserts generated symbols only into the
actual expression body. It does not, for example, insert such symbols into code that is called from
body, but does not explicitly appear in body.
Section 2.7.6 will discuss how you can use Block to set up local values which work in a different
way.
Since x does not appear explicitly in
the body of the module, the local value
is not used.
Most of the time, you will probably set up modules by giving explicit Mathematica input of the
form Module[vars, body]. Since the function Module has the attribute HoldAll, the form of body will
usually be kept unevaluated until the module is executed.
It is, however, possible to build modules dynamically in Mathematica. The generation of new symbols, and their insertion into body are always done only when a module is actually executed, not when
the module is first given as Mathematica input.
This evaluates the body of the module
immediately, making x appear
explicitly.
385
In[2]:= %[2y]
In[3]:= %[a]
Out[3]= a 2 y
In general, Mathematica renames the formal parameters in an object like Function[vars, body]
whenever body is modified in any way by the action of another pure function.
The formal parameter y is renamed
because the body of the inner pure
function was changed.
Mathematica renames formal parameters in pure functions more liberally than is strictly necessary.
In principle, renaming could be avoided if the names of the formal parameters in a particular function
do not actually conflict with parts of expressions substituted into the body of the pure function. For
uniformity, however, Mathematica still renames formal parameters even in such cases.
In this case, the formal parameter x in
the inner function shields the body of
the function, so no renaming is needed.
In[8]:= %[a]
Out[8]= Function
y$, Function
z$, a y$ z$
386
As mentioned on page 249, pure functions in Mathematica are like expressions in formal logic.
The renaming of formal parameters allows Mathematica pure functions to reproduce all the semantics
of standard expressions faithfully.
local parameters
local constants
local variables
Mathematica has several scoping constructs in which certain names are treated as local. When
you mix these constructs in any way, Mathematica does appropriate renamings to avoid conflicts.
Mathematica renames the formal
parameter of the pure function to
avoid a conflict.
In[13]:= ReleaseHold[%]
Out[13]= y y$1
Mathematica treats transformation rules as scoping constructs, in which the names you give to
patterns are local. You can set up named patterns either using x_, x__ and so on, or using x:patt.
The x in the h goes with the x_, and is
considered local to the rule.
In a rule like f[x_] -> x + y, the x which appears on the right-hand side goes with the name of
the x_ pattern. As a result, this x is treated as a variable local to the rule, and cannot be modified by
other scoping constructs.
The y, on the other hand, is not local to the rule, and can be modified by other scoping constructs.
When this happens, Mathematica renames the patterns in the rule to prevent the possibility of a conflict.
387
When you use With on a scoping construct, Mathematica automatically performs appropriate renamings. In some cases, however, you may want to make substitutions inside scoping constructs, without
any renaming. You can do this using the /. operator.
When you substitute for y using With,
the x in the pure function is renamed
to prevent a conflict.
When you apply a rule such as f [x_] -> rhs, or use a definition such as f [x_] := rhs, Mathematica
implicitly has to substitute for x everywhere in the expression rhs. It effectively does this using the
/. operator. As a result, such substitution does not respect scoping constructs. However, when the
insides of a scoping construct are modified by the substitution, the other variables in the scoping
construct are renamed.
This defines a function for creating
pure functions.
388
In[2]:= p[s + 1]
1
In[4]:= pm[s + 1]
1
1s
Out[4]= s$242
f s$2427 s$242
In many cases, the most important issue is that dummy variables should be kept local, and should
not interfere with other variables in your mathematical expression. In some cases, however, what is
instead important is that different uses of the same dummy variable should not conflict.
Repeated dummy variables often appear in products of vectors and tensors. With the summation
convention, any vector or tensor index that appears exactly twice is summed over all its possible
values. The actual name of the repeated index never matters, but if there are two separate repeated
indices, it is essential that their names do not conflict.
This sets up the repeated index j as a
dummy variable.
There are many situations in mathematics where you need to have variables with unique names.
One example is in representing solutions to equations. With an equation like sinx , there are
an infinite number of solutions, each of the form x n, where n is a dummy variable that can be
equal to any integer. If you generate solutions to the equation on two separate occasions, there is no
guarantee that the value of n should be the same in both cases. As a result, you must set up the
solution so that the object n is different every time.
This defines a value for sinsol, with n
as a dummy variable.
Another place where unique objects are needed is in representing constants of integration. When
you do an integral, you are effectively solving an equation for a derivative. In general, there are
many possible solutions to the equation, differing by additive constants of integration. The standard
Mathematica Integrate function always returns a solution with no constant of integration. But if you
were to introduce constants of integration, you would need to use modules to make sure that they
are always unique.
389
In[1]:= x^2 + 3
Out[1]= 3 x2
In[3]:= x
Out[2]= 3 1 a
Out[3]= x
As described in the sections above, the variable x in a module such as Module[{x}, body] is always
set up to refer to a unique symbol, different each time the module is used, and distinct from the global
symbol x. The x in a block such as Block[{x}, body] is, however, taken to be the global symbol x.
What the block does is to make the value of x local. The value x had when you entered the block is
always restored when you exit the block. And during the execution of the block, x can take on any
value.
This sets the symbol t to have
value 17.
In[4]:= t = 17
In[8]:= t
Out[4]= 17
t$1
Out[7]= 1297
Out[8]= 17
Blocks in Mathematica effectively allow you to set up environments in which you can temporarily
change the values of variables. Expressions you evaluate at any point during the execution of a block
will use the values currently defined for variables in the block. This is true whether the expressions
appear directly as part of the body of the block, or are produced at any point in its evaluation.
390
In[10]:= u
Out[10]= 289 x2
Out[11]= 32 x2
An important implicit use of Block in Mathematica is for iteration constructs such as Do, Sum and
Table. Mathematica effectively uses Block to set up local values for the iteration variables in all of
these constructs.
Sum automatically makes the value of
the iterator t local.
Out[12]= 385
Out[13]= 385
When you set up functions in Mathematica, it is sometimes convenient to have global variables
which can affect the functions without being given explicitly as arguments. Thus, for example, Mathematica itself has a global variable $RecursionLimit which affects the evaluation of all functions, but
is never explicitly given as an argument.
Mathematica will usually keep any value you define for a global variable until you explicitly change
it. Often, however, you want to set up values which last only for the duration of a particular computation, or part of a computation. You can do this by making the values local to a Mathematica
block.
This defines a function which depends
on the global variable t.
In[15]:= f[a]
Out[15]= 17 a2
Out[16]= 2 b2
You can use global variables not only to set parameters in functions, but also to accumulate results
from functions. By setting up such variables to be local to a block, you can arrange to accumulate
results only from functions called during the execution of the block.
This function increments the global
variable t, and returns its current
value.
391
In[18]:= h[a]
In[20]:= t
Out[18]= 17 a2
Out[19]= c2
Out[20]= 17 a2
When you enter a block such as Block[{x}, body], any value for x is removed. This means that
you can in principle treat x as a symbolic variable inside the block. However, if you explicitly return
x from the block, it will be replaced by its value outside the block as soon as it is evaluated.
The value of t is removed when you
enter the block.
2
1 + 2 t + t
Out[22]= 3 17 a2
Module[vars, body]
Block[vars, body]
lexical scoping
dynamic scoping
Most traditional computer languages use a so-called lexical scoping mechanism for variables,
which is analogous to the module mechanism in Mathematica. Some symbolic computer languages
such as LISP also allow dynamic scoping, analogous to Mathematica blocks.
392
When lexical scoping is used, variables are treated as local to a particular section of the code in a
program. In dynamic scoping, the values of variables are local to a part of the execution history of the
program.
In compiled languages like C and Java, there is a very clear distinction between code and execution history. The symbolic nature of Mathematica makes this distinction slightly less clear, since
code can in principle be built up dynamically during the execution of a program.
What Module[vars, body] does is to treat the form of the expression body at the time when the
module is executed as the code of a Mathematica program. Then when any of the vars explicitly
appears in this code, it is considered to be local.
Block[vars, body] does not look at the form of the expression body. Instead, throughout the evaluation of body, the block uses local values for the vars.
This defines m in terms of i.
In[1]:= m = i^2
Out[1]= i2
2.7.8 Contexts
It is always a good idea to give variables and functions names that are as explicit as possible.
Sometimes, however, such names may get inconveniently long.
In Mathematica, you can use the notion of contexts to organize the names of symbols. Contexts
are particularly important in Mathematica packages which introduce symbols whose names must not
conflict with those of any other symbols. If you write Mathematica packages, or make sophisticated
use of packages that others have written, then you will need to know about contexts.
The basic idea is that the full name of any symbol is broken into two parts: a context and a short
name. The full name is written as context`short, where the ` is the backquote or grave accent character
(ASCII decimal code 96), called a context mark in Mathematica.
Here is a symbol with short name x,
and context aaaa.
In[1]:= aaaa`x
In[2]:= %^2 - %
In[3]:= aaaa`x = 78
Out[1]= aaaa`x
Out[3]= 78
2.7.8 Contexts
393
It is typical to have all the symbols that relate a particular topic in a particular context. Thus, for
example, symbols that represent physical units might have a context PhysicalUnits` . Such symbols
might have full names like PhysicalUnits`Joule or PhysicalUnits`Mole .
Although you can always refer to a symbol by its full name, it is often convenient to use a shorter
name.
At any given point in a Mathematica session, there is always a current context $Context . You can
refer to symbols that are in this context simply by giving their short names.
The default context for Mathematica
sessions is Global` .
In[5]:= $Context
Out[5]= Global`
Out[6]= x, x
Contexts in Mathematica work somewhat like file directories in many operating systems. You can
always specify a particular file by giving its complete name, including its directory. But at any given
point, there is usually a current working directory, analogous to the current Mathematica context. Files
that are in this directory can then be specified just by giving their short names.
Like directories in many operating systems, contexts in Mathematica can be hierarchical. Thus, for
example, the full name of a symbol can involve a sequence of context names, as in c `c `c
`name.
`name
`context`name or `c `c ` ... `name
name
In[7]:= a`b`x
Out[7]= a`b`x
When you start a Mathematica session, the default current context is Global` . Symbols that you
introduce will usually be in this context. However, built-in symbols such as Pi are in the context
System` .
394
In order to let you easily access not only symbols in the context Global`, but also in contexts such
as System`, Mathematica supports the notion of a context search path. At any point in a Mathematica session, there is both a current context $Context , and also a current context search path $ContextPath .
The idea of the search path is to allow you to type in the short name of a symbol, then have
Mathematica search in a sequence of contexts to find a symbol with that short name.
The context search path for symbols in Mathematica is analogous to the search path for program
files provided in operating systems such as Unix and MS-DOS.
The default context path includes the
contexts for system-defined symbols.
In[8]:= $ContextPath
In[9]:= Context[Pi]
Context[s]
$Context
$ContextPath
Contexts[ ]
Out[9]= System`
When you use contexts in Mathematica, there is no reason that two symbols which are in different
contexts cannot have the same short name. Thus, for example, you can have symbols with the short
name Mole both in the context PhysicalUnits` and in the context BiologicalOrganisms` .
There is, however, then the question of which symbol you actually get when you type in only the
short name Mole. The answer to this question is determined by which of the contexts comes first in
the sequence of contexts listed in the context search path.
This introduces two symbols, both with
short name Mole.
In[11]:= $ContextPath =
Join[$ContextPath,
{"PhysicalUnits`", "BiologicalOrganisms`"}]
In[12]:= Context[Mole]
Out[12]= PhysicalUnits`
In general, when you type in a short name for a symbol, Mathematica assumes that you want the
symbol with that name whose context appears earliest in the context search path. As a result, symbols
2.7.8 Contexts
395
with the same short name whose contexts appear later in the context search path are effectively
shadowed. To refer to these symbols, you need to use their full names.
Mathematica always warns you when you introduce new symbols that shadow existing symbols with your current choice for $ContextPath . If you use a notebook front end, Mathematica will
typically let you select in such cases which symbol you want to keep.
This introduces a symbol with short
name Mole in the context Global` .
Mathematica warns you that the new
symbol shadows existing symbols with
short name Mole.
In[13]:= Global`Mole
Mole::shdw:
Symbol Mole appears in multiple contexts
{Global`, P<<11>>s`, BiologicalOrganisms`}
; definitions in context Global`
may shadow or be shadowed by other definitions.
Out[13]= Mole
In[14]:= Context[Mole]
Out[14]= Global`
If you once introduce a symbol which shadows existing symbols, it will continue to do so until
you either rearrange $ContextPath , or explicitly remove the symbol. You should realize that it is not
sufficient to clear the value of the symbol; you need to actually remove the symbol completely from
Mathematica. You can do this using the function Remove[s] .
Clear[s]
Remove[s]
In[15]:= Remove[Mole]
In[16]:= Context[Mole]
Out[16]= PhysicalUnits`
When Mathematica prints out the name of a symbol, it has to choose whether to give the full name,
or just the short name. What it does is to give whatever version of the name you would have to type
in to get the particular symbol, given your current settings for $Context and $ContextPath .
The short name is printed for the first
symbol, so this would give that symbol
if you typed it in.
If you type in a short name for which there is no symbol either in the current context, or in any
context on the context search path, then Mathematica has to create a new symbol with this name. It
always puts new symbols of this kind in the current context, as specified by $Context.
This introduces the new symbol with
short name tree.
In[18]:= tree
Out[18]= tree
396
In[19]:= Context[tree]
Out[19]= Global`
In[1]:= <<Calculus`Pade`
In[2]:= $ContextPath
In[3]:= Context[Pade]
Out[3]= Calculus`Pade`
x
1 x3
30
Out[4]=
2x
x2
x3
x4
1
3
5
30
360
The full names of symbols defined in packages are often quite long. In most cases, however, you
will only need to use their short names. The reason for this is that after you have read in a package,
its context is added to $ContextPath , so the context is automatically searched whenever you type in
a short name.
There is a complication, however, when two symbols with the same short name appear in two
different packages. In such a case, Mathematica will warn you when you read in the second package.
It will tell you which symbols will be shadowed by the new symbols that are being introduced.
The symbol Pade in the context
Calculus`Pade` is shadowed by the
symbol with the same short name in
the new package.
In[5]:= <<NewPade`
Pade::shdw:
Symbol Pade appears in multiple contexts
{NewPade`, Calculus`Pade`}; definitions in context
NewPade` may shadow or be shadowed by other
definitions.
x
1 x3
30
Out[6]=
2x
x2
x3
x4
1
3
5
30
360
397
Conflicts can occur not only between symbols in different packages, but also between symbols in
packages and symbols that you introduce directly in your Mathematica session. If you define a symbol
in your current context, then this symbol will shadow any other symbol with the same short name in
packages that you read in. The reason for this is that Mathematica always searches for symbols in the
current context before looking in contexts on the context search path.
This defines a function in the current
context.
In[8]:= <<Calculus`VectorAnalysis`
1
Out[7]=
f
Out[9]= Cartesian x, y, z
Out[11]= 1 2 y
If you get into the situation where unwanted symbols are shadowing the symbols you want, the
best thing to do is usually to get rid of the unwanted symbols using Remove[s] . An alternative that is
sometimes appropriate is to rearrange the entries in $ContextPath and to reset the value of $Context
so as to make the contexts that contain the symbols you want be the ones that are searched first.
$Packages
398
Symbols that are not intended for export, but are instead intended only for internal use within the
package, are conventionally put into a context with the name Package`Private`. This context is not
added to the context search path. As a result, the symbols in this context cannot be accessed except
by giving their full names.
Package`
Package`Private`
System`
Needed `, Needed `, ...
There is a standard sequence of Mathematica commands that is typically used to set up the contexts
in a package. These commands set the values of $Context and $ContextPath so that the new symbols
which are introduced are created in the appropriate contexts.
BeginPackage["Package`"]
Begin["`Private`"]
End[ ]
EndPackage[ ]
399
BeginPackage["Collatz`"]
Collatz::usage =
"Collatz[n] gives a list of the iterates in the 3n+1 problem,
starting from n. The conjecture is that this sequence always
terminates."
Begin["`Private`"]
Collatz[1] := {1}
Collatz[n_Integer] := Prepend[Collatz[3 n + 1], n] /; OddQ[n] && n > 0
Collatz[n_Integer] := Prepend[Collatz[n/2], n] /; EvenQ[n] && n > 0
End[ ]
EndPackage[ ]
The sample package Collatz.m.
Defining usage messages at the beginning of a package is the standard way of making sure that
symbols you want to export are created in the appropriate context. The way this works is that in
defining these messages, the only symbols you mention are exactly the ones you want to export.
These symbols are then created in the context Package`, which is then current.
In the actual definitions of the functions in a package, there are typically many new symbols,
introduced as parameters, temporary variables, and so on. The convention is to put all these symbols
in the context Package`Private`, which is not put on the context search path when the package is
read in.
This reads in the sample package given
above.
In[1]:= <<Collatz.m
In[2]:= $ContextPath
In[3]:= Context[Collatz]
In[4]:= ?Collatz`Private`*
Out[3]= Collatz`
Collatz`Private`n
In the Collatz package, the functions that are defined depend only on built-in Mathematica functions. Often, however, the functions defined in one package may depend on functions defined in
another package.
400
Two things are needed to make this work. First, the other package must be read in, so that the
functions needed are defined. And second, the context search path must include the context that these
functions are in.
You can explicitly tell Mathematica to read in a package at any point using the command <<context`.
(Section 2.12.5 discusses the tricky issue of translation from system-independent context names to
system-dependent file names.) Often, however, you want to set it up so that a particular package is
read in only if it is needed. The command Needs["context`"] tells Mathematica to read in a package
if the context associated with that package is not already in the list $Packages .
Get["context`"] or <<context`
Needs["context`"]
If you use BeginPackage["Package`"] with a single argument, Mathematica puts on the context
search path only the Package` context and the contexts for built-in Mathematica symbols. If the definitions you give in your package involve functions from other packages, you must make sure that the
contexts for these packages are also included in your context search path. You can do this by giving
a list of the additional contexts as a second argument to BeginPackage . BeginPackage automatically
calls Needs on these contexts, reading in the corresponding packages if necessary, and then making
sure that the contexts are on the context search path.
Begin["context`"]
End[ ]
Executing a function like Begin which manipulates contexts changes the way that Mathematica
interprets names you type in. However, you should realize that the change is effective only in subsequent expressions that you type in. The point is that Mathematica always reads in a complete input
expression, and interprets the names in it, before it executes any part of the expression. As a result,
by the time Begin is executed in a particular expression, the names in the expression have already
been interpreted, and it is too late for Begin to have an effect.
401
The fact that context manipulation functions do not have an effect until the next complete expression
is read in means that you must be sure to give those functions as separate expressions, typically on
separate lines, when you write Mathematica packages.
The name x is interpreted before this
expression is executed, so the Begin
has no effect.
Context manipulation functions are used primarily as part of packages intended to be read into
Mathematica. Sometimes, however, you may find it convenient to use such functions interactively.
This can happen, for example, if you go into a dialog, say using TraceDialog , while executing a
function defined in a package. The parameters and temporary variables in the function are typically
in a private context associated with the package. Since this context is not on your context search path,
Mathematica will print out the full names of the symbols, and will require you to type in these full
names in order to refer to the symbols. You can however use Begin["Package`Private`"] to make
the private context of the package your current context. This will make Mathematica print out short
names for the symbols, and allow you to refer to the symbols by their short names.
In[1]:= DeclarePackage["Calculus`VectorAnalysis`",
{"Div", "Grad", "Curl"}]
Out[1]= Calculus`VectorAnalysis`
Out[2]= 2 x, 2 y, 0
402
When you set up a large collection of Mathematica packages, it is often a good idea to create an
additional names file which contains a sequence of DeclarePackage commands, specifying packages
to load when particular names are used. Within a particular Mathematica session, you then need to
load explicitly only the names file. When you have done this, all the other packages will automatically
be loaded if and when they are needed.
DeclarePackage works by immediately creating symbols with the names you specify, but giving
each of these symbols the special attribute Stub. Whenever Mathematica finds a symbol with the Stub
attribute, it automatically loads the package corresponding to the context of the symbol, in an attempt
to find the definition of the symbol.
In[1]:= x // InputForm
Out[1]//InputForm= x
Once you have made an assignment such as x = 2, then whenever x is evaluated, it is replaced by 2.
Sometimes, however, you may want to continue to refer to x itself, without immediately getting the
value of x.
You can do this by referring to x by name. The name of the symbol x is the string "x", and even
though x itself may be replaced by a value, the string "x" will always stay the same.
The names of the symbols x and xp
are the strings "x" and "xp".
In[5]:= x = 2
Out[5]= 2
403
In[7]:= t // InputForm
Out[7]//InputForm= InputForm[{"x", "xp"}]
NameQ["form"]
Names["form"]
Contexts["form`"]
You can specify the form of symbol names using string patterns of the kind discussed on page 411.
"x*" stands, for example, for all names that start with x.
This gives a list of all symbol names in
this Mathematica session that begin
with x.
Clear["form"]
Clear["context`*"]
Remove["form"]
Remove["context`*"]
In[12]:= Clear["x*"]
In[13]:= Names["x*"]
Out[13]= x, xp, x$
404
In[15]:= Remove["x*"]
In[16]:= Names["x*"]
Out[16]=
Remove["Global`*"]
If you do not set up any additional contexts, then all the symbols that you introduce in a Mathematica session will be placed in the Global` context. You can remove these symbols completely using
Remove["Global`*"] . Built-in Mathematica objects are in the System` context, and are thus unaffected
by this.
On[General::newsym]
Off[General::newsym]
In[1]:= On[General::newsym]
In[2]:= sin[k]
General::newsym: Symbol sin is new.
General::newsym: Symbol k is new.
Out[2]= sin k
In[3]:= Off[General::newsym]
Generating a message when Mathematica creates a new symbol is often a good way to catch typing
mistakes. Mathematica itself cannot tell the difference between an intentionally new name, and a
405
misspelling of a name it already knows. But by reporting all new names it encounters, Mathematica
allows you to see whether any of them are mistakes.
$NewSymbol
When Mathematica creates a new symbol, you may want it not just to print a message, but instead to perform some other action. Any function you specify as the value of the global variable
$NewSymbol will automatically be applied to strings giving the name and context of each new symbol
that Mathematica creates.
This defines a function to be applied to
each new symbol which is created.
In[5]:= v + w
Name: v
Name: w
Context: Global`
Context: Global`
Out[5]= v w
406
"text"
Text strings.
When you input a string of text to Mathematica you must always enclose it in quotes. However,
when Mathematica outputs the string it usually does not explicitly show the quotes.
You can see the quotes by asking for the input form of the string. In addition, in a Mathematica
notebook, quotes will typically appear automatically as soon as you start to edit a string.
When Mathematica outputs a string, it
usually does not explicitly show the
quotes.
In[2]:= InputForm[%]
The fact that Mathematica does not usually show explicit quotes around strings makes it possible
for you to use strings to specify quite directly the textual output you want.
The strings are printed out here
without explicit quotes.
You should understand, however, that even though the string "x" often appears as x in output, it
is still a quite different object from the symbol x.
The string "x" is not the same as the
symbol x.
You can test whether any particular expression is a string by looking at its head. The head of any
string is always String.
All strings have head String.
In[5]:= Head["x"]
Out[5]= String
407
You can use strings just like other expressions as elements of patterns and transformations. Note,
however, that you cannot assign values directly to strings.
This gives a definition for an
expression that involves a string.
In[7]:= z["gold"] = 79
Out[7]= 79
or StringJoin[{s , s , ... }]
join several strings together
StringLength[s]
StringReverse[s]
In[2]:= StringLength[%]
StringTake[s, n]
StringTake[s, {n}]
StringTake[s, {n , n }]
StringDrop[s, n]
StringDrop[s, {n , n }]
Taking and dropping substrings.
Out[1]= aaaaaaabbbcccccccccc
Out[2]= 20
Out[3]= .gnirts A
408
StringTake and StringDrop are the analogs for strings of Take and Drop for lists. Like Take and
Drop, they use standard Mathematica sequence specifications, so that, for example, negative numbers
count character positions from the end of a string. Note that the first character of a string is taken to
have position 1.
Here is a sample string.
In[5]:= StringTake[alpha, 5]
Out[5]= ABCDE
Out[6]= E
StringInsert[s, snew, n]
StringInsert[s, snew, n] is set up to produce a string whose nth character is the first character
of snew.
This produces a new string whose
fourth character is the first character of
the string "XX".
Out[8]= abcXXdefgh
Out[9]= abcdefghXXX
Out[10]= aXXXbcXXXdefghXXX
409
Out[11]= aXXXgh
Out[12]= aXXXdXXX
Out[13]= aXXXdYYYY
StringPosition[s, sub]
StringPosition[s, sub, k]
You can use StringPosition to find where a particular substring appears within a given string.
StringPosition returns a list, each of whose elements corresponds to an occurrence of the substring. The elements consist of lists giving the starting and ending character positions for the substring. These lists are in the form used as sequence specifications in StringTake , StringDrop and
StringReplacePart .
This gives a list of the positions of the
substring "abc".
410
StringReplace allows you to perform replacements for substrings within a string. StringReplace
sequentially goes through a string, testing substrings that start at each successive character position.
To each substring, it tries in turn each of the transformation rules you have specified. If any of the
rules apply, it replaces the substring, then continues to go through the string, starting at the character
position after the end of the substring.
This replaces all occurrences of the
character a by the string XX.
In[18]:= StringReplace["abcdabcdaabcabcd",
{"abc" -> "Y", "d" -> "XXX"}]
Out[17]= XXbcdXXbcdXXXXbcXXbcd
Out[18]= YXXXYXXXaYYXXX
Sort[{s , s , s , ... }]
411
Sorting strings.
Matching strings.
The character * can be used in a string pattern as a metacharacter to stand for any sequence of
alphanumeric characters. Thus, for example, the string pattern "a*b" would match any string which
begins with an a, ends with a b, and has any number of alphanumeric characters in between. Similarly,
"a*b*" would match any string that starts with a, and has any number of other characters, including
at least one b.
The string matches the string pattern
you have given.
The way * is used in Mathematica string patterns is analogous to the way it is used for filename patterns in many operating systems. Mathematica however provides some other string pattern
metacharacters that are tailored to matching different classes of Mathematica symbol names.
412
\* etc.
literal * etc.
In Mathematica there is a general convention that only built-in names should contain upper-case
characters. Assuming that you follow this convention, you can use @ as a metacharacter to set up
string patterns which match names you have defined, but avoid matching built-in names.
413
In[2]:= RotateLeft[%, 3]
In[3]:= StringJoin[%]
Out[2]= t, r, i, n, g, ., A, , s
Out[3]= tring.A s
DigitQ[string]
LetterQ[string]
UpperCaseQ[string]
LowerCaseQ[string]
In[4]:= LetterQ["Mixed"]
In[5]:= UpperCaseQ["Mixed"]
Out[4]= True
Out[5]= False
ToUpperCase[string]
ToLowerCase[string]
Out[7]= a, b, c, d, e, f, g, h
Out[8]= T, U, V, W, X, Y, Z
414
CharacterRange will usually give meaningful results for any range of characters that have a natural
ordering. The way CharacterRange works is by using the character codes that Mathematica internally
assigns to every character.
This shows the ordering defined by the
internal character codes used by
Mathematica.
In[1]:= ""
Out[1]= OO
In[2]:= StringReplace[%, "" -> " "]
Out[2]=
In[3]:= Characters[%]
Out[3]= , , , , , , , , , ,
In a Mathematica notebook, a special character such as can always be displayed directly. But if
you use a text-based interface, then typically the only characters that can readily be displayed are the
ones that appear on your keyboard.
As a result, what Mathematica does in such situations is to try to approximate special characters
by similar-looking sequences of ordinary characters. And when this is not practical, Mathematica just
gives the full name of the special character.
In a Mathematica notebook using
StandardForm , special characters can
be displayed directly.
In OutputForm , however, the special
characters are approximated when
possible by sequences of ordinary ones.
Mathematica always uses full names for special characters in InputForm . This means that when
special characters are written out to files or external programs, they are by default represented purely
as sequences of ordinary characters.
This uniform representation is crucial in allowing special characters in Mathematica to be used in a
way that does not depend on the details of particular computer systems.
In InputForm the full names of all
special characters are always written
out explicitly.
\[Name]
415
a literal character
a character specified using its full name
\"
\\
a \ to be included in a string
In[9]:= Characters[%]
Out[8]= \[Alpha] is .
Out[9]= \, , A, l, p, h, a, , , i, s, , , .
Out[11]=
\t
In[2]:= InputForm[%]
Out[2]//InputForm= "First line.\nSecond line."
When you enter a long string in Mathematica, it is often convenient to break your input across several
lines. Mathematica will by default ignore such breaks, so that if you subsequently output the string, it
can then be broken in whatever way is appropriate.
416
In[4]:= InputForm[%]
Out[4]//InputForm= "A string on two lines."
"text"
"\<text\>"
In[6]:= InputForm[%]
Out[6]//InputForm= "A string on\ntwo lines."
You should realize that even though it is possible to achieve some formatting of Mathematica output
by creating strings which contain raw tabs and newlines, this is rarely a good idea. Typically a much
better approach is to use the higher-level Mathematica formatting primitives to be discussed in the next
two sections. These primitives will always yield consistent output, independent of such issues as the
positions of tab settings on a particular device.
In strings with newlines, text is always
aligned on the left.
417
Within Mathematica you can use formatting primitives to avoid raw tabs and newlines. But if you
intend to send your output in textual form to external programs, then these programs will often expect
to get raw tabs and newlines.
Note that you must either use WriteString or give your output in OutputForm in order for the
raw tabs and newlines to show up. In InputForm , they will just be given as \t and \n.
This outputs a string to a file.
In[11]:= !!test
In[13]:= !!test
First line.
Second line.
Mathematica assigns every character that can appear in a string a unique character code. This code is
used internally as a way to represent the character.
This gives the character codes for the
characters in the string.
In[2]:= FromCharacterCode[%]
In[3]:= ToCharacterCode[""]
Out[1]= 65, 66, 67, 68, 32, 97, 98, 99, 100
418
Mathematica assigns names such as \[Alpha] to a large number of special characters. This means
that you can always refer to such characters just by giving their names, without ever having to know
their character codes.
This generates a string of special
characters from their character codes.
In[7]:= InputForm[%]
Out[6]= 8QY
Out[7]//InputForm= "\[PartialD]\[EmptySet]\[Del]\[Element]"
Mathematica has names for all the common characters that are used in mathematical notation and
in standard European languages. But for a language such as Japanese, there are more than 3,000
additional characters, and Mathematica does not assign an explicit name to each of them. Instead, it
refers to such characters by standardized character codes.
Here is a string containing Japanese
characters.
In[8]:= "
Out[8]=
Q"
Q
In[9]:= InputForm[%]
Out[9]//InputForm= "\:6570\:5b66"
The notebook front end for Mathematica is typically set up so that when you enter a character in a
particular font, Mathematica will automatically work out the character code for that character.
Sometimes, however, you may find it convenient to be able to enter characters directly using
character codes.
\0
\nnn
\.nn
\:nnnn
419
For characters with character codes below 256, you can use \nnn or \.nn. For characters with
character codes above 256, you must use \:nnnn. Note that in all cases you must give a fixed number
of octal or hexadecimal digits, padding with leading 0s if necessary.
This gives character codes in
hexadecimal for a few characters.
In[11]:= "\.41\.e0\:03b1\:2135"
Out[11]= AZ
In assigning codes to characters, Mathematica follows three compatible standards: ASCII, ISO Latin1, and Unicode. ASCII covers the characters on a normal American English keyboard. ISO Latin-1
covers characters in many European languages. Unicode is a more general standard which defines
character codes for several tens of thousands of characters used in languages and notations around
the world.
ASCII characters
ASCII control characters
arrows
420
Out[12]= 9"#$%&'[,.0123456789:;?=>
?SABCDEFGHIJKLMNOPQRSTUVWXYZ
\^
_`abcdefghijklmnopqrstuvwxyzM
Out[13]=
R34
Out[15]=
$CharacterEncoding = None
$CharacterEncoding = "name"
$SystemCharacterEncoding
When you press a key or combination of keys on your keyboard, the operating system of your
computer sends a certain bit pattern to Mathematica. How this bit pattern is interpreted as a character
within Mathematica will depend on the character encoding that has been set up.
The notebook front end for Mathematica typically takes care of setting up the appropriate character
encoding automatically for whatever font you are using. But if you use Mathematica with a text-based
interface or via files or pipes, then you may need to set $CharacterEncoding explicitly.
421
By specifying an appropriate value for $CharacterEncoding you will typically be able to get Mathematica to handle raw text generated by whatever language-specific text editor or operating system you
use.
You should realize, however, that while the standard representation of special characters used in
Mathematica is completely portable across different computer systems, any representation that involves
raw character encodings will inevitably not be.
"PrintableASCII"
"ASCII"
"ISOLatin1"
"ISOLatin2"
"ISOLatin3"
"ISOLatin4"
"ISOLatinCyrillic"
"AdobeStandard"
"MacintoshRoman"
"WindowsANSI"
"Symbol"
"ZapfDingbats"
"ShiftJIS"
"EUC"
,
"UTF8"
"Unicode"
Mathematica knows about various raw character encodings, appropriate for different computer
systems and different languages.
422
Any character that is included in a particular raw encoding will be written out in raw form by
Mathematica if you specify that encoding. But characters which are not included in the encoding will
still be written out using standard Mathematica full names or hexadecimal codes.
In addition, any character included in a particular encoding can be given in raw form as input to
Mathematica if you specify that encoding. Mathematica will automatically translate the character to its
own standard internal form.
This writes a string to the file tmp.
In[2]:= !!tmp
In[5]:= !!tmp
Out[3]= MacintoshRoman
Out[6]= None
Out[7]= a b c
Mathematica supports both 8- and 16-bit raw character encodings. In an encoding such as
"ISOLatin1" , all characters are represented by bit patterns containing 8 bits. But in an encoding such
as "ShiftJIS" some characters instead involve bit patterns containing 16 bits.
Most of the raw character encodings supported by Mathematica include basic ASCII as a subset.
This means that even when you are using such encodings, you can still give ordinary Mathematica
input in the usual way, and you can specify special characters using \[ and \: sequences.
Some raw character encodings, however, do not include basic ASCII as a subset. An example is
the "Symbol" encoding, in which the character codes normally used for a and b are instead used for
and .
This gives the usual ASCII character
codes for a few English letters.
In[8]:= ToCharacterCode["abcdefgh"]
Out[9]=
ToCharacterCode["string"]
423
ToCharacterCode["string", "encoding"]
generate codes for characters using the specified encoding
FromCharacterCode[{n , n , ... }]
generate characters from codes using the standard
Mathematica encoding
FromCharacterCode[{n , n , ... }, "encoding"]
generate characters from codes using the specified encoding
Handling character codes with different encodings.
In[10]:= ToCharacterCode["abc\[EAcute]\[Pi]"]
The character codes used internally by Mathematica are based on Unicode. But externally Mathematica
by default always uses plain ASCII sequences such as \[Name] or \:xxxx to refer to special characters.
By telling it to use the raw "Unicode" character encoding, however, you can get Mathematica to read
and write characters in raw 16-bit Unicode form.
424
In[3]:= x2
y
2
Out[3]= x y
FullForm[expr]
InputForm[expr]
OutputForm[expr]
StandardForm[expr]
2
Out[5]//OutputForm= x + Sqrt[y]
Output forms provide textual representations of Mathematica expressions. In some cases these textual representations are also suitable for input to Mathematica. But in other cases they are intended just
to be looked at, or to be exported to other programs, rather than to be used as input to Mathematica.
425
TraditionalForm[expr]
TeXForm[expr]
MathMLForm[expr]
CForm[expr]
FortranForm[expr]
Section 2.9.17 will discuss how you can create your own output forms. You should realize however
that in communicating with external programs it is often better to use MathLink to send expressions
directly than to generate a textual representation for these expressions.
426
When you type something like x^2 what Mathematica at first sees is just the string of characters x, ^,
2. But with the usual way that Mathematica is set up, it immediately knows to convert this string of
characters into the expression Power[x, 2].
Then, after whatever processing is possible has been done, Mathematica takes the expression
Power[x, 2] and converts it into some kind of textual representation for output.
Mathematica reads the string of
characters x, ^, 2 and converts it to the
expression Power[x, 2].
In[1]:= x ^ 2
In[2]:= FortranForm[%]
In[3]:= %
Out[1]= x2
Out[2]//FortranForm= x**2
Out[3]= x2
It is important to understand that in a typical Mathematica session In[n] and Out[n] record only
the underlying expressions that are processed, not the textual representations that happen to be used
for their input or output.
If you explicitly request a particular kind of output, say by using TraditionalForm[expr] , then
what you get will be labeled with Out[n]//TraditionalForm . This indicates that what you are
seeing is expr//TraditionalForm , even though the value of Out[n] itself is just expr.
Mathematica also allows you to specify globally that you want output to be displayed in a particular
form. And if you do this, then the form will no longer be indicated explicitly in the label for each
line. But it is still the case that In[n] and Out[n] will record only underlying expressions, not the
textual representations used for their input and output.
This sets t to be an expression with
FortranForm explicitly wrapped
around it.
In[5]:= %
Out[5]= x2 y2
427
In[6]:= t
1
Out[7]= x [[ 2 y [[ 22 ,
x [[ 2 y [[ 2
One-dimensional strings
Two-dimensional boxes
In[2]:= FullForm[%]
In[3]:= Characters[%]
Out[3]= x, ^, 2, , , , y, ^, 3
Out[4]= RowBox
SuperscriptBox
x, 2, , SuperscriptBox
y, 3
If you use the notebook front end for Mathematica, then you can see the expression that corresponds
to the textual form of each cell by using the Show Expression menu item.
Here is a cell containing an expression
in StandardForm .
Log
1 x2
1
Log
x
2 1 x2
2
428
Cell[BoxData[
RowBox[{
FractionBox["1",
RowBox[{"2", " ",
RowBox[{"(",
RowBox[{"1", "+",
SuperscriptBox["x", "2"]}], ")"}]}]], "+",
RowBox[{"Log", "[", "x", "]"}], "",
FractionBox[
RowBox[{"Log", "[",
RowBox[{"1", "+",
SuperscriptBox["x", "2"]}], "]"}], "2"]}]], "Output"]
ToString[expr, form]
ToBoxes[expr, form]
In[3]:= ToExpression[%]
Out[3]= 2 x2
In any Mathematica session, Mathematica is always effectively using ToExpression to interpret the
textual form of your input as an actual expression to evaluate.
If you use the notebook front end for Mathematica, then the interpretation only takes place when the
contents of a cell are sent to the kernel, say for evaluation. This means that within a notebook there
is no need for the textual forms you set up to correspond to meaningful Mathematica expressions; this
is only necessary if you want to send these forms to the kernel.
FullForm
429
InputForm
one-dimensional notation
StandardForm
two-dimensional notation
In[5]:= 1 + x^2
In[6]:= 1 x2
Out[4]= 1 x2
Out[5]= 1 x2
Out[6]= 1 x2
Built into Mathematica is a collection of standard rules for use by ToExpression in converting
textual forms to expressions.
These rules define the grammar of Mathematica. They state, for example, that x + y should be interpreted as Plus[x, y], and that xy should be interpreted as Power[x, y]. If the input you give
is in FullForm, then the rules for interpretation are very straightforward: every expression consists
just of a head followed by a sequence of elements enclosed in brackets. The rules for InputForm are
slightly more sophisticated: they allow operators such as +, =, and ->, and understand the meaning
of expressions where these operators appear between operands. StandardForm involves still more
sophisticated rules, which allow operators and operands to be arranged not just in a one-dimensional
sequence, but in a full two-dimensional structure.
Mathematica is set up so that FullForm , InputForm and StandardForm form a strict hierarchy:
anything you can enter in FullForm will also work in InputForm , and anything you can enter in
InputForm will also work in StandardForm .
If you use a notebook front end for Mathematica, then you will typically want to use all the features
of StandardForm . If you use a text-based interface, however, then you will typically be able to use
only features of InputForm .
x^2
\!\(x\^2\)
ordinary InputForm
one-dimensional representation of StandardForm
When you use StandardForm in a Mathematica notebook, you can enter directly two-dimensional
forms such as x2 . But InputForm allows only one-dimensional forms. Nevertheless, even though the
430
actual text you give in InputForm must be one-dimensional, it is still possible to make it represent a
two-dimensional form. Thus, for example, \!\(x\^2\) represents the two-dimensional form x2 , and
is interpreted by Mathematica as Power[x, 2].
Here is ordinary one-dimensional
input.
In[9]:= % == %%
1
Out[7]= x2
y
1
Out[8]= x2
y
Out[9]= True
If you copy a two-dimensional form out of Mathematica, it is normally given in \!\( ... \) form.
When you paste this one-dimensional form back into a Mathematica notebook, it will automatically
snap into two-dimensional form. If you simply type a \!\( ... \) form into a notebook, you can
get it to snap into two-dimensional form using the Make 2D menu item.
ToExpression[input, form]
StandardForm and its subsets FullForm and InputForm provide precise ways to represent any
Mathematica expression in textual form. And given such a textual form, it is always possible to
convert it unambiguously to the expression it represents.
TraditionalForm is an example of a textual form intended primarily for output. It is possible to
take any Mathematica expression and display it in TraditionalForm . But TraditionalForm does not
have the precision of StandardForm , and as a result there is in general no unambiguous way to go
back from a TraditionalForm representation and get the expression it represents.
Nevertheless, ToExpression[input, TraditionalForm] takes text in TraditionalForm and attempts to interpret it as an expression.
This takes a string and interprets it as
TraditionalForm input.
Out[10]= f 6
Out[11]= 6 f
431
When TraditionalForm output is generated as the result of a computation, the actual collection
of boxes that represent the output typically contains special InterpretationBox and TagBox objects
which specify how an expression can be reconstructed from the TraditionalForm output.
The same is true of TraditionalForm that is obtained by explicit conversion from StandardForm .
But if you edit TraditionalForm extensively, or enter it from scratch, then Mathematica will have to
try to interpret it without the benefit of any additional embedded information.
Short[expr]
Short[expr, n]
Shallow[expr]
Shallow[expr, {depth, length}]
In[2]:= Short[t]
Out[2]//Short= 1 12 x :87; 12 x y11 y12
When Mathematica generates output, it first effectively writes the output in one long row. Then it
looks at the width of text you have asked for, and it chops the row of output into a sequence of
separate lines. Each of the lines may of course contain superscripts and built-up fractions, and so
may take up more than one actual line on your output device. When you specify a particular number
of lines in Short, Mathematica takes this to be the number of logical lines that you want, not the
number of actual physical lines on your particular output device.
Here is a four-line version of t. More
terms are shown in this case.
In[3]:= Short[t, 4]
Out[3]//Short= 1 12 x 66 x2 220 x3 495 x4 792 x5 924 x6
792 x7 495 x8 220 x9 66 x10 12 x11 :68;
495 x4 y8 220 y9 660 x y9 660 x2 y9 220 x3 y9
66 y10 132 x y10 66 x2 y10 12 y11 12 x y11 y12
432
In[4]:= Short[InputForm[t]]
Out[4]//Short= 1 12[x 66[x^2 220[x^3 ??85>> 12[x[y^11 y^12
Short works by removing a sequence of parts from an expression until the output form of the
result fits on the number of lines you specify. Sometimes, however, you may find it better to
specify not how many final output lines you want, but which parts of the expression to drop.
Shallow[expr, {depth, length}] includes only length arguments to any function, and drops all subexpressions that are below the specified depth.
Shallow shows a different outline of t.
In[5]:= Shallow[t]
Out[5]//Shallow= 1 12 x 66 Power
:2; 220 Power
:2;
495 Power
:2; 792 Power
:2;
924 Power
:2; 792 Power
:2;
495 Power
:2; 220 Power
:2; :81;
Shallow is particularly useful when you want to drop parts in a uniform way throughout a highly
nested expression, such as a large list structure returned by Trace.
Here is the recursive definition of the
Fibonacci function.
In[8]:= tr = Trace[fib[8]] ;
In[9]:= Shallow[tr]
In[10]:= Short[tr, 4]
Out[7]= 1
Text strings.
433
In[2]:= InputForm[%]
Out[2]//InputForm= "This is a string."
You can put any kind of text into a Mathematica string. This includes non-English characters, as well
as newlines and other control information. Section 2.8 discusses in more detail how strings work.
StringForm["cccc``cccc", x , x , ... ]
output a string in which successive `` are replaced by
successive xi
StringForm["cccc`i`cccc", x , x , ... ]
output a string in which each `i` is replaced by the
corresponding xi
Using format strings.
In many situations, you may want to generate output using a string as a template, but splicing
in various Mathematica expressions. You can do this using StringForm .
This generates output with each
successive `` replaced by an
expression.
Out[3]= x = 3, y = 1 u
Out[4]= a, b, a
The string in StringForm acts somewhat like a format directive in the formatted output statements of languages such as C and Fortran. You can determine how the expressions in StringForm
will be formatted by wrapping them with standard output format functions.
You can specify how the expressions in
StringForm are formatted using
standard output format functions.
You should realize that StringForm is only an output format. It does not evaluate in any way. You
can use the function ToString to create an ordinary string from a StringForm object.
StringForm generates formatted output
in standard Mathematica output form.
In[7]:= InputForm[%]
In[8]:= InputForm[ToString[%]]
Out[6]= Q: a > b
434
StringForm allows you to specify a template string, then fill in various expressions. Sometimes
all you want to do is to concatenate together the output forms for a sequence of expressions. You can
do this using SequenceForm .
x2
HoldForm[expr]
Using text strings and functions like StringForm , you can generate pieces of output that do not
necessarily correspond to valid Mathematica expressions. Sometimes, however, you want to generate
output that corresponds to a valid Mathematica expression, but only so long as the expression is not
evaluated. The function HoldForm maintains its argument unevaluated, but allows it to be formatted
in the standard Mathematica output form.
HoldForm maintains 1 + 1 unevaluated.
In[11]:= HoldForm[1 + 1]
Out[11]= 1 1
In[12]:= HoldForm[x = 3]
Out[12]= x = 3
435
In[13]:= HoldForm[34^78]
Out[13]= 3478
In[2]:= ScientificForm[%]
In[3]:= EngineeringForm[%]
NumberForm[expr, tot]
ScientificForm[expr, tot]
EngineeringForm[expr, tot]
Out[1]=
Out[2]//ScientificForm=
Out[3]//EngineeringForm=
436
option name
default value
DigitBlock
Infinity
NumberSeparator
NumberPoint
"."
NumberMultiplier
"\[Times]"
NumberSigns
{"-", ""}
NumberPadding
{"", ""}
SignPadding
False
NumberFormat
Automatic
ExponentFunction
Automatic
All the options in the table except the last one apply to both integers and approximate real numbers.
All the options can be used in any of the functions NumberForm , ScientificForm ,
EngineeringForm and AccountingForm . In fact, you can in principle reproduce the behavior of any
one of these functions simply by giving appropriate option settings in one of the others. The default
option settings listed in the table are those for NumberForm .
Setting DigitBlock->n breaks digits
into blocks of length n.
Out[8]//NumberForm= 265,252,859,812,191,058,636,308,480,000,000
437
When Mathematica prints an approximate real number, it has to choose whether scientific notation
should be used, and if so, how many digits should appear to the left of the decimal point. What
Mathematica does is first to find out what the exponent would be if scientific notation were used, and
one digit were given to the left of the decimal point. Then it takes this exponent, and applies any
function given as the setting for the option ExponentFunction . This function should return the actual
exponent to be used, or Null if scientific notation should not be used.
The default is to use scientific notation
for all numbers with exponents outside
the range to 5.
In[12]:= NumberForm[%,
ExponentFunction -> (If[-10 < # < 10, Null, #]&)]
Out[11]=
Out[12]//NumberForm=
Having determined what the mantissa and exponent for a number should be, the final step is to
assemble these into the object to print. The option NumberFormat allows you to give an arbitrary
function which specifies the print form for the number. The function takes as arguments three strings:
the mantissa, the base, and the exponent for the number. If there is no exponent, it is given as "".
This gives the exponents in Fortran-like
e format.
PaddedForm[expr, tot]
In[15]:= FortranForm[7.8^20]
Out[15]//FortranForm= 6.948515870862152e17
print with all numbers having room for tot digits, padding
with leading spaces if necessary
print with all numbers having room for tot digits, with
exactly frac digits to the right of the decimal point
Whenever you print a collection of numbers in a column or some other definite arrangement, you
typically need to be able to align the numbers in a definite way. Usually you want all the numbers
438
to be set up so that the digit corresponding to a particular power of 10 always appears at the same
position within the region used to print a number.
You can change the positions of digits in the printed form of a number by padding it in various
ways. You can pad on the right, typically adding zeros somewhere after the decimal. Or you can pad
on the left, typically inserting spaces in place of leading zeros.
This pads with spaces to make room
for up to 7 digits in each integer.
Out[16]//PaddedForm=
Out[17]//PaddedForm=
456,
12345,
12
456
12345
12
In[21]:= PaddedForm[
ColumnForm[{6.7 10^8, 48.7, -2.3 10^-16}], {4, 2}]
Out[18]//PaddedForm= 6.7000,
6.8880,
7.0000
Out[20]//PaddedForm= 6.7000,
Out[21]//PaddedForm=
6.8880,
7.0000
6.70 108
48.70
2.30 1016
With the default setting for the option NumberPadding , both NumberForm and PaddedForm insert
trailing zeros when they pad a number on the right. You can use spaces for padding on both the left
and the right by setting NumberPadding -> {" ", " "}.
This uses spaces instead of zeros for
padding on the right.
BaseForm[expr, b]
Printing numbers in other bases.
6.888 ,
7.
439
In[23]:= BaseForm[2342424, 2]
Out[23]//BaseForm= 10001110111110000110002
In[25]:= BaseForm[2.3, 2]
Out[24]//BaseForm= e71e57d16
Out[25]//BaseForm= 10.0100110011001100112
Section 3.1.3 discusses how to enter numbers in arbitrary bases, and also how to get lists of the
digits in a number.
MatrixForm[list]
Here is a list.
In[2]:= TableForm[%]
In[3]:= MatrixForm[%]
46
Out[2]//TableForm= 47
48
2116
2209
2304
97336
103823
110592
440
x y x y2 x y3
"
$
$
$ x2 y x2 y2 x2 y3
Out[4]//MatrixForm= $
$
$
$
3
3
2
3
3
#x y x y x y
PaddedForm[TableForm[list], tot]
PaddedForm[TableForm[list], {tot, frac}]
%
'
'
'
'
'
'
'
&
In[6]:= TableForm[fac]
3628800
Out[6]//TableForm= 1307674368000
2432902008176640000
Out[7]//PaddedForm=
Out[8]//TableForm=
Out[9]//PaddedForm=
3628800
1307674368000
2432902008176640000
3628800
1307674368000
2432902008176640000
6.70000
6.88800
6.99999
You can use TableForm and MatrixForm to format lists that are nested to any depth, corresponding
to arrays with any number of dimensions.
Here is the format for a array of
elements a[i, j].
a
1, 1
a
2, 1
a
1, 2
a
2, 2
Here is a array.
441
a
1,
a
1,
Out[11]//TableForm=
b
1,
b
1,
And here is a array.
1
2
1
2
a
2,
a
2,
b
2,
b
2,
1
2
1
2
a
1,
a
2,
Out[12]//TableForm=
c
1,
c
2,
1
1
1
1
a
1,
a
2,
c
1,
c
2,
2
2
2
2
b
1,
b
2,
d
1,
d
2,
1
1
1
1
b
1,
b
2,
d
1,
d
2,
2
2
2
2
In general, when you print an n-dimensional table, successive dimensions are alternately given as
columns and rows. By setting the option TableDirections -> {dir , dir , ... }, where the diri are
Column or Row, you can specify explicitly which way each dimension should be given. By default, the
option is effectively set to {Column, Row, Column, Row, ... }.
The option TableDirections allows
you to specify explicitly how each
dimension in a multidimensional table
should be given.
a
1, 1
a
1, 2
a
2, 1
a
2, 2
b
1, 1
b
1, 2
b
2, 1
b
2, 2
Whenever you make a table from a nested list such as {list , list , ... }, there is a question of
whether it should be the listi or their elements which appear as the basic entries in the table. The
default behavior is slightly different for MatrixForm and TableForm .
MatrixForm handles only arrays that are rectangular. Thus, for example, to consider an array as
two-dimensional, all the rows must have the same length. If they do not, MatrixForm treats the array
as one-dimensional, with elements that are lists.
MatrixForm treats this as a
one-dimensional array, since the rows
are of differing lengths.
a, a, a
b, b
While MatrixForm can handle only rectangular arrays, TableForm can handle arbitrary ragged
arrays. It leaves blanks wherever there are no elements supplied.
TableForm can handle ragged arrays.
a
b
a
b
Out[16]//TableForm=
p q
r s
x
y
442
You can control the number of levels in a nested list to which both TableForm and MatrixForm go
by setting the option TableDepth .
This tells TableForm only to go down
to depth 2. As a result {x, y} is
treated as a single table entry.
a
c
x, y
d
option name
default value
TableDepth
Infinity
TableDirections
TableAlignments
TableSpacing
{1, 3, 0, 1, 0, ... }
TableHeadings
With the option TableAlignments , you can specify how each entry in the table should be aligned
with its row or column. For columns, you can specify Left, Center or Right. For rows, you can specify Bottom, Center or Top. If you set TableAlignments -> Center, all entries will be centered both
horizontally and vertically. TableAlignments -> Automatic uses the default choice of alignments.
Entries in columns are by default
aligned on the left.
a
Out[18]//TableForm= bbbb
cccccccc
Out[19]//TableForm=
a
bbbb
cccccccc
You can use the option TableSpacing to specify how much horizontal space there should be
between successive columns, or how much vertical space there should be between successive rows. A
setting of 0 specifies that successive objects should abut.
443
a
Out[20]//TableForm= ccc
None
Automatic
{{lab , lab , ... }, ... }
b
d
1
1 2
a[1, 1, 1]
a[1, 1, 2]
a[1, 2, 1]
a[1, 2, 2]
1
2 2
a[2, 1, 1]
a[2, 1, 2]
a[2, 2, 1]
a[2, 2, 2]
first
a
ap
middle
b
bp
last
c
cp
row a
Out[23]//TableForm= row b
row c
2
5
3
6
4
1
StyleForm[expr, "style"]
444
option
typical setting(s)
FontSize
12
FontWeight
"Plain" or "Bold"
weight of characters
FontSlant
"Plain" or "Italic"
slant of characters
FontFamily
FontColor
GrayLevel[0]
color of characters
Background
GrayLevel[1]
If you use the notebook front end for Mathematica, then each piece of output that is generated will by
default be in the style of the cell in which the output appears. By using StyleForm[expr, "style"],
however, you can tell Mathematica to output a particular expression in a different style.
Here is an expression output in the
style normally used for section
headings.
x2 y2
Page 572 describes in more detail how cell styles work. By using StyleForm[expr, "style", options]
you can generate output that is in a particular style, but with certain options modified.
In[1]:= ToBoxes[a + b]
Out[1]= RowBox
a, , b
445
In[2]:= DisplayForm[%]
Out[2]//DisplayForm= a b
DisplayForm[boxes]
Out[4]//DisplayForm= ai
Out[5]//DisplayForm= a1 b2
"text"
RowBox[{a, b, ... }]
GridBox[{{a , b , ... }, {a , b , ... }, ... }]
SubscriptBox[a, b]
SuperscriptBox[a, b]
SubsuperscriptBox[a, b, c]
UnderscriptBox[a, b]
OverscriptBox[a, b]
UnderoverscriptBox[a, b, c]
a1 b1
a grid of boxes a2 b2
subscript ab
superscript ab
subscript and superscript acb
underscript a
b
overscript a
c
FractionBox[a, b]
a
fraction
b
SqrtBox[a]
square root
RadicalBox[a, b]
Some basic box types.
literal text
bth root
b
a
a
446
x
Out[6]//DisplayForm=
n
y
This puts a superscript on a
subscripted object.
Out[7]//DisplayForm= ab c
Out[8]//DisplayForm= acb
FrameBox[box]
GridBox[list, RowLines->True]
GridBox[list, ColumnLines->True]
x
y
2 3 4
Out[10]//DisplayForm= 3 4 5
4 5 6
And this also puts a frame around the
outside.
Out[11]//DisplayForm=
2 3 4
3 4 5
4 5 6
StyleBox[boxes, options]
StyleBox[boxes, "style"]
447
StyleBox takes the same options as StyleForm . The difference is that StyleForm acts as a wrapper for any expression, while StyleBox represents underlying box structure.
This shows the string "name" in italics.
Out[13]//DisplayForm=
Out[14]//DisplayForm=
name
name
If you use a notebook front end for Mathematica, then you will be able to change the style and
appearance of what you see on the screen directly by using menu items. Internally, however, these
changes will still be recorded by the insertion of appropriate StyleBox objects.
FormBox[boxes, form]
InterpretationBox[boxes, expr]
TagBox[boxes, tag]
ErrorBox[boxes]
If you edit the boxes given in an InterpretationBox , then there is no guarantee that the interpretation specified by the interpretation box will still be correct. As a result, Mathematica provides
various options that allow you to control the selection and editing of InterpretationBox objects.
448
option
default value
Editable
False
Selectable
True
Deletable
True
DeletionWarning
False
BoxAutoDelete
False
StripWrapperBoxes
False
TagBox objects are used to store information that will not be displayed but which can nevertheless
be used by the rules that interpret boxes. Typically the tag in TagBox[boxes, tag] is a symbol which
gives the head of the expression corresponding to boxes. If you edit only the arguments of this
expression then there is a good chance that the interpretation specified by the TagBox will still be
appropriate. As a result, Editable->True is the default setting for a TagBox.
The rules that Mathematica uses for interpreting boxes are in general set up to ignore details of
formatting, such as those defined by StyleBox objects. Thus, unless StripWrapperBoxes->False , a
red x, for example, will normally not be distinguished from an ordinary black x.
A red x is usually treated as identical
to an ordinary one.
In[19]:= ToExpression[
StyleBox[x, FontColor->RGBColor[1,0,0]]] == x
Out[19]= True
ButtonBox[boxes]
In a Mathematica notebook it is possible to set up elements which perform an action whenever you
click on them. These elements are represented internally by ButtonBox objects. When you create an
expression containing a ButtonBox , you will be able to edit the contents of the ButtonBox directly
so long as the Active option is False for the cell containing the expression. As soon as you set
Active->True , the ButtonBox will perform its action whenever you click on it.
Section 2.11.6 discusses how to set up actions for ButtonBox objects.
449
option
default value
ColumnAlignments
Center
RowAlignments
Baseline
ColumnSpacings
0.8
RowSpacings
1.0
ColumnsEqual
False
RowsEqual
False
ColumnWidths
Automatic
RowMinHeight
GridBaseline
Axis
ColumnLines
False
RowLines
False
GridDefaultElement
""
Options to GridBox.
1
2
6
2
24
720
Out[2]//DisplayForm=
3 720
362880
4 40320 479001600
450
1
2
6
2
24
720
Out[3]//DisplayForm=
3
720
362880
4 40320 479001600
This left justifies the first two columns
and right justifies the last one.
In[4]:= GridBox[t,
ColumnAlignments->{Left, Left, Right}] // DisplayForm
1
2
Out[4]//DisplayForm=
3
4
This sets the gutters between columns.
2
6
24
720
720
362880
40320 479001600
1
2
Out[5]//DisplayForm=
3
4
This forces all columns to be the same
width.
Center
Left
Right
6
720
362880
479001600
Out[6]//DisplayForm=
2
24
720
40320
1
2
3
4
2
24
720
40320
6
720
362880
479001600
x x x x
,
x x x x
centered (default)
left justified (aligned on left edge)
right justified (aligned on right edge)
"."
"c"
451
In formatting complicated tables, it is often important to be able to control in detail the alignment
of table entries. By setting ColumnAlignments->"c" you tell Mathematica to arrange the elements in
each column so that the first occurrence of the character "c" in each entry is aligned.
Choosing ColumnAlignments->"." will therefore align numbers according to the positions of their
decimal points. Mathematica also provides a special \[AlignmentMarker] character, which can be
entered as , am ,. This character does not display explicitly, but can be inserted in entries in a table to
mark which point in these entries should be lined up.
Center
Top
Bottom
Baseline
Axis
{pos , pos , ... }
centered
tops aligned
bottoms aligned
baselines aligned (default)
axes aligned
separate specifications for each row in the grid
yz
yz
In a piece of ordinary text, successive characters are normally positioned so that their baselines are
aligned. For many characters, such as m and x, the baseline coincides with the bottom of the character.
But in general the baseline is the bottom of the main part of the character, and for example, in most
fonts g and y have descenders that extend below the baseline.
This shows the alignment of characters
with the default setting
RowAlignments->Baseline .
Out[10]//DisplayForm= x m g y
Out[11]//DisplayForm= x m g y
Like characters in ordinary text, Mathematica will normally position sequences of boxes so that their
baselines are aligned. For many kinds of boxes the baseline is simply taken to be the baseline of the
452
main element of the box. Thus, for example, the baseline of a SuperScript box xy is taken to be the
baseline of x.
x
For a FractionBox , the fraction bar defines the axis of the box. In text in a particular font, one
y
can also define an axisa line going through the centers of symmetrical characters such as + and (.
The baseline for a FractionBox is then taken to be the same distance below its axis as the baseline
for text in the current font is below its axis.
For a GridBox, you can use the option GridBaseline to specify where the baseline should be taken
to lie. The possible settings are the same as the ones for RowAlignments . The default is Axis, which
makes the center of the GridBox be aligned with the axis of text around it.
The GridBaseline option specifies
where the baseline of the GridBox
should be assumed to be.
Out[12]//DisplayForm=
x x
x x
x x
, x x!
option
default value
Background
GrayLevel[0.8]
ButtonFrame
"Palette"
ButtonExpandable
True
ButtonMargins
ButtonMinHeight
ButtonStyle
"Paste"
In[13]:= ButtonBox["abcd",
ButtonFrame->"DialogBox"] // DisplayForm
Out[13]//DisplayForm=
abcd
453
abc
xyz
In[15]:= GridBox[{{ButtonBox["abcd"]},
{ButtonBox["x"]}}] // DisplayForm
abcd
Out[15]//DisplayForm=
x
Here the lower button is made not to
expand.
abcd
Out[16]//DisplayForm=
Section 2.11.6 will discuss how to set up actions for ButtonBox objects.
printers point
pica
font point size
em
en
x-height
Units of distance.
454
full name
alias
\[InvisibleSpace]
, is ,
zero-width space
\[VeryThinSpace]
,,
1/18 em (x x)
\[ThinSpace]
, ,
3/18 em (x x)
\[MediumSpace]
, ,
4/18 em (x x)
\[ThickSpace]
, ,
5/18 em (x x)
\[NegativeVeryThinSpace]
, - ,
em (xx)
\[NegativeThinSpace]
, - ,
em (xx)
\[NegativeMediumSpace]
, - ,
em (xx)
\[NegativeThickSpace]
, - ,
em (x)
\[RawSpace]
\[SpaceIndicator]
, space ,
Spacing characters of various widths. indicates the space key on your keyboard.
When you enter input such as x+y, Mathematica will automatically convert this to
RowBox[{"x","+","y"}] . When the RowBox is output, Mathematica will then try to insert appropriate
space between each element. Typically, it will put more space around characters such as + that are
usually used as operators, and less space around characters such as x that are not. You can however
always modify spacing by inserting explicit spacing characters. Positive spacing characters will move
successive elements further apart, while negative ones will bring them closer together.
Mathematica by default leaves more
space around characters such as + and
- that are usually used as operators.
Out[17]//DisplayForm= ab c
Out[18]//DisplayForm= a b c
StyleBox[boxes, AutoSpacing->False]
leave the same space around every character in boxes
Inhibiting automatic spacing in Mathematica.
455
When you have an expression displayed on the screen, the notebook front end allows you interactively to make detailed adjustments to the positions of elements. Typically a , , b ,
c nudge whatever you have selected by one pixel at your current screen magnification. Such
adjustments are represented within Mathematica using AdjustmentBox objects.
The left and right margins in an AdjustmentBox are given in ems; the bottom and top ones in
x-heights. By giving positive values for margins you can force there to be space around a box. By
giving negative values you can effectively trim space away, and force other boxes to be closer. Note
that in a RowBox, vertical alignment is determined by the position of the baseline; in a FractionBox
or an OverscriptBox , for example, it is instead determined by top and bottom margins.
StyleBox[boxes, ShowContents->False]
leave space for boxes but do not display them
Leaving space for boxes without displaying them.
If you are trying to line up different elements of your output, you can use ShowContents->False
in StyleBox to leave space for boxes without actually displaying them.
This leaves space for the Y, but does
not display it.
456
The sizes of most characters are determined solely by what font they are in, as specified for example
by the FontSize option in StyleBox . But there are some special expandable characters whose size
can change even within a particular font. Examples are parentheses, which by default are taken to
expand so as to span any expression they contain.
Parentheses by default expand to span
whatever expressions they contain.
X
Out[23]//DisplayForm= X,
option
default value
SpanMinSize
Automatic
SpanMaxSize
Automatic
SpanSymmetric
True
SpanLineThickness
Automatic
X
"
"
$
$
$
$
$
$
Out[24]//DisplayForm= $
$Y
$
$$
$
## Z
X
"
$
$Y
Out[25]//DisplayForm= $
$
$
$
#Z
457
%
"X'
$
$Y'
'
'
$
Out[27]//DisplayForm= $
'
$
$
'
$
'
$ '
# &
Setting SpanSymmetric->False allows
expandable characters to grow
asymmetrically.
X
Out[28]//DisplayForm= X, Y
The notebook front end typically provides a Spanning Characters menu which allows you to change
the spanning characteristics of all characters within your current selection.
a xxxxxxx b
a dddddddddd b
option
default value
ScriptSizeMultipliers
0.71
ScriptMinSize
ScriptBaselineShifts
{Automatic, Automatic}
StyleBox options for controlling the size and positioning of subscripts, etc.
458
In[32]:= b = ToBoxes[X^X^X^X^X]
In[33]:= b // DisplayForm
X
XX
Out[33]//DisplayForm= XX
X
XX
Out[34]//DisplayForm= XX
X
XX
Out[35]//DisplayForm= XX
Mathematica will usually optimize the position of subscripts and superscripts in a way that depends
on their environment. If you want to line up several different subscripts or superscripts you therefore
typically have to use the option ScriptBaselineShifts to specify an explicit distance to shift each
one.
The second subscript is by default
shifted down slightly more than the
first.
This tells Mathematica to apply exactly
the same shift to both subscripts.
option
default value
LimitsPositioning
Automatic
Out[38]= f
i
i=0
In[39]:= 1/%
1
Out[39]=
n
)i=0 f
i
459
Out[40]//DisplayForm= XX
low
option
default value
MultilineFunction
Automatic
When you are dealing with long expressions it is inevitable that they will continue beyond the
length of a single line. Many kinds of boxes change their display characteristics when they break
across several lines.
This displays as a built-up fraction on
a single line.
1 5 x 10 x2 10 x3 5 x4 x5
Out[42]=
1 5 y 10 y2 10 y3 5 y4 y5
You can use the option MultilineFunction to specify how a particular box should be displayed if
it breaks across several lines. The setting MultilineFunction->None prevents the box from breaking
at all.
You can to some extent control where expressions break across lines by inserting \[NoBreak] and
\[NonBreakingSpace] characters. Mathematica will try to avoid ever breaking an expression at the
position of such characters.
You can force Mathematica to break a line by explicitly inserting a \[NewLine] character, obtained
in the standard notebook front end simply by typing RETURN. With default settings for options, Mathematica will automatically indent the next line after you type a RETURN. However, the level of indenting
used will be fixed as soon as the line is started, and will not change when you edit around it. By
460
inserting an \[IndentingNewLine] character, you can tell Mathematica always to maintain the correct
level of indenting based on the actual environment in which a line occurs.
full name
alias
\[NoBreak]
, nb ,
\[NonBreakingSpace]
, nbs ,
\[NewLine]
\[IndentingNewLine]
, nl ,
When Mathematica breaks an expression across several lines, it indents intermediate lines by an
amount proportional to the nesting level in the expression at which the break occurred.
The line breaks here occur only at
level 1.
In[44]:= Range[30]
Out[44]= 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
Out[45]= x +
y
In[2]:= \( x \^ 2 \)
Out[1]= \x\^2\
Out[2]= SuperscriptBox x, 2
It is important to distinguish between forms that represent just raw boxes, and forms that represent
the meaning of the boxes.
461
In[4]:= \( x \^ 2 \)
Out[4]= SuperscriptBox
x, 2
In[5]:= \!\( x \^ 2 \)
\(input\)
\!\(input\)
Out[5]= x2
Out[6]//FullForm= Power x, 2
raw boxes
the meaning of the boxes
If you copy the contents of a StandardForm cell into another program, such as a text editor, Mathematica will automatically generate a \!\( ... \) form. This is done so that if you subsequently paste
the form back into Mathematica, the original contents of the StandardForm cell will automatically be
re-created. Without the \!, only the raw boxes corresponding to these contents would be obtained.
With default settings for options, \!\( ... \) forms pasted into Mathematica notebooks are automatically displayed in two-dimensional form. \!\( ... \) forms entered directly from the keyboard can
be displayed in two-dimensional form using the Make 2D item in the Edit menu.
"\(input\)"
"\!\(input\)"
Mathematica will usually treat a \( ... \) form that appears within a string just like any other
sequence of characters. But by inserting a \! you can tell Mathematica instead to treat this form like
the boxes it represents. In this way you can therefore embed box structures within ordinary character
strings.
Mathematica treats this as an ordinary
character string.
Out[7]= \ x \^ 2 \
Out[8]= x2
462
box \^ box
SuperscriptBox[box , box ]
box \_ box
SubscriptBox[box , box ]
OverscriptBox[box , box ]
box \+ box
UnderscriptBox[box , box ]
\@ box
\@ box \% box
form \` box
\* input
Mathematica requires that any input forms you give for boxes be enclosed within \( and \). But
within these outermost \( and \) you can use additional \( and \) to specify grouping.
Here ordinary parentheses are used to
indicate grouping.
In[10]:= \( x \/ (y + z) \) // DisplayForm
x
Out[10]//DisplayForm=
y z
In[11]:= \( x \/ y + z \) // DisplayForm
x
Out[11]//DisplayForm= z
y
When you type aa+bb as input to Mathematica, the first thing that happens is that aa, + and bb
are recognized as being separate tokens. The same separation into tokens is done when boxes are
constructed from input enclosed in \( ... \). However, inside the boxes each token is given as a
string, rather than in its raw form.
The RowBox has aa, + and bb broken
into separate strings.
463
In[15]:= \( aa + bb \) // FullForm
In[16]:= \( aa \ + \ bb \) // FullForm
Out[16]//FullForm= RowBox List "aa", " ", "", " ", "bb"
Out[17]//FullForm= RowBox
List
"aa", "", RowBox
List
"bb", "", "cc"
Within \( ... \) sequences, you can set up certain kinds of boxes by using backslash notations such
as \^ and \@. But for other kinds of boxes, you need to give ordinary Mathematica input, prefaced
by \*.
This constructs a GridBox .
a b
c d
\* in effect acts like an escape: it allows you to enter ordinary Mathematica syntax even within
a \( ... \) sequence. Note that the input you give after a \* can itself in turn contain \( ... \)
sequences.
You can alternate nested \* and
\( . . . \). Explicit quotes are needed
outside of \( . . . \).
a
Out[21]//DisplayForm= x c2
b
d
x y
x y
In the notebook front end, you can typically use * or 8 to get a dialog box in which you
can enter raw boxesjust as you do after \*.
\!\(input\)
\!\(form \` input\)
Controlling the way input is interpreted.
464
Out[22]= c 1 x
Out[23]= c 1 x
When you copy the contents of a cell from a notebook into a program such as a text editor, no
explicit backslash backquote sequence is usually included. But if you expect to paste what you get
back into a cell of a different type from the one it came from, then you will typically need to include
a backslash backquote sequence in order to ensure that everything is interpreted correctly.
ToString[expr]
ToBoxes[expr]
ToExpression[input]
In[3]:= FullForm[%]
Out[5]= RowBox
SuperscriptBox
x, 2, , SuperscriptBox
y, 2
465
In generating data for files and external programs, it is sometimes necessary to produce twodimensional forms which use only ordinary keyboard characters. You can do this using OutputForm .
This produces a string which gives a
two-dimensional rendering of the
expression, using only ordinary
keyboard characters.
In[7]:= FullForm[%]
Out[6]= 2
2
x + y
Out[7]//FullForm= " 2
2\nx
+ y"
Out[8]//DisplayForm= 2 2
x y
If you operate only with one-dimensional structures, you can effectively use ToString to do string
manipulation with formatting functions.
This generates a string corresponding
to the OutputForm of StringForm .
InputForm
StandardForm
TraditionalForm
Out[10]= x2 y2
Out[11]= x2 y2
Out[12]= x2 y2
Out[13]= RowBox
SuperscriptBox
x, 2, , SuperscriptBox
y, 2
466
ToExpression[input, form, h]
In[18]:= ReleaseHold[%]
Out[16]= 2
Out[17]= Hold 1 1
Out[18]= 2
SyntaxQ["string"]
SyntaxLength["string"]
ToExpression will attempt to interpret any string as Mathematica input. But if you give it a string
that does not correspond to syntactically correct input, then it will print a message, and return
$Failed.
This is not syntactically correct input,
so ToExpression does not convert it to
an expression.
Out[19]= $Failed
Out[20]= $Failed
You can use the function SyntaxQ to test whether a particular string corresponds to syntactically
correct Mathematica input. If SyntaxQ returns False, you can find out where the error occurred using
SyntaxLength . SyntaxLength returns the number of characters which were successfully processed
before a syntax error was detected.
467
Out[21]= False
Out[22]= 3
Out[23]= 10
a, xyz,
"some text", " + "
123.456 , 3*^45
+, ->,
(* comment *)
symbols
strings
numbers
operators
input to be ignored
When you give text as input to Mathematica, the first thing that Mathematica does is to break the
text into a sequence of tokens, with each token representing a separate syntactic unit.
Thus, for example, if you give the input xx+yy-zzzz , Mathematica will break this into the sequence
of tokens xx, +, yy, - and zzzz. Here xx, yy and zzzz are tokens that correspond to symbols, while
+ and - are operators.
Operators are ultimately what determine the structure of the expression formed from a particular
piece of input. The Mathematica language involves several general classes of operators, distinguished
by the different positions in which they appear with respect to their operands.
468
prefix
!x
Not[x]
postfix
x!
Factorial[x]
infix
x+y+z
Plus[x, y, z]
matchfix
{x, y, z}
List[x, y, z]
compound
x /: y = z
TagSet[x, y, z]
overfix
f
x
OverHat[x]
Operators typically work by picking up operands from definite positions around them. But when
a string contains more than one operator, the result can in general depend on which operator picks
up its operands first.
Thus, for example, a*b+c could potentially be interpreted either as (a*b)+c or as a*(b+c) depending on whether * or + picks up its operands first.
To avoid such ambiguities, Mathematica assigns a precedence to each operator that can appear.
Operators with higher precedence are then taken to pick up their operands first.
Thus, for example, the multiplication operator * is assigned higher precedence than +, so that it
picks up its operands first, and a*b+c is interpreted as (a*b)+c rather than a*(b+c) .
The * operator has higher precedence
than +, so in both cases Times is the
innermost function.
In[2]:= a * b + c // f
In[3]:= f @ a * b + c
Out[2]= f a b c
Out[3]= c b f a
Whatever the precedence of the operators you are using, you can always specify the structure of
the expressions you want to form by explicitly inserting appropriate parentheses.
Inserting parentheses makes Plus
rather than Times the innermost
function.
469
e[e], e @@ e, etc.
Power-related operators
Multiplication-related operators
Addition-related operators
Relational operators
Arrow and vector operators
Logic operators
\e e , e && e, e e, e e, etc.
e&
Assignment operators
e = e, e := e, etc.
Compound expression
e; e
The table on pages 10241029 gives the complete ordering by precedence of all operators in
Mathematica. Much of this ordering, as in the case of * and +, is determined directly by standard
mathematical usage. But in general the ordering is simply set up to make it less likely for explicit
parentheses to have to be inserted in typical pieces of input.
Operator precedences are such that this
requires no parentheses.
In[5]:= x y x y y m
0!nm
In[6]:= FullForm[%]
Out[7]=
flat
x+y+z
x+y+z
left grouping
x/y/z
(x / y) / z
right grouping
x^y^z
x ^ (y ^ z)
470
Out[8]//FullForm= Plus a, b, c, d
In[8]:= FullForm[a + b + c + d]
In[9]:= FullForm[a ^ b ^ c ^ d]
The syntax of the Mathematica language is defined not only for characters that you can type on a
typical keyboard, but also for all the various special characters that Mathematica supports.
Letters such as , and Y from any alphabet are treated just like ordinary English letters, and can
for example appear in the names of symbols. The same is true of letter-like forms such as ,
and [.
But many other special characters are treated as operators. Thus, for example, K and are infix
operators, while a is a prefix operator, and and are matchfix operators.
K is an infix operator.
In[10]:= a b c // FullForm
Out[10]//FullForm= CirclePlus
a, b, c
Some special characters form elements of fairly complicated compound operators. Thus, for example, f 7 x contains the compound operator with elements and 7.
The and 7 form parts of a
compound operator.
Out[13]= c x a x b x7x
Out[14]= c x a x b x7x
Input to Mathematica can be given not only in the form of one-dimensional strings, but also in
the form of two-dimensional boxes. The syntax of the Mathematica language covers not only onedimensional constructs but also two-dimensional ones.
This superscript is interpreted as a
power.
In[15]:= xab
8x f is a two-dimensional compound
operator.
In[16]:= x xn
Out[15]= xab
Out[16]= n x1n
471
#
1
In[17]:=
s
n
n1
Out[17]= Zeta s
#
1
In[18]:= n
s
n
n1
Out[18]= n Zeta s
In[1]:= 2 3 FullForm
In[2]:= 2 3
In[3]:= x_ y_ := Mod[x + y, 2]
In[4]:= 2 3
Out[1]//FullForm= CirclePlus 2, 3
Out[2]= 2 O 3
Out[4]= 1
xOy
CirclePlus[x, y]
xhy
TildeTilde[x, y]
xiy
Therefore[x, y]
xjy
LeftRightArrow[x, y]
Yx
Del[x]
x
Square[x]
/x,y, ... 0
AngleBracket[x, y, ... ]
472
Mathematica follows the general convention that the function associated with a particular operator
should have the same name as the special character that represents that operator.
\[Congruent] is displayed as k.
In[5]:= x \[Congruent] y
Out[5]= x k y
In[6]:= FullForm[%]
Out[6]//FullForm= Congruent
x, y
x \[name] y
\[name] x
\[Leftname] x, y, ... \[Rightname]
name[x, y]
name[x]
name[x, y, ... ]
The conventional correspondence in Mathematica between operator names and function names.
You should realize that even though the functions CirclePlus and CircleTimes do not have
built-in evaluation rules, the operators K and L do have built-in precedences. Pages 10241029 list all
the operators recognized by Mathematica, in order of their precedence.
The operators g and O have definite
precedenceswith g higher than O.
xy
Subscript[x, y]
x
SubPlus[x]
x
SubMinus[x]
x[
SubStar[x]
x
SuperPlus[x]
x
SuperMinus[x]
x[
SuperStar[x]
SuperDagger[x]
In[7]:= x y z // FullForm
Out[7]//FullForm= Mod
Plus
z, CircleTimes
x, y, 2
Overscript[x, y]
Underscript[x, y]
N
x
=
x
K
x
f
x
xL
x
N
OverBar[x]
OverVector[x]
OverTilde[x]
OverHat[x]
OverDot[x]
UnderBar[x]
In[8]:= x2 y2 InputForm
In[9]:= x2 y2 InputForm
473
In[10]:= x y InputForm
Out[10]//InputForm= SuperDagger[x] + SuperPlus[y]
In[11]:= $
x%
y InputForm
Out[11]//InputForm= OverBar[x] + OverHat[y]
In[2]:= bin[i + j, k]
Out[2]=
Format[expr ] := expr
Format[expr , form] := expr
ij
k
In[3]:= FullForm[%]
Out[3]//FullForm= bin
Plus
i, j, k
By making definitions for Format, you can tell Mathematica to format a particular expression so as
to look like another expression. You can also tell Mathematica to run a program to determine how a
particular expression should be formatted.
This specifies that Mathematica should
run a simple program to determine
how xrep objects should be formatted.
Out[6]= x x4 x9
474
Prefix[f [x], h]
prefix form h x
Postfix[f [x], h]
postfix form x h
In[9]:= s^2
Out[7]= ?> x
Out[8]= abc
Out[9]= abc
When you have an output form involving operators, the question arises of whether the arguments of some of them should be parenthesized. As discussed in Section 2.1.3, this depends on the
precedence of the operators. When you set up output forms involving operators, you can use
PrecedenceForm to specify the precedence to assign to each operator. Mathematica uses integers from
1 to 1000 to represent precedence levels. The higher the precedence level for an operator, the less it
needs to be parenthesized.
Here is treated as an operator with
precedence 100. This precedence turns
out to be low enough that parentheses
are inserted.
Out[10]= abc
When you make an assignment for Format[expr], you are defining the output format for expr in all
standard types of Mathematica output. By making definitions for Format[expr, form], you can specify
formats to be used in specific output forms.
This specifies the TeXForm for the
symbol x.
475
Out[2]= HoldComplete 2 2
Built into Mathematica are a large number of rules for generating output and interpreting input. Particularly in StandardForm , these rules are carefully set up to be consistent, and to allow input and
output to be used interchangeably.
It is fairly rare that you will need to modify these rules. The main reason is that Mathematica
already has built-in rules for the input and output of many operators to which it does not itself assign
specific meanings.
Thus, if you want to add, for example, a generalized form of addition, you can usually just use an
operator like K for which Mathematica already has built-in input and output rules.
This outputs using the O operator.
In[3]:= CirclePlus[u, v, w]
Out[3]= u O v O w
In[4]:= u v w // FullForm
Out[4]//FullForm= CirclePlus
u, v, w
In dealing with output, you can make definitions for Format[expr] to change the way that a particular expression will be formatted. You should realize, however, that as soon as you do this, there
is no guarantee that the output form of your expression will be interpreted correctly if it is given as
Mathematica input.
If you want to, Mathematica allows you to redefine the basic rules that it uses for the input and
output of all expressions. You can do this by making definitions for MakeBoxes and MakeExpression .
You should realize, however, that unless you make such definitions with great care, you are likely to
end up with inconsistent results.
This defines how gplus objects should
be output in StandardForm .
476
In[7]:= a mn b
Out[6]= a Omn b
Syntax::sntxi:
Incomplete expression; more input is needed.
When you give definitions for MakeBoxes , you can think of this as essentially a lower-level version
of giving definitions for Format. An important difference is that MakeBoxes does not evaluate its
argument, so you can define rules for formatting expressions without being concerned about how
these expressions would evaluate.
In addition, while Format is automatically called again on any results obtained by applying it, the
same is not true of MakeBoxes . This means that in giving definitions for MakeBoxes you explicitly
have to call MakeBoxes again on any subexpressions that still need to be formatted.
477
Printing expressions.
ab
c
1
2
3
4
5
1
4
9
16
25
Print simply takes the arguments you give, and prints them out one after the other, with no spaces
in between. In many cases, you will need to print output in a more complicated format. You can do
this by giving an output form as an argument to Print.
This prints the matrix in the form of a
table.
The output generated by Print is usually given in the standard Mathematica output format. You
can however explicitly specify that some other output format should be used.
This prints output in Mathematica input
form.
You should realize that Print is only one of several mechanisms available in Mathematica for
generating output. Another is the function Message described in Section 2.9.21, used for generating
named messages. There are also a variety of lower-level functions described in Section 2.12.3 which
allow you to produce output in various formats both as part of an interactive session, and for files
and external programs.
478
Mathematica provides many capabilities for manipulating the contents of notebooks, as discussed in
Section 2.11. StylePrint handles the simple case when all you want to do is to add a cell of a
particular style.
Input[ ]
InputString[ ]
Input["prompt"]
InputString["prompt"]
Interactive input.
Exactly how Input and InputString work depends on the computer system and Mathematica interface you are using. With a text-based interface, they typically just wait for standard input, terminated
with a newline. With a notebook interface, however, they typically get the front end to put up a
dialog box, in which the user can enter input.
In general, Input is intended for reading complete Mathematica expressions. InputString , on the
other hand, is for reading arbitrary strings.
2.9.21 Messages
479
2.9.21 Messages
Mathematica has a general mechanism for handling messages generated during computations. Many
built-in Mathematica functions use this mechanism to produce error and warning messages. You can
also use the mechanism for messages associated with functions you write.
The basic idea is that every message has a definite name, of the form symbol::tag. You can use this
name to refer to the message. (The object symbol::tag has head MessageName .)
Off[s::tag]
On[s::tag]
As discussed in Section 1.3.11, you can use On and Off to control the printing of particular messages. Most messages associated with built-in functions are switched on by default. You can use Off
to switch them off if you do not want to see them.
This prints a warning message.
In[1]:= Log[a, b, c]
Log::argt: Log called with 3 arguments; 1 or 2
arguments are expected.
Out[1]= Log a, b, c
In[2]:= Off[Log::argt]
In[3]:= Log[a, b, c]
Out[3]= Log
a, b, c
Although most messages associated with built-in functions are switched on by default, there are
some which are switched off by default, and which you will see only if you explicitly switch them
on. An example is the message General::newsym , discussed in Section 2.7.13, which tells you every
time a new symbol is created.
s::tag
s::tag = string
Messages[s]
Manipulating messages.
The text of a message with the name s::tag is stored simply as the value of s::tag, associated with
the symbol s. You can therefore see the text of a message simply by asking for s::tag. You can set
the text by assigning a value to s::tag.
480
In[5]:= LinearSolve::nosol
Out[5]= Linear equation encountered which has no solution.
Messages are always stored as strings suitable for use with StringForm . When the message is
printed, the appropriate expressions are spliced into it. The expressions are wrapped with HoldForm
to prevent evaluation. In addition, any function that is assigned as the value of the global variable
$MessagePrePrint is applied to the resulting expressions before they are given to StringForm . The
default for $MessagePrePrint is Short.
Most messages are associated directly with the functions that generate them. There are, however,
some general messages, which can be produced by a variety of functions.
If you give the wrong number of arguments to a function F, Mathematica will warn you by printing
a message such as F::argx. If Mathematica cannot find a message named F::argx, it will use the
text of the general message General::argx instead. You can use Off[F::argx] to switch off the
argument count message specifically for the function F. You can also use Off[General::argx] to
switch off all messages that use the text of the general message.
Mathematica prints a message if you
give the wrong number of arguments
to a built-in function.
In[8]:= Sqrt[a, b]
Sqrt::argx:
Sqrt called with 2 arguments; 1 argument is expected.
Out[8]= Sqrt a, b
In[9]:= General::argx
Out[9]= `1` called with `2`
arguments; 1 argument is expected.
If something goes very wrong with a calculation you are doing, it is common to find that the same
warning message is generated over and over again. This is usually more confusing than useful. As a
result, Mathematica keeps track of all messages that are produced during a particular calculation, and
stops printing a particular message if it comes up more than three times. Whenever this happens,
Mathematica prints the message General::stop to let you know. If you really want to see all the
messages that Mathematica tries to print, you can do this by switching off General::stop .
2.9.21 Messages
481
$MessageList
MessageList[n]
In every computation you do, Mathematica maintains a list $MessageList of all the messages that
are produced. In a standard Mathematica session, this list is cleared after each line of output is generated. However, during a computation, you can access the list. In addition, when the nth output line
in a session is generated, the value of $MessageList is assigned to MessageList[n] .
This returns $MessageList , which
gives a list of the messages produced.
In[11]:= InputForm[%]
Out[11]//InputForm= {HoldForm[Sqrt::argx], HoldForm[Exp::argx]}
In writing programs, it is often important to be able to check automatically whether any messages
were generated during a particular calculation. If messages were generated, say as a consequence of
producing indeterminate numerical results, then the result of the calculation may be meaningless.
Check[expr, failexpr]
Out[12]= 1
0
Power::indet: Indeterminate expression 0
Out[13]= err
encountered.
482
Check[expr, failexpr] tests for all messages that are actually printed out. It does not test for
messages whose output has been suppressed using Off.
In some cases you may want to test only for a specific set of messages, say ones associated with
numerical overflow. You can do this by explicitly telling Check the names of the messages you want
to look for.
The message generated by Sin[1, 2]
is ignored by Check, since it is not the
one specified.
Out[14]= Sin 1, 2
Message[s::tag]
Message[s::tag, expr , ... ]
print a message
print a message, with the expri spliced into its string form
Generating messages.
By using the function Message, you can mimic all aspects of the way in which built-in Mathematica
functions generate messages. You can for example switch on and off messages using On and Off, and
Message will automatically look for General::tag if it does not find the specific message s::tag.
This defines the text of a message
associated with f.
In[16]:= f[x_] :=
If[x > 10,
(Message[f::overflow, x]; Infinity), x!]
In[17]:= f[20]
Out[17]=
In[18]:= Off[f::overflow]
In[19]:= f[20]
Out[19]=
When you call Message, it first tries to find a message with the explicit name you have specified.
If this fails, it tries to find a message with the appropriate tag associated with the symbol General. If
this too fails, then Mathematica takes any function you have defined as the value of the global variable
$NewMessage , and applies this function to the symbol and tag of the message you have requested.
By setting up the value of $NewMessage appropriately, you can, for example, get Mathematica to
read in the text of a message from a file when that message is first needed.
483
$Language = "lang"
$Language = {"lang ", "lang ", ... }
In[2]:= Sqrt[a, b, c]
Out[1]= French
Sqrt::argx:
Sqrt est appele avec 3 arguments; il faut y avoir 1.
Out[2]= Sqrt a, b, c
symbol::tag
symbol::tag::Language
When built-in Mathematica functions generate messages, they look first for messages of the form
s::t::Language, in the language specified by $Language . If they fail to find any such messages, then
they use instead the form s::t without an explicit language specification.
The procedure used by built-in functions will also be followed by functions you define if you call
Message with message names of the form s::t. If you give explicit languages in message names,
however, only those languages will be used.
484
(* text *)
Comments in Mathematica.
There is a convention in Mathematica that all functions intended for later use should be given a
definite usage message, which documents their basic usage. This message is defined as the value
of f::usage, and is retrieved when you type ?f.
f::usage = "text"
?f
??f
In[4]:= ?f
f[x] gives the square of x.
In[5]:= ??f
f[x] gives the square of x.
f[x_] := x^2
When you define a function f, you can usually display its value using ?f. However, if you give a
usage message for f, then ?f just gives the usage message. Only when you type ??f do you get all the
details about f, including its actual definition.
485
If you ask for information using ? about just one function, Mathematica will print out the complete
usage messages for the function. If you ask for information on several functions at the same time,
however, Mathematica will just give you the name of each function.
f::usage
f::notes
f::usage::Language, etc.
In addition to the usage message, there are some messages such as notes and qv that are often
defined to document functions.
If you use Mathematica with a text-based interface, then messages and comments are the primary
mechanisms for documenting your definitions. However, if you use Mathematica with a notebook
interface, then you will be able to give much more extensive documentation in text cells in the
notebook.
486
70
60
50
40
30
20
10
5
10
15
20
In[2]:= InputForm[%]
Out[2]//InputForm= Graphics[{Point[{1, 2}], Point[{2, 3}],
Point[{3, 5}], Point[{4, 7}], Point[{5, 11}],
Point[{6, 13}], Point[{7, 17}], Point[{8, 19}],
Point[{9, 23}], Point[{10, 29}], Point[{11, 31}],
Point[{12, 37}], Point[{13, 41}], Point[{14, 43}],
Point[{15, 47}], Point[{16, 53}], Point[{17, 59}],
Point[{18, 61}], Point[{19, 67}], Point[{20, 71}]},
{PlotRange -> Automatic,
AspectRatio -> GoldenRatio^(-1),
DisplayFunction :> $DisplayFunction,
ColorOutput -> Automatic, Axes -> Automatic,
AxesOrigin -> Automatic, PlotLabel -> None,
AxesLabel -> None, Ticks -> Automatic,
GridLines -> None, Prolog -> {}, Epilog -> {},
AxesStyle -> Automatic, Background -> Automatic,
DefaultColor -> Automatic,
DefaultFont :> $DefaultFont, RotateLabel -> True,
Frame -> False, FrameStyle -> Automatic,
FrameTicks -> Automatic, FrameLabel -> None,
PlotRegion -> Automatic, ImageSize -> Automatic,
TextStyle :> $TextStyle, FormatType :> $FormatType}]
Each complete piece of graphics in Mathematica is represented as a graphics object. There are several
different kinds of graphics object, corresponding to different types of graphics. Each kind of graphics
object has a definite head which identifies its type.
Graphics[list]
487
DensityGraphics[list]
density plot
ContourGraphics[list]
contour plot
SurfaceGraphics[list]
three-dimensional surface
Graphics3D[list]
GraphicsArray[list]
The functions like Plot and ListPlot discussed in Section 1.9 all work by building up Mathematica
graphics objects, and then displaying them.
Graphics
DensityGraphics
DensityPlot , ListDensityPlot
ContourGraphics
ContourPlot , ListContourPlot
SurfaceGraphics
Plot3D, ListPlot3D
Graphics3D
ParametricPlot3D
You can create other kinds of graphical images in Mathematica by building up your own graphics objects. Since graphics objects in Mathematica are just symbolic expressions, you can use all the
standard Mathematica functions to manipulate them.
Once you have created a graphics object, you must then display it. The function Show allows you
to display any Mathematica graphics object.
Show[g]
Show[g , g , ... ]
488
In[5]:= InputForm[%]
In[6]:= Show[%]
Graphics directives
Graphics options
Out[4]= AGraphicsA
Out[5]//InputForm=
Graphics[Polygon[{{1., 0.},
{0.8090169943749475, 0.5877852522924731},
{0.30901699437494745, 0.9510565162951535},
{-0.30901699437494745, 0.9510565162951535},
{-0.8090169943749475, 0.5877852522924731}, {-1., 0.}}]]
Given a particular list of graphics primitives, Mathematica provides two basic mechanisms for modifying the final form of graphics you get. First, you can insert into the list of graphics primitives
certain graphics directives, such as RGBColor, which modify the subsequent graphical elements in the
list. In this way, you can specify how a particular set of graphical elements should be rendered.
This takes the list of graphics
primitives created above, and adds the
graphics directive GrayLevel[0.3] .
489
In[8]:= Show[%]
By inserting graphics directives, you can specify how particular graphical elements should be rendered. Often, however, you want to make global modifications to the way a whole graphics object is
rendered. You can do this using graphics options.
By adding the graphics option Frame
you can modify the overall appearance
of the graphics.
0.8
0.6
0.4
0.2
0
-1
-0.5
0.5
In[10]:= InputForm[%]
Out[10]//InputForm=
Graphics[{GrayLevel[0.3],
Polygon[{{1., 0.}, {0.8090169943749475,
0.5877852522924731},
{0.30901699437494745, 0.9510565162951535},
{-0.30901699437494745, 0.9510565162951535},
{-0.8090169943749475, 0.5877852522924731}, {-1., 0.}}
]}, {Frame -> True}]
You can specify graphics options in Show. As a result, it is straightforward to take a single graphics
object, and show it with many different choices of graphics options.
Notice however that Show always returns the graphics objects it has displayed. If you specify
graphics options in Show, then these options are automatically inserted into the graphics objects that
Show returns. As a result, if you call Show again on the same objects, the same graphics options will
be used, unless you explicitly specify other ones. Note that in all cases new options you specify will
overwrite ones already there.
490
Options[g]
Options[g, opt]
AbsoluteOptions[g, opt]
Some graphics options work by requiring you to specify a particular value for a parameter related to
a piece of graphics. Other options allow you to give the setting Automatic , which makes Mathematica
use internal algorithms to choose appropriate values for parameters. In such cases, you can find out
the values that Mathematica actually used by applying the function AbsoluteOptions .
Here is a plot.
1.4
1.2
10
0.8
0.6
FullGraphics[g]
When you use a graphics option such as Axes, Mathematica effectively has to construct a list of
graphics elements to represent the objects such as axes that you have requested. Usually Mathematica
does not explicitly return the list it constructs in this way. Sometimes, however, you may find it useful
491
to get this list. The function FullGraphics gives the complete list of graphics primitives needed to
generate a particular plot, without any options being used.
This plots a list of values.
6
5
4
3
2
10
With their default option settings, functions like Plot and Show actually cause Mathematica to
generate graphical output. In general, the actual generation of graphical output is controlled by
the graphics option DisplayFunction . The default setting for this option is the value of the global
variable $DisplayFunction .
In most cases, $DisplayFunction and the DisplayFunction option are set to use the lower-level
rendering function Display to produce output, perhaps after some preprocessing. Sometimes, however, you may want to get a function like Plot to produce a graphics object, but you may not
immediately want that graphics object actually rendered as output. You can tell Mathematica to generate the object, but not render it, by setting the option DisplayFunction -> Identity. Section 2.10.14
will explain exactly how this works.
492
Out[17]= AGraphicsA
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
0
10
point at position x, y
line through the points {x , y }, {x , y }, ...
filled rectangle
filled polygon with the specified list of corners
circle with radius r centered at x, y
filled disk with radius r centered at x, y
rectangular array of gray levels between 0 and 1
the text of expr, centered at x, y (see
Section 2.10.16)
493
0.5
-0.5
-1
You can combine graphics objects that you have created explicitly from graphics primitives with ones
that are produced by functions like Plot.
This produces an ordinary Mathematica
plot.
0.5
1
-0.5
-1
494
0.5
-0.5
-1
You can combine different graphical elements simply by giving them in a list. In two-dimensional
graphics, Mathematica will render the elements in exactly the order you give them. Later elements are
therefore effectively drawn on top of earlier ones.
Here is a list of two Rectangle
graphics elements.
The Polygon graphics primitive takes a list of x, y coordinates, corresponding to the corners of a
polygon. Mathematica joins the last corner with the first one, and then fills the resulting area.
Here are the coordinates of the corners
of a regular pentagon.
1
1
1
Out[8]=
5 5 , 1 5
,
2
2
4
1
1
1
5 5 , 1 5
,
2
2
4
1
1
1
5 5 , 1 5
,
2
2
4
1
1
1
5 5 , 1 5
, 0, 1
2
2
4
In[11]:= Show[Graphics[
Polygon[ {{-1, -1}, {1, 1}, {1, -1}, {-1, 1}} ] ]]
495
496
Circle[{x, y}, r]
Circle[{x, y}, {rx , ry }]
Circle[{x, y}, r, {theta , theta }]
Circle[{x, y}, {rx , ry }, {theta , theta }]
Disk[{x, y}, r], etc.
Mathematica allows you to generate arcs of circles, and segments of ellipses. In both cases, the
objects are specified by starting and finishing angles. The angles are measured counterclockwise in
radians with zero corresponding to the positive x direction.
This draws a
wedge centered at
the origin.
Here is a
array of values between
0 and 1.
497
498
In the default case, Raster always generates an array of gray cells. As described on page 517, you
can use the option ColorFunction to apply a coloring function to all the cells.
You can also use the graphics primitive RasterArray . While Raster takes an array of values,
RasterArray takes an array of Mathematica graphics directives. The directives associated with each
cell are taken to determine the color of that cell. Typically the directives are chosen from the set
GrayLevel , RGBColor or Hue. By using RGBColor and Hue directives, you can create color rasters
using RasterArray .
499
In[2]:= Show[Graphics[ % ]]
Mathematica provides various kinds of graphics directives. One important set is those for specifying
the colors of graphical elements. Even if you have a black-and-white display device, you can still give
color graphics directives. The colors you specify will be converted to gray levels at the last step in
the graphics rendering process. Note that you can get gray-level display even on a color device by
setting the option ColorOutput -> GrayLevel .
GrayLevel[i]
RGBColor[r, g, b]
Hue[h]
Hue[h, s, b]
Basic Mathematica color specifications.
500
20
15
10
5
The function Hue[h] provides a convenient way to specify a range of colors using just one parameter. As h varies from 0 to 1, Hue[h] runs through red, yellow, green, cyan, blue, magenta, and back
to red again. Hue[h, s, b] allows you to specify not only the hue, but also the saturation and
brightness of a color. Taking the saturation to be equal to one gives the deepest colors; decreasing
the saturation toward zero leads to progressively more washed out colors.
For most purposes, you will be able to specify the colors you need simply by giving appropriate
RGBColor or Hue directives. However, if you need very precise or repeatable colors, particularly for
color printing, there are a number of subtleties which arise, as discussed in Section 2.10.17.
When you give a graphics directive such as RGBColor , it affects all subsequent graphical elements
that appear in a particular list. Mathematica also supports various graphics directives which affect only
specific types of graphical elements.
The graphics directive PointSize[d] specifies that all Point elements which appear in a graphics
object should be drawn as circles with diameter d. In PointSize , the diameter d is measured as a
fraction of the width of your whole plot.
Mathematica also provides the graphics directive AbsolutePointSize[d] , which allows you to
of an inch,
specify the absolute diameter of points, measured in fixed units. The units are
approximately printers points.
PointSize[d]
AbsolutePointSize[d]
501
70
60
50
40
30
20
10
5
Thickness[w]
10
15
20
AbsoluteThickness[w]
Dashing[{w , w , ... }]
AbsoluteDashing[{w , w , ... }]
Graphics directives for lines.
502
In[7]:= Table[
{AbsoluteThickness[n], Line[{{0, 0}, {n, 1}}]}, {n, 4}]
Out[7]= AbsoluteThickness
1,
AbsoluteThickness
2,
AbsoluteThickness
3,
AbsoluteThickness
4,
Line
0,
Line
0,
Line
0,
Line
0,
0,
0,
0,
0,
1,
2,
3,
4,
1,
1,
1,
1
In[8]:= Show[Graphics[%]]
The Dashing graphics directive allows you to create lines with various kinds of dashing. The
basic idea is to break lines into segments which are alternately drawn and omitted. By changing the
lengths of the segments, you can get different line styles. Dashing allows you to specify a sequence
of segment lengths. This sequence is repeated as many times as necessary in drawing the whole line.
This gives a dashed line with a
succession of equal-length segments.
503
One way to use Mathematica graphics directives is to insert them directly into the lists of graphics
primitives used by graphics objects. Sometimes, however, you want the graphics directives to be
applied more globally, and for example to determine the overall style with which a particular type
of graphical element should be rendered. There are typically graphics options which can be set to
specify such styles in terms of lists of graphics directives.
0.4
0.2
2
-0.2
10
504
GrayLevel[0.5]
RGBColor[1, 0, 0], etc.
Thickness[0.05]
Dashing[{0.05, 0.05}]
Dashing[{0.01, 0.05, 0.05, 0.05}]
gray
red, etc.
thick
dashed
dot-dashed
The various style options allow you to specify how particular graphical elements in a plot should
be rendered. Mathematica also provides options that affect the rendering of the whole plot.
Prolog -> g
Epilog -> g
0.75
0.5
0.25
2
-0.25
-0.5
-0.75
10
505
0.75
0.5
0.25
2
10
-0.25
-0.5
-0.75
{x, y}
Scaled[{sx, sy}]
original coordinates
scaled coordinates
40
20
1
-20
-40
506
When you use {x, y} or Scaled[{sx, sy}], you are specifying position either completely in original coordinates, or completely in scaled coordinates. Sometimes, however, you may need to use a
combination of these coordinate systems. For example, if you want to draw a line at a particular point
whose length is a definite fraction of the width of the plot, you will have to use original coordinates
to specify the basic position of the line, and scaled coordinates to specify its length.
You can use Scaled[{dsx, dsy}, {x, y}] to specify a position using a mixture of original and
scaled coordinates. In this case, {x, y} gives a position in original coordinates, and {dsx, dsy} gives
the offset from the position in scaled coordinates.
Note that you can use Scaled with either one or two arguments to specify radii in Disk and
Circle graphics elements.
In[2]:= Show[Graphics[Table[
Line[{{x, x^2}, Offset[{0, 6}, {x, x^2}]}],
{x, 10}], Frame->True]]
100
80
60
40
20
0
0
10
507
In[3]:= Show[Graphics[Table[
Circle[{x, x^2}, Offset[{2, 2}]],
{x, 10}], Frame->True]]
100
80
60
40
20
0
0
10
In most kinds of graphics, you typically want the relative positions of different objects to adjust
automatically when you change the coordinates or the overall size of your plot. But sometimes you
may instead want the offset from one object to another to be constrained to remain fixed. This can be
the case, for example, when you are making a collection of plots in which you want certain features
to remain consistent, even though the different plots have different forms.
Offset[{adx, ady}, position] allows you to specify the position of an object by giving an absolute
offset from a position that is specified in original or scaled coordinates. The units for the offset are
printers points, equal to
of an inch.
When you give text in a plot, the size of the font that is used is also specified in printers points.
A 10-point font, for example, therefore has letters whose basic height is 10 printers points. You can
use Offset to move text around in a plot, and to create plotting symbols or icons which match the
size of text.
When Mathematica renders a graphics object, one of the first things it has to do is to work out
what range of original x and y coordinates it should actually display. Any graphical elements that are
outside this range will be clipped, and not shown.
The option PlotRange specifies the range of original coordinates to include. As discussed on
page 136, the default setting is PlotRange -> Automatic , which makes Mathematica try to choose
a range which includes all interesting parts of a plot, while dropping outliers. By setting
508
PlotRange -> All, you can tell Mathematica to include everything. You can also give explicit ranges
of coordinates to include.
This sets up a polygonal object whose
corners have coordinates between
roughly M.
In[5]:= Show[Graphics[obj]]
The option PlotRange allows you to specify a rectangular region in the original coordinate system,
and to drop any graphical elements that lie outside this region. In order to render the remaining
elements, however, Mathematica then has to determine how to position this rectangular region with
respect to the final display area.
509
The option PlotRegion allows you to specify where the corners of the rectangular region lie within
the final display area. The positions of the corners are specified in scaled coordinates, which are
defined to run from 0 to 1 across the display area. The default is PlotRegion -> {{0, 1}, {0, 1}},
which specifies that the rectangular region should fill the whole display area.
By specifying PlotRegion , you can
effectively add margins around your
plot.
1.4
1.2
1
0.8
0.6
0.4
0.2
2
AspectRatio -> r
AspectRatio -> Automatic
8 10
make the ratio of height to width for the display area equal
to r
determine the shape of the display area from the original
coordinate system
What we have discussed so far is how Mathematica translates the original coordinates you specify
into positions in the final display area. What remains to discuss, however, is what the final display
area is like.
On most computer systems, there is a certain fixed region of screen or paper into which the Mathematica display area must fit. How it fits into this region is determined by its shape or aspect ratio.
In general, the option AspectRatio specifies the ratio of height to width for the final display area.
It is important to note that the setting of AspectRatio does not affect the meaning of the scaled
or display coordinates. These coordinates always run from 0 to 1 across the display area. What
AspectRatio does is to change the shape of this display area.
This generates a graphic object
corresponding to a hexagon.
510
For two-dimensional graphics, AspectRatio is set by default to the fixed value of 1/GoldenRatio .
Sometimes, however, you may want to determine the aspect ratio for a plot from the original coordinate system used in the plot. Typically what you want is for one unit in the x direction in the
original coordinate system to correspond to the same distance in the final display as one unit in the
y direction. In this way, objects that you define in the original coordinate system are displayed with
their natural shape. You can make this happen by setting the option AspectRatio -> Automatic .
With AspectRatio -> Automatic , the
aspect ratio of the final display area is
determined from the original
coordinate system, and the hexagon is
shown with its natural shape.
Using scaled coordinates, you can specify the sizes of graphical elements as fractions of the size of
the display area. You cannot, however, tell Mathematica the actual physical size at which a particular
graphical element should be rendered. Of course, this size ultimately depends on the details of your
graphics output device, and cannot be determined for certain within Mathematica. Nevertheless, graphics directives such as AbsoluteThickness discussed on page 501 do allow you to indicate absolute
sizes to use for particular graphical elements. The sizes you request in this way will be respected by
most, but not all, output devices. (For example, if you optically project an image, it is neither possible
nor desirable to maintain the same absolute size for a graphical element within it.)
511
0.4
0.2
10
-0.2
0.4
0.2
-0.2
0
10
0.4
0.2
-0.2
0
10
512
draw no axes
draw both x and y axes
draw a y axis but no x axis
choose the crossing point for the axes automatically
specify the crossing point
specify the style for axes
specify individual styles for axes
y
0.4
0.2
10
-0.2
With the default setting Ticks -> Automatic , Mathematica creates a certain number of major and
minor tick marks, and places them on axes at positions which yield the minimum number of decimal
digits in the tick labels. In some cases, however, you may want to specify the positions and properties
of tick marks explicitly. You will need to do this, for example, if you want to have tick marks at
multiples of , or if you want to put a nonlinear scale on an axis.
None
Automatic
513
{x , x , ... }
0.4
0.2
Pi
2 Pi
3 Pi
-0.2
In[6]:= Show[bp,
Ticks -> {{0, {Pi/2, ""}, Pi, {3Pi/2, ""},
2Pi, {5Pi/2, ""}, 3Pi}, Automatic}]
0.4
0.2
Pi
-0.2
2 Pi
3 Pi
514
Particularly when you want to create complicated tick mark specifications, it is often convenient to
define a tick mark function which creates the appropriate tick mark specification given the minimum
and maximum values on a particular axis.
This defines a function which gives a
list of tick mark positions with a
spacing of 1.
0.4
0.2
10
-0.2
Sometimes you may want to generate tick marks which differ only slightly from those produced
automatically with the setting Ticks -> Automatic . You can get the complete specification for tick
marks that were generated automatically in a particular plot by using AbsoluteOptions[g, Ticks],
as discussed on page 490.
draw no frame
draw a frame around the plot
specify a style for the frame
515
The Axes option allows you to draw a single pair of axes in a plot. Sometimes, however, you may
instead want to show the scales for a plot on a frame, typically drawn around the whole plot. The
option Frame allows you effectively to draw four axes, corresponding to the four edges of the frame
around a plot. These four axes are ordered clockwise, starting from the one at the bottom.
This draws frame axes, and labels each
of them.
0.2
label 4
label 2
0.4
0
-0.2
0
6
label 1
10
Grid lines in Mathematica work very much like tick marks. As with tick marks, you can specify
explicit positions for grid lines. There is no label or length to specify for grid lines. However, you
can specify a style.
This generates x but not y grid lines.
0.4
0.2
2
-0.2
10
516
4
2
0
-2
-4
2
1
0
-4
-2
-1
0
2
4
-2
4
2
0
-2
-4
-4
4
2
0
-2
-4
2
1
0
-4
-2
-1
0
2
4
-2
2
1
-2
0
-1
4 -2
517
Mathematica can render any graphics object within a Rectangle . In all cases, what it puts in the
rectangle is a scaled down version of what would be obtained if you displayed the graphics object on
its own. Notice that in general the display area for the graphics object will be sized so as to touch at
least one pair of edges of the rectangle.
density plot
ContourGraphics[array]
contour plot
The functions DensityPlot and ContourPlot discussed in Section 1.9.5 work by creating
ContourGraphics and DensityGraphics objects containing arrays of values.
Most of the options for density and contour plots are the same as those for ordinary two-dimensional
plots. There are, however, a few additional options.
option name
default value
ColorFunction
Automatic
ColorFunctionScaling
True
Mesh
True
MeshStyle
Automatic
In a density plot, the color of each cell represents its value. By default, each cell is assigned a
gray level, running from black to white as the value of the cell increases. In general, however, you
can specify other color maps for the relation between the value of a cell and its color. The option
ColorFunction allows you to specify a function which is applied to each cell value to find the color
of the cell. With ColorFunctionScaling->True the cell values are scaled so as to run between 0 and
1 in a particular density plot; with ColorFunctionScaling->False no such scaling is performed. The
function you give as the setting for ColorFunction may return any Mathematica color directive, such
as GrayLevel , Hue or RGBColor . A common setting to use is ColorFunction -> Hue.
518
0.5
-0.5
-1
-1
-0.5
0.5
0.5
-0.5
-1
-1
-0.5
0.5
519
option name
default value
Contours
10
ContourLines
True
ContourStyle
Automatic
ContourShading
True
ColorFunction
Automatic
ColorFunctionScaling
True
In constructing a contour plot, the first issue is what contours to use. With the default setting
Contours -> 10, Mathematica uses a sequence of 10 contour levels equally spaced between the minimum and maximum values defined by the PlotRange option.
Contours -> n
Contours -> {z , z , ... }
Specifying contours.
0.5
-0.5
-1
-1
-0.5
0.5
520
There are some slight subtleties associated with labeling density and contour plots. Both the Axes
and Frame options from ordinary two-dimensional graphics can be used. But setting
AxesOrigin -> Automatic keeps the axes outside the plot in both cases.
Point[{x, y, z}]
Line[{{x , y , z }, {x , y , z }, ... }]
Polygon[{{x , y , z }, {x , y , z }, ... }]
Cuboid[{xmin, ymin, zmin}, {xmax, ymax, zmax}]
Text[expr, {x, y, z}]
521
If you give a list of graphics elements in two dimensions, Mathematica simply draws each element
in turn, with later elements obscuring earlier ones. In three dimensions, however, Mathematica collects
together all the graphics elements you specify, then displays them as three-dimensional objects, with
the ones in front in three-dimensional space obscuring those behind.
Every time you evaluate rantri, it
generates a random triangle in
three-dimensional space.
522
By creating an appropriate list of polygons, you can build up any three-dimensional object in Mathematica. Thus, for example, all the surfaces produced by ParametricPlot3D are represented simply as
lists of polygons.
The package Graphics`Polyhedra` contains examples of lists of polygons which correspond to
polyhedra in three dimensions.
This loads a package which defines
various polyhedra.
In[8]:= <<Graphics`Polyhedra`
In[9]:= Tetrahedron[ ]
Dodecahedron[ ] is another
three-dimensional object defined in the
polyhedra package.
Out[9]= Polygon
0., 0., 1.73205, 0., 1.63299, 0.57735,
1.41421, 0.816497, 0.57735,
Polygon
0., 0., 1.73205, 1.41421, 0.816497,
0.57735, 1.41421, 0.816497, 0.57735,
Polygon
0., 0., 1.73205, 1.41421, 0.816497,
0.57735, 0., 1.63299, 0.57735,
Polygon
0., 1.63299, 0.57735,
1.41421, 0.816497, 0.57735,
1.41421, 0.816497, 0.57735
523
524
Mathematica allows polygons in three dimensions to have any number of vertices. However, these
vertices should lie in a plane, and should form a convex figure. If they do not, then Mathematica will
break the polygon into triangles, which are planar by definition, before rendering it.
Cuboid[{x, y, z}]
525
526
For Point and Line objects, the color specification directives also work the same in three dimensions
as in two dimensions. For Polygon objects, however, they can work differently.
In two dimensions, polygons are always assumed to have an intrinsic color, specified directly by
graphics directives such as RGBColor . In three dimensions, however, Mathematica also provides the
option of generating colors for polygons using a more physical approach based on simulated illumination. With the default option setting Lighting -> True for Graphics3D objects, Mathematica ignores
explicit colors specified for polygons, and instead determines all polygon colors using the simulated
illumination model. Even in this case, however, explicit colors are used for points and lines.
intrinsic colors
colors based on simulated illumination (default)
In[5]:= <<Graphics`Polyhedra`
527
528
EdgeForm[ ]
EdgeForm[g]
When you render a three-dimensional graphics object in Mathematica, there are two kinds of lines
that can appear. The first kind are lines from explicit Line primitives that you included in the graphics
object. The second kind are lines that were generated as the edges of polygons.
You can tell Mathematica how to render all lines of the second kind by giving a list of graphics
directives inside EdgeForm .
This renders a dodecahedron with its
edges shown as thick gray lines.
In[9]:= Show[Graphics3D[
{EdgeForm[{GrayLevel[0.5], Thickness[0.02]}],
Dodecahedron[ ]}]]
FaceForm[gfront, gback]
529
An important aspect of polygons in three dimensions is that they have both front and back faces.
Mathematica uses the following convention to define the front face of a polygon: if you look at a
polygon from the front, then the corners of the polygon will appear counterclockwise, when taken in
the order that you specified them.
This defines a dodecahedron with one
face removed.
In[11]:= Show[Graphics3D[d]]
In[12]:= Show[Graphics3D[
{FaceForm[GrayLevel[0.8], GrayLevel[0.3]], d}],
Lighting -> False]
530
In[1]:= <<Graphics`Polyhedra`
1
0
-1
-1
-1
0
1
1
0.5
0
-0.5
-1
0
-1
0
-1
1
531
Much as in two dimensions, you can use either original or scaled coordinates to specify the positions of elements in three-dimensional objects. Scaled coordinates, specified as Scaled[{sx, sy, sz}]
are taken to run from 0 to 1 in each dimension. The coordinates are set up to define a right-handed
coordinate system on the box.
{x, y, z}
Scaled[{sx, sy, sz}]
original coordinates
scaled coordinates, running from 0 to 1 in each dimension
In[5]:= Show[Graphics3D[{stel,
Cuboid[Scaled[{0, 0, 0}],
Scaled[{0.2, 0.2, 0.2}]]}]]
Once you have specified where various graphical elements go inside a three-dimensional box, you
must then tell Mathematica how to draw the box. The first step is to specify what shape the box should
be. This is analogous to specifying the aspect ratio of a two-dimensional plot. In three dimensions, you
can use the option BoxRatios to specify the ratio of side lengths for the box. For Graphics3D objects,
the default is BoxRatios -> Automatic , specifying that the shape of the box should be determined
from the ranges of actual coordinates for its contents.
532
To produce an image of a three-dimensional object, you have to tell Mathematica from what view
point you want to look at the object. You can do this using the option ViewPoint .
Some common settings for this option were given on page 153. In general, however, you can tell
Mathematica to use any view point, so long as it lies outside the box.
View points are specified in the form ViewPoint -> {sx, sy, sz}. The values si are given in a
special coordinate system, in which the center of the box is {0, 0, 0}. The special coordinates are
scaled so that the longest side of the box corresponds to one unit. The lengths of the other sides
of the box in this coordinate system are determined by the setting for the BoxRatios option. For a
cubical box, therefore, each of the special coordinates runs from to across the box. Note that
the view point must always lie outside the box.
This generates a picture using the
default view point {1.3, -2.4, 2}.
2
z
-2
-2
0
-1
0
x
-2
1
2
533
2
z
0
-2
-2
-2
-1
y
1
2
2
2
0
-2
-2
-2
-1
y
2
2
option name
default value
ViewPoint
{1.3, -2.4, 2}
ViewCenter
Automatic
ViewVertical
{0, 0, 1}
534
In making a picture of a three-dimensional object you have to specify more than just where you
want to look at the object from. You also have to specify how you want to frame the object in your
final image. You can do this using the additional options ViewCenter and ViewVertical .
ViewCenter allows you to tell Mathematica what point in the object should appear at the center of
your final image. The point is specified by giving its scaled coordinates, running from 0 to 1 in each
direction across the box. With the setting ViewCenter -> {1/2, 1/2, 1/2}, the center of the box will
therefore appear at the center of your final image. With many choices of view point, however, the box
will not appear symmetrical, so this setting for ViewCenter will not center the whole box in the final
image area. You can do this by setting ViewCenter -> Automatic .
ViewVertical specifies which way up the object should appear in your final image. The setting
for ViewVertical gives the direction in scaled coordinates which ends up vertical in the final image. With the default setting ViewVertical -> {0, 0, 1}, the z direction in your original coordinate
system always ends up vertical in the final image.
With this setting for ViewCenter , a
corner of the box appears in the center
of your image.
0
-2
2
z 0
-2
-2
-1
0
x
y
0
-2
2
0 x
-1
-
0
2 z
-2
-2
535
When you set the options ViewPoint , ViewCenter and ViewVertical , you can think about it
as specifying how you would look at a physical object. ViewPoint specifies where your head is
relative to the object. ViewCenter specifies where you are looking (the center of your gaze). And
ViewVertical specifies which way up your head is.
In terms of coordinate systems, settings for ViewPoint , ViewCenter and ViewVertical specify
how coordinates in the three-dimensional box should be transformed into coordinates for your image
in the final display area.
For some purposes, it is useful to think of the coordinates in the final display area as three dimensional. The x and y axes run horizontally and vertically, respectively, while the z axis points out
of the page. Positions specified in this display coordinate system remain fixed when you change
ViewPoint and so on. The positions of light sources discussed in the next section are defined in this
display coordinate system.
Once you have obtained a two-dimensional image of a three-dimensional object, there are still some
issues about how this image should be rendered. The issues however are identical to those that occur
for two-dimensional graphics. Thus, for example, you can modify the final shape of your image by
changing the AspectRatio option. And you specify what region of your whole display area your
image should take up by setting the PlotRegion option.
This modifies the aspect ratio of the
final image.
536
Mathematica usually scales the images of three-dimensional objects to be as large as possible, given
the display area you specify. Although in most cases this scaling is what you want, it does have the
consequence that the size at which a particular three-dimensional object is drawn may vary with the
orientation of the object. You can set the option SphericalRegion -> True to avoid such variation.
With this option setting, Mathematica effectively puts a sphere around the three-dimensional bounding
box, and scales the final image so that the whole of this sphere fits inside the display area you specify.
The sphere has its center at the center of the bounding box, and is drawn so that the bounding box
just fits inside it.
This draws a rather elongated version
of the plot.
-2
2
z
0
-2
-2
2
-1
2
y
-2
2
0
-2
-2 -1
x
0 1
2
By setting SphericalRegion -> True, you can make the scaling of an object consistent for all
orientations of the object. This is useful if you create animated sequences which show a particular
object in several different orientations.
537
Graphics3D[primitives]
SurfaceGraphics[array]
Here is a
array of values.
538
In[2]:= Show[SurfaceGraphics[moda]]
Graphics3D[surface]
6
2
4
2
0
-2
0
-1
-1
0
1
2 -2
539
6
2
4
2
0
-2
0
-1
-1
0
1
2 -2
6
4
0
-2
0
-1
-1
0
1
2
-2
option name
default value
Mesh
True
MeshStyle
Automatic
MeshRange
Automatic
540
When you create a surface using SurfaceGraphics , the default is to draw a rectangular mesh on
the surface. As discussed on page 154, including this mesh typically makes it easier for one to see the
shape of the surface. You can nevertheless get rid of the mesh by setting the option Mesh -> False.
You can also set the option MeshStyle to a list of graphics directives which specify thickness, color or
other properties of the mesh lines.
A SurfaceGraphics object contains an array of values which specify the height of a surface at
points in an x, y grid. By setting the option MeshRange , you can give the range of original x and y
coordinates that correspond to the points in this grid. When you use
Plot3D[f, {x, xmin, xmax}, {y, ymin, ymax}] to generate a SurfaceGraphics object, the setting
MeshRange -> {{xmin, xmax}, {ymin, ymax}} is automatically generated. The setting for MeshRange
is used in labeling the x and y axes in surface plots, and in working out polygon coordinates if you
convert a SurfaceGraphics object to an explicit list of polygons in a Graphics3D object.
None
Automatic
leave out clipped parts of the surface, so that you can see
through
show the clipped part of the surface with the same shading
as an actual surface in the same position would have
(default setting)
The option PlotRange works for SurfaceGraphics as it does for other Mathematica graphics objects. Any parts of a surface that lie outside the range of coordinates defined by PlotRange will be
clipped. The option ClipFill allows you to specify what should happen to the parts of a surface
that are clipped.
541
0.4
0.2
0
-0.2
-0.4
0
1
2
30
0.4
0.2
0
-0.2
-0.4
0
1
2
30
0.4
0.2
0
-0.2
-0.4
0
1
2
30
542
Whenever Mathematica draws a surface, it has to know not only the height, but also the color of the
surface at each point. With the default setting Lighting -> True, Mathematica colors the surface using
a simulated lighted model. However, with Lighting -> False, Mathematica uses a color function
to determine how to color the surface.
The default color function takes the height of the surface, normalized to run from 0 to 1, and colors
each part of the surface with a gray level corresponding to this height. There are two ways to change
the default.
First, if you set the option ColorFunction -> c, then Mathematica will apply the function c to each
height value to determine the color to use at that point. With ColorFunction -> Hue, Mathematica
will for example color the surface with a range of hues.
0.6
0.4
1
0.2
0
-2
0
-1
-1
0
1
2 -2
In[10]:= stripes[f_] :=
If[Mod[f, 1] > 0.5, GrayLevel[1], GrayLevel[0]]
543
0.6
0.4
1
0.2
0
-2
0
-1
-1
0
1
2 -2
The second way to change the default coloring of surfaces is to supply an explicit second array
along with the array of heights. ColorFunction is then applied to the elements of this second array,
rather than the array of heights, to find the color directives to use. In the second array, you can
effectively specify the value of another coordinate for each point on the surface. This coordinate will
be plotted using color, rather than position.
You can generate an array of color values automatically using Plot3D[{f, s}, ... ]. If you give the
array explicitly in ListPlot3D or SurfaceGraphics , you should realize that with an n n array of
heights, you need an n n array to specify colors. The reason is that the heights are specified
for points on a grid, whereas the colors are specified for squares on the grid.
When you supply a second function or array to Plot3D, ListPlot3D , and so on, the default setting
for the ColorFunction option is Automatic . This means that the function or array should contain
explicit Mathematica color directives, such as GrayLevel or RGBColor. However, if you give another
setting, such as ColorFunction -> Hue, then the function or array can yield pure numbers or other
data which are converted to color directives when the function specified by ColorFunction is applied.
544
1
0.75
0.5
0.25
0
0
1
2
30
10
6
2
4
4
6
2
8
10
545
The default lighting used by Mathematica involves three point light sources, and no ambient component. The light sources are colored respectively red, green and blue, and are placed at
angles
on the right-hand side of the object.
Here is a surface, shaded using
simulated lighting using the default set
of lights.
1
0.5
0
-0.5
-1
0
-2
0
-2
2
1
0.5
0
-0.5
-1
0
-2
0
-2
2
546
In[3]:= Show[%,
LightSources -> {{{-1, 0, 0.5}, GrayLevel[0.5]}}]
1
0.5
0
-0.5
-1
0
-2
0
-2
2
The positions of light sources in Mathematica are specified in the display coordinate system. The x
and y coordinates are in the plane of the final display, and the z coordinate comes out of the plane.
Using this coordinate system ensures that the light sources remain fixed with respect to the viewer,
even when the relative positions of the viewer and object change.
Even though the view point is
changed, the light source is kept fixed
on the left-hand side of the image.
-2
-2
1
0.5
0
-0.5
5
-1
1
The perceived color of a polygon depends not only on the light which falls on the polygon, but also
on how the polygon reflects that light. You can use the graphics directive SurfaceColor to specify
the way that polygons reflect light.
If you do not explicitly use SurfaceColor directives, Mathematica effectively assumes that all polygons have matte white surfaces. Thus the polygons reflect light of any color incident on them, and do
so equally in all directions. This is an appropriate model for materials such as uncoated white paper.
547
Using SurfaceColor , however, you can specify more complicated models. The basic idea is to
distinguish two kinds of reflection: diffuse and specular.
In diffuse reflection, light incident on a surface is scattered equally in all directions. When this kind
of reflection occurs, a surface has a dull or matte appearance. Diffuse reflectors obey Lamberts
Law of light reflection, which states that the intensity of reflected light is cos times the intensity of
the incident light, where is the angle between the incident light direction and the surface normal
vector. Note that when c , there is no reflected light.
In specular reflection, a surface reflects light in a mirror-like way. As a result, the surface has a
shiny or gloss appearance. With a perfect mirror, light incident at a particular angle is reflected at
exactly the same angle. Most materials, however, scatter light to some extent, and so lead to reflected
light that is distributed over a range of angles. Mathematica allows you to specify how broad the
distribution is by giving a specular exponent, defined according to the Phong lighting model. With
specular exponent n, the intensity of light at an angle away from the mirror reflection direction is
assumed to vary like cosn . As n # , therefore, the surface behaves like a perfect mirror. As n
decreases, however, the surface becomes less shiny, and for n , the surface is a completely diffuse
reflector. Typical values of n for actual materials range from about 1 to several hundred.
Most actual materials show a mixture of diffuse and specular reflection. In addition, they typically
behave as if they have a certain intrinsic color. When the incident light is white, the reflected light has
the color of the material. When the incident light is not white, each color component in the reflected
light is a product of the corresponding component in the incident light and in the intrinsic color of
the material.
In Mathematica, you can specify reflection properties by giving an intrinsic color associated with
diffuse reflection, and another one associated with specular reflection. To get no reflection of a particular kind, you must give the corresponding intrinsic color as black, or GrayLevel[0] . For materials
that are effectively white, you can specify intrinsic colors of the form GrayLevel[a] , where a is the
reflectance or albedo of the surface.
SurfaceColor[GrayLevel[a]]
SurfaceColor[RGBColor[r, g, b]]
SurfaceColor[diff, spec]
SurfaceColor[diff, spec, n]
In[5]:= <<Graphics`Shapes`
548
In[6]:= s = Sphere[ ] ;
In[7]:= Show[Graphics3D[s]]
In[8]:= Show[Graphics3D[{
SurfaceColor[GrayLevel[0.2],
GrayLevel[0.8], 5], s}]]
When you set up light sources and surface colors, it is important to make sure that the total
intensity of light reflected from a particular polygon is never larger than 1. You will get strange effects
if the intensity is larger than 1.
549
In[1]:= <<Graphics`Polyhedra`
1
0.5
0
-0.5
-1
0.5
0
-0.5
-1
-0.5
0
0.5
1
550
1
0.5
0
-0.5
-1
0.5
0
-0.5
-1
-0.5
0
0.5
1
1
0.5
0
-0.5
-1
0.5
0
-0.5
-1
-0.5
0
0.5
1
551
By setting the option Axes -> True, you tell Mathematica to draw axes on the edges of the threedimensional box. However, for each axis, there are in principle four possible edges on which it can
be drawn. The option AxesEdge allows you to specify on which edge to draw each of the axes.
None
Automatic
{diri , dirj }
-1
-0.5
0.5
1
0.5
0
-0.5
When you draw the x axis on a three-dimensional box, there are four possible edges on which the
axis can be drawn. These edges are distinguished by having larger or smaller y and z coordinates.
When you use the specification {diry , dirz } for where to draw the x axis, you can set the diri to be +1
or -1 to represent larger or smaller values for the y and z coordinates.
552
You can give the same kind of tick mark specifications in three dimensions as were described for
two-dimensional graphics in Section 2.10.5.
553
Mathematica allows you to draw grid lines on the faces of the box that surrounds a threedimensional object. If you set FaceGrids -> All, grid lines are drawn in gray on every face. By
setting FaceGrids -> {face , face , ... } you can tell Mathematica to draw grid lines only on specific
faces. Each face is specified by a list {dirx , diry , dirz }, where two of the diri must be 0, and the third
one is +1 or -1. For each face, you can also explicitly tell Mathematica where and how to draw the grid
lines, using the same kind of specifications as you give for the GridLines option in two-dimensional
graphics.
This draws grid lines only on the top
and bottom faces of the box.
554
default setting
generate no display
apply f to graphics objects to produce display
Within the Mathematica kernel, graphics are always represented by graphics objects involving graphics primitives. When you actually render graphics, however, they must be converted to a lower-level
form which can be processed by a Mathematica front end, such as a notebook interface, or by other
external programs.
The standard low-level form that Mathematica uses for graphics is PostScript. The Mathematica function Display takes any Mathematica graphics object, and converts it into a block of PostScript code. It
can then send this code to a file, an external program, or in general any output stream.
Display["file", graphics]
Display["!program", graphics]
Display[stream, graphics]
DisplayString[graphics]
555
With the standard two-dimensional graphics primitives in Mathematica you can produce most of
the effects that can be obtained with PostScript. Sometimes, however, you may find it necessary to
give PostScript code directly. You can do this using the special two-dimensional graphics primitive
PostScript .
The strings you specify in the PostScript primitive will be inserted verbatim into the final PostScript code generated by Display. You should use the PostScript primitive with care. For example,
it is crucial that the code you give restores the PostScript stack to exactly its original state when it
is finished. In addition, to specify positions of objects, you will have to understand the coordinate
scaling that Mathematica does in its PostScript output. Finally, any PostScript primitives that you insert
can only work if they are supported in the final PostScript interpreter that you use to display your
graphics.
The PostScript primitive gives raw
PostScript code which draws a Bezier
curve.
In[1]:= Show[Graphics[ {
PostScript[".008 setlinewidth"],
PostScript[".1 .1 moveto"],
PostScript["1.1 .6 -.1 .6 .9 .1 curveto stroke"] },
Frame -> True]]
1
0.8
0.6
0.4
0.2
0
0
0.2
0.4
0.6
0.8
In most cases, a particular Mathematica graphics object always generates PostScript of a particular
form. For Graphics3D objects, the option RenderAll allows you to choose between two different
forms.
The main issue is how the polygons which make up three-dimensional objects should be rendered.
With the default setting RenderAll -> True, all polygons you specify are drawn in full, but those
behind are drawn first. When all the polygons are drawn, only those in front are visible. However,
while an object is being drawn on a display, you can typically see the polygons inside it.
The problem with this approach is that for an object with many layers, you may generate a large
amount of spurious PostScript code associated with polygons that are not visible in the final image.
You can potentially avoid this by setting RenderAll -> False. In this case, Mathematica works out
exactly which polygons or parts of polygons will actually be visible in your final image, and renders
556
only these. So long as there are fairly few intersections between polygons, this approach will typically
yield less PostScript code, though it may be much slower.
When you generate a PostScript representation of a three-dimensional object, you lose all information about the depths of the parts of the object. Sometimes, you may want to send to external
programs a representation which includes depth information. Often, the original Graphics3D object in
Mathematica form is then the appropriate representation. But some external programs cannot handle
intersecting polygons. To deal with this, Graphics3D includes the option PolygonIntersections . If
you set PolygonIntersections -> False, then Show will return not your original Graphics3D object,
but rather one in which intersecting polygons have been broken into disjoint pieces, at least with the
setting for ViewPoint and so on that you have given.
Sin
x2
1
0.8
0.6
0.4
0.2
557
Sin
x2
1
0.8
0.6
0.4
0.2
Sinx
1
0.8
0.6
0.4
0.2
1
558
"style"
FontSize -> n
FontSlant -> "Italic"
If you use the standard notebook front end for Mathematica, then you can set $TextStyle or TextStyle
to be the name of a cell style in your current notebook. This tells Mathematica to use that cell style as
the default for formatting any text that appears in graphics.
You can also explicitly specify how text should be formatted by using options such as FontSize
and FontFamily . Note that FontSize gives the absolute size of the font to use, measured in units
of printers points, with one point being
inches. If you resize a plot, the text in it will not by
default change size: to get text of a different size you must explicitly specify a new value for the
FontSize option.
StyleForm[expr, "style"]
StyleForm[expr, options]
TraditionalForm[expr]
Sinx
1
0.8
0.6
0.4
0.2
1
559
Sinx
1
0.8
0.6
0.4
0.2
1
sin2 x
1
0.8
0.6
0.4
0.2
1
You should realize that the ability to refer to cell styles such as "Section" depends on using the
standard Mathematica notebook front end. Even if you are just using a text-based interface to Mathematica, however, you can still specify formatting of text in graphics using options such as FontSize.
The complete collection of options that you can use is given on page 612.
560
Two-dimensional text.
In[1]:= Show[Graphics[
Table[ Text[Expand[(1 + x)^n], {n, n}], {n, 5} ] ],
PlotRange -> All]
1 5 x 10 x2 10 x3 5 x4 x5
1 4 x 6 x2 4 x3 x4
1 3 x 3 x2 x3
1 2 x x2
1x
561
In[2]:= Show[Graphics[Text[
StyleForm["Some text", FontSize->14, FontWeight->"Bold"],
{2, 2}, {-1, 0}, {0, 1}]], Frame -> True]
Some text
0
0
When you specify an offset for text, the relative coordinates that are used are taken to run from
to 1 in each direction across the box that bounds the text. The point {0, 0} in this coordinate system
is defined to be center of the text. Note that the offsets you specify need not lie in the range to 1.
Note that you can specify the color of a piece of text by preceding the Text graphics primitive with
an appropriate RGBColor or other graphics directive.
Three-dimensional text.
In[3]:= <<Graphics`Polyhedra`
In[4]:= Show[Graphics3D[{Dodecahedron[ ],
Text["a point", {2, 2, 2}, {1, 1}]}]]
a point
562
Note that when you use text in three-dimensional graphics, Mathematica assumes that the text is
never hidden by any polygons or other objects.
option name
default value
Background
None
background color
TextStyle
{}
FormatType
StandardForm
format type
In[5]:= Show[Graphics[{{GrayLevel[0.5],
Rectangle[{0, 0}, {1, 1}]},
Text["Some text", {0.5, 0.5}]}]]
Some text
In[6]:= Show[Graphics[{{GrayLevel[0.5],
Rectangle[{0, 0}, {1, 1}]},
Text["Some text", {0.5, 0.5},
Background->Automatic]}]]
Some text
563
gray levels
Color displays
Color printing
When you generate graphics output in Mathematica, there are different specifications of color which
are natural for different kinds of output devices. Sometimes output devices may automatically convert
from one form of color specification to another. But Mathematica provides graphics directives which
allow you directly to produce color specifications appropriate for particular devices.
GrayLevel[i]
RGBColor[r, g, b]
Hue[h, s, b]
CMYKColor[c, m, y, k]
Each color directive in Mathematica yields a definite color directive in the PostScript code that
Mathematica sends to your output device. Thus, for example, the RGBColor directive in Mathematica
yields setrgbcolor in PostScript. The final treatment of the PostScript color directives is determined
by your output device, and the PostScript interpreter that is used.
Nevertheless, in most cases, the parameters specified in the Mathematica color directives will be
used fairly directly to set the intensities or densities of the components of the color output.
When this is done, it is important to realize that a given set of parameters in a Mathematica color
directive may yield different perceived colors on different output devices. For example, the actual
intensities of red, green and blue components will often differ between different color displays even
when the settings for these components are the same. Such differences also occur when the brightness
or contrast of a particular color display is changed.
In addition, you should realize that the complete gamut of colors that you can produce by varying
parameters on a particular output device is smaller, often substantially so, than the gamut of colors
which can be perceived by the human visual system. Even though the space of colors that we can
perceive can be described with three parameters, it is not possible to reach all parts of this space with
mixtures of a fixed number of primary colors.
564
Different choices of primary colors are typically made for different types of output devices. Color
displays, which work with emitted or transmitted light, typically use red, green and blue primary
colors. However, color printing, which works with reflected light, typically uses cyan, magenta, yellow
and black as primary colors. When a color image is printed, four separate passes are typically made,
each time laying down one of these primary colors.
Thus, while RGBColor and Hue are natural color specifications for color displays, CMYKColor is the
natural specification for color printing.
By default, Mathematica takes whatever color specifications you give, and uses them directly. The
option ColorOutput , however, allows you to make Mathematica always convert the color specifications
you give to ones appropriate for a particular kind of output device.
ColorOutput -> f
One of the most complicated issues in color output is performing the color separation necessary to
take a color specified using red, green and blue primaries, and render the color using cyan, magenta,
yellow and black printing inks. Mathematica has a built-in algorithm for doing this conversion. The
algorithm is based on an approximation to typical monitor colors and the standard set of four-color
process printing inks. Note that the colors of these printing inks are not even close to complementary
to typical monitor colors, and the actual transformation is quite nonlinear.
While Mathematica has built-in capabilities for various color conversions, you can also specify your
own color conversions using ColorOutput -> f. With this option setting, the function f is automatically
applied to each color directive generated by Mathematica.
Note that while any of the color directives given above can be used in setting up graphics objects,
simulated lighting calculations in Mathematica are always done using RGBColor , and so all color
directives are automatically converted to this form when simulated lighting is used.
This defines a transformation on
RGBColor objects, which extracts the
red component, and squares it.
Out[1]= GrayLevel r2
Out[2]= GrayLevel g2
565
1
0.5
0
-0.5
-1
0
-2
0
-2
2
Note that if you give your own ColorOutput transformation, you must specify how the transformation acts on every color directive that arises in the image you are producing. For three-dimensional
plots shaded with simulated lighting, you must typically specify the transformation at least for
RGBColor and GrayLevel .
Sound[{s , s , ... }]
The functions Play and ListPlay discussed in Section 1.9.12 return Sound objects.
Play returns a Sound object. On
appropriate computer systems, it also
produces sound.
566
SampledSoundList[{a , a , ... }, r]
SampledSoundFunction[f, n, r]
At the lowest level, all sounds in Mathematica are represented as a sequence of amplitude samples. In
SampledSoundList , these amplitude samples are given explicitly in a list. In SampledSoundFunction ,
however, they are generated when the sound is output, by applying the specified function to a
sequence of integer arguments. In both cases, all amplitude values obtained must be between
and 1.
Display[stream, sound]
Display[stream, {graphics, sound}]
567
Mathematica uses the same function Display to output sound, graphics, and combinations of the
two.
In Play, ListPlay and Sound, the option DisplayFunction specifies how the sound should ultimately be output. The default for this option is the global variable $SoundDisplayFunction . Typically,
this is set to an appropriate call to Display.
ExportString[graphics, "format"]
568
"EPS"
"PDF"
"SVG"
"PICT"
"WMF"
"TIFF"
"GIF"
"JPEG"
"PNG"
"BMP"
"EPSI"
Macintosh PICT
"EPSTIFF"
"XBitmap"
"PBM"
"PPM"
"PGM"
"PNM"
"DICOM"
Typical graphics formats supported by Mathematica. The first group are resolution independent.
When you export a graphic outside of Mathematica, you usually have to specify the absolute size at
which the graphic should be rendered. You can do this using the ImageSize option to Export.
ImageSize->x makes the width of the graphic be x printers points; ImageSize->72 xi thus makes
the width xi inches. The default is to produce an image that is four inches wide. ImageSize->{x, y}
scales the graphic so that it fits in an x y region.
569
ImageSize
Automatic
ImageRotated
False
ImageResolution
Automatic
Within Mathematica, graphics are manipulated in a way that is completely independent of the
resolution of the computer screen or other output device on which the graphics will eventually be
rendered.
Many programs and devices accept graphics in resolution-independent formats such as Encapsulated PostScript (EPS). But some require that the graphics be converted to rasters or bitmaps with a
specific resolution. The ImageResolution option for Export allows you to determine what resolution
in dots per inch (dpi) should be used. The lower you set this resolution, the lower the quality of the
image you will get, but also the less memory the image will take to store. For screen display, typical
resolutions are 72 dpi and above; for printers, 300 dpi and above.
"DXF"
"STL"
"WAV"
"AU"
"SND"
"AIFF"
570
Import["name.ext"]
Import["file", "format"]
ImportString["string", "format"]
In[1]:= g = Import["ocelot.jpg"]
In[2]:= Show[g]
Out[1]= AGraphicsA
Import yields expressions with different structures depending on the type of data it reads. Typically
you will need to know the structure if you want to manipulate the data that is returned.
571
Graphics[primitives, opts]
Graphics[Raster[data], opts]
{graphics , graphics , ... }
Sound[SampledSoundList[data, r]]
resolution-independent graphics
resolution-dependent bitmap images
animated graphics
sounds
In[4]:= Shallow[InputForm[g]]
In[6]:= Dimensions[d]
In[7]:= ListPlot[Sort[Flatten[d]]]
250
200
150
100
50
10000
20000
30000
40000
572
Cell[contents, "style"]
Cell[contents, "style", options]
Within a given notebook, there is always a collection of styles that can be used to determine the
appearance and behavior of cells. Typically the styles are named so as to reflect what role cells which
have them will play in the notebook.
"Title"
"Section"
"Subsection"
"Text"
"Input"
"Output"
573
A particular style such as "Section" or "Text" defines various settings for the options associated
with a cell. You can override these settings by explicitly setting options within a specific cell.
Here is the expression for a cell in
which options are set to use a gray
background and to put a frame around
the cell.
574
option
default value
CellFrame
False
Background
GrayLevel[1]
Editable
True
TextAlignment
Left
FontSize
12
CellTags
{}
The standard notebook front end for Mathematica provides several ways to change the options of a
cell. In simple cases, such as changing the size or color of text, there will often be a specific menu
item for the purpose. But in general you can use the option inspector that is built into the front end.
This is typically accessed using the Option Inspector menu item in the Format menu.
Sometimes you will want just to change the options associated with a specific cell. But often you
may want to change the options associated with all cells in your notebook that have a particular style.
You can do this by using the Edit Style Sheet command in the front end to open up the style sheet
associated with your notebook, and then modifying the options for the cells in this style sheet that
represent the style you want to change.
CellPrint[Cell[... ]]
575
CellPrint allows you to take a raw Cell expression and insert it into your current notebook.
Sometimes, however, you may find it more convenient to give an ordinary Mathematica expression,
and then have Mathematica convert it into a Cell of a certain style, and insert this cell into a notebook.
You can do this using the function StylePrint .
StylePrint[expr, "style"]
create a new cell of the specified style, and write expr into it
576
Another heading
CellPrint and StylePrint provide simple ways to modify open notebooks in the front end from
within the kernel. Later in this section we will discuss more sophisticated and flexible ways to do
this.
577
Notebook[
Cell["Section heading", "Section"],
Cell["Some text.", "Text"],
Cell["More text.", "Text"]]
Just like individual cells, notebooks in Mathematica can also have options. You can look at and
modify these options using the options inspector in the standard notebook front end.
option
default value
WindowSize
{nx, ny}
WindowFloating
False
WindowToolbars
{}
ShowPageBreaks
False
CellGrouping
Automatic
Evaluator
"Local"
In addition to notebook options, you can also set any cell option at the notebook level. Doing this
tells Mathematica to use that option setting as the default for all the cells in the notebook. You can
override the default by explicitly setting the options within a particular cell.
Here is the expression corresponding to
a notebook with a ruler displayed in
the toolbar at the top of the window.
Notebook[
Cell["Section heading", "Section"],
Cell["Some text.", "Text"],
WindowToolbars->"RulerBar"]
578
Notebook[
Cell["Section heading", "Section"],
Cell["Some text.", "Text"],
Background->GrayLevel[.7]]
If you go outside of Mathematica and look at the raw text of the file that corresponds to a Mathematica
notebook, you will find that what is in the file is just the textual form of the expression that represents
the notebook. One way to create a Mathematica notebook is therefore to construct an appropriate
expression and put it in a file.
In notebook files that are written out by Mathematica, some additional information is typically
included to make it faster for Mathematica to read the file in again. The information is enclosed in
Mathematica comments indicated by (* ... *) so that it does not affect the actual expression stored in
the file.
NotebookOpen["file.nb"]
NotebookPut[expr]
NotebookGet[obj]
In[2]:= <<sample.nb
In[3]:= NotebookOpen["sample.nb"]
Section heading
Some text.
579
Once you have set up a notebook in the front end using NotebookOpen , you can then manipulate
the notebook interactively just as you would any other notebook. But in order to use NotebookOpen ,
you have to explicitly have a notebook expression in a file. With NotebookPut , however, you can take
a notebook expression that you have created in the kernel, and immediately display it as a notebook
in the front end.
Here is a notebook expression in the
kernel.
In[5]:= NotebookPut[%]
Section heading
Some text.
Out[5]= NotebookObject
In[6]:= NotebookGet[%]
Out[6]= Notebook
Cell
CellGroupData
Cell
TextData
Section heading, Section,
Cell
TextData
Some text., Text, Open
Notebooks[ ]
Notebooks["name"]
SelectedNotebook[ ]
InputNotebook[ ]
EvaluationNotebook[ ]
ButtonNotebook[ ]
580
Within the Mathematica kernel, notebooks that you have open in the front end are referred to by
notebook objects of the form NotebookObject[fe, id]. The first argument of NotebookObject specifies
the FrontEndObject for the front end in which the notebook resides, while the second argument gives
a unique serial number for the notebook.
Here is a notebook named Example.nb .
First Heading
Second Heading
In[1]:= Notebooks["Example.nb"]
In[2]:= NotebookGet[First[%]]
Out[1]= {NotebookObject[<<Example.nb>>]}
Out[4]= {NotebookObject[<<Untitled-1.nb>>]}
NotebookGet[obj]
NotebookPut[expr, obj]
NotebookPut[expr]
Exchanging whole notebook expressions between the kernel and front end.
If you want to do extensive manipulations on a particular notebook you will usually find it convenient to use NotebookGet to get the whole notebook into the kernel as a single expression. But if
instead you want to do a sequence of small operations on a notebook, then it is often better to leave
581
the notebook in the front end, and then to send specific commands from the kernel to the front end
to tell it what operations to do.
Mathematica is set up so that anything you can do interactively to a notebook in the front end you
can also do by sending appropriate commands to the front end from the kernel.
Options[obj]
Options[obj, option]
AbsoluteOptions[obj, option]
SetOptions[obj, option->value]
First Heading
Second Heading
Within any open notebook, the front end always maintains a current selection. The selection can
consist for example of a region of text within a cell or of a complete cell. Usually the selection is
indicated on the screen by some form of highlighting. The selection can also be between two characters of text, or between two cells, in which case it is usually indicated on the screen by a vertical or
horizontal insertion bar.
You can modify the current selection in an open notebook by issuing commands from the kernel.
582
Character
individual character
Word
Expression
TextLine
TextParagraph
CellContents
Cell
CellGroup
EvaluationCell
ButtonCell
GeneratedCell
Notebook
Units used in specifying selections.
complete subexpression
line of text
paragraph of text
the contents of the cell
complete cell
cell group
cell associated with the current evaluation
cell associated with any button that initiated the
evaluation
cell generated by the current evaluation
complete notebook
In[7]:= nb = SelectedNotebook[ ];
583
584
NotebookFind[obj, data]
NotebookFind[obj, data, Previous]
NotebookFind[obj, data, All]
NotebookFind[obj, data, dir, elems]
Out[11]= $Failed
Out[12]= $Failed
CellContents
CellStyle
CellLabel
CellTags
{elem , elem , ... }
585
In setting up large notebooks, it is often convenient to insert tags which are not usually displayed,
but which mark particular cells in such a way that they can be found using NotebookFind . You can
set up tags for cells either interactively in the front end, or by explicitly setting the CellTags option
for a cell.
NotebookLocate["tag"]
NotebookLocate[{"file", "tag"}]
locate and select cells with the specified tag in the current
notebook
open another notebook if necessary
NotebookLocate is the underlying function that Mathematica calls when you follow a hyperlink in
a notebook. The menu item Create Hyperlink sets up the appropriate NotebookLocate as part of the
script for a particular hyperlink button.
NotebookWrite[obj, data]
NotebookApply[obj, data]
NotebookDelete[obj]
NotebookRead[obj]
NotebookWrite[obj, data] is similar to a Paste operation in the front end: it replaces the current selection in your notebook by data. If the current selection is a cell NotebookWrite[obj, data]
586
will replace the cell with data. If the current selection lies between two cells, however, then
NotebookWrite[obj, data] will create an appropriate new cell or cells.
Here is a notebook with a word of text
selected.
In[15]:= NotebookWrite[nb,
Cell["This cell contains text.", "Text"]]
Here is a first <<inserted text>>.
This cell contains text.
587
In[17]:= NotebookRead[nb]
Here is a first <<inserted text>>.
This cell contains text.
NotebookWrite[obj, data] just discards the current selection and replaces it with data. But particularly if you are setting up palettes, it is often convenient first to modify data by inserting the current
selection somewhere inside it. You can do this using selection placeholders and NotebookApply . The
first time the character , entered as \[SelectionPlaceholder] or spl, appears anywhere in
data, NotebookApply will replace this character by the current selection.
Here is a simple notebook with the
current selection being the contents of
a cell.
In[18]:= nb = SelectedNotebook[ ] ;
Expand1 x4
x 1 Expand1 x4
588
SelectionEvaluate[obj]
SelectionCreateCell[obj]
SelectionEvaluateCreateCell[obj]
SelectionAnimate[obj]
SelectionAnimate[obj, t]
In[21]:= SelectionEvaluate[nb]
1
x
1 4x 6x2 4x3 x4
SelectionEvaluate allows you to take material from a notebook and send it through the kernel
for evaluation. On its own, however, SelectionEvaluate always overwrites the material you took.
But by using functions like SelectionCreateCell you can maintain a record of the sequence of forms
that are generatedjust like in a standard Mathematica session.
This makes the current selection be the
whole cell.
In[23]:= SelectionCreateCell[nb]
1
x
1 4x 6x2 4x3 x4
1
x
1 4x 6x2 4x3 x4
589
In[25]:= SelectionEvaluateCreateCell[nb]
1
x
1 4x 6x2 4x3 x4
1
Factorx
1 4x 6x2 4x3 x4
1 x 4x2 6x3 4x4 x5
1 x4
Functions like NotebookWrite and SelectionEvaluate by default leave the current selection just
after whatever material they insert into your notebook. You can then always move the selection by
explicitly using SelectionMove . But functions like NotebookWrite and SelectionEvaluate can also
take an additional argument which specifies where the current selection should be left after they do
their work.
SelectionEvaluate[obj, sel]
SelectionCreateCell[obj, sel]
SelectionEvaluateCreateCell[obj, sel]
evaluate the current selection, make a new cell for the result,
and make the new current selection be as specified by sel
Performing operations and specifying what the new current selection should be.
590
After
Before
All
Placeholder
None
In[26]:= nb = SelectedNotebook[ ] ;
10
10
3628800
10
FactorInteger3628800
Options[obj, option]
591
Options[NotebookSelection[obj], option]
find the value for the current selection
SetOptions[obj, option->value]
SetOptions[NotebookSelection[obj], option->value]
set the value for the current selection
Finding and setting options for whole notebooks and for the current selection.
NotebookCreate[ ]
NotebookCreate[options]
NotebookOpen["name"]
NotebookOpen["name", options]
SetSelectedNotebook[obj]
NotebookPrint[obj]
NotebookPrint[obj, "file"]
NotebookPrint[obj, "!command"]
NotebookSave[obj]
NotebookSave[obj, "file"]
NotebookClose[obj]
Operations on whole notebooks.
592
If you call NotebookCreate[ ] a new empty notebook will appear on your screen.
By executing commands like SetSelectedNotebook and NotebookOpen , you tell the Mathematica
front end to change the windows you see. Sometimes you may want to manipulate a notebook without
ever having it displayed on the screen. You can do this by using the option setting Visible->False
in NotebookOpen or NotebookCreate .
AbsoluteOptions[$FrontEnd, option]
the absolute setting for an option
SetOptions[$FrontEnd, option->value]
reset an option in the front end
Manipulating global options in the front end.
Just like cells and notebooks, the complete Mathematica front end has various options, which you can
look at and manipulate from the kernel.
This gives the object corresponding to
the front end currently in use.
In[1]:= $FrontEnd
Out[1]= AFrontEndObjectA
option
default value
NotebookDirectory
"M$"
NotebookPath
(system dependent)
Language
"English"
MessageOptions
(list of settings)
2.11.5 Advanced Topic: Executing Notebook Commands Directly in the Front End
593
By using NotebookWrite you can effectively input to the front end any ordinary text that you can
enter on the keyboard. FrontEndTokenExecute allows you to send from the kernel any command
that the front end can execute. These commands include both menu items and control sequences.
FrontEndTokenExecute["name"]
"Indent"
"NotebookStatisticsDialog"
"OpenCloseGroup"
"CellSplit"
"DuplicatePreviousInput"
"FindDialog"
"ColorSelectorDialog"
"GraphicsAlign"
"CompleteSelection"
A few named commands that can be given to the front end. These commands usually correspond to menu items.
2.11.5 Advanced Topic: Executing Notebook Commands Directly in the Front End
When you execute a command like NotebookWrite[obj, data] the actual operation of inserting data
into your notebook is performed in the front end. Normally, however, the kernel is needed in order to
evaluate the original command, and to construct the appropriate request to send to the front end. But
it turns out that the front end is set up to execute a limited collection of commands directly, without
ever involving the kernel.
594
NotebookWrite[obj, data]
FrontEnd`NotebookWrite[obj, data]
version of NotebookWrite to be executed directly in the
front end
Distinguishing kernel and front end versions of commands.
The basic way that Mathematica distinguishes between commands to be executed in the kernel and
to be executed directly in the front end is by using contexts. The kernel commands are in the usual
System` context, but the front end commands are in the FrontEnd` context.
FrontEndExecute[expr]
In[2]:= FrontEnd`NotebookWrite[FrontEnd`SelectedNotebook[ ],
"a + b + c + d"]
xyz
Out[2]= FrontEnd`NotebookWrite
FrontEnd`SelectedNotebook
, a b c d
In[3]:= FrontEndExecute[%]
xyz
abcd
If you write sophisticated programs for manipulating notebooks, then you will have no choice but
to execute these programs primarily in the kernel. But for the kinds of operations typically performed
by simple buttons, you may find that it is possible to execute all the commands you need directly in
the front endwithout the kernel even needing to be running.
595
ButtonBox[boxes]
ButtonBox[boxes, Active->True]
Expand
Expand
abc xy
Cell[BoxData[GridBox[{
{
ButtonBox["abc"],
ButtonBox["xy"]}
},
ColumnSpacings->0]], "Input", Active->True]
ButtonBox[boxes, ButtonStyle->"style"]
a button whose properties are taken from the specified
style
Basic ButtonBox objects.
By setting the ButtonStyle you can specify defaults both for how a button will be displayed, and
what its action will be. The notebook front end provides a number of standard ButtonStyle settings,
which you can access from the Create Button and Edit Button menu items.
596
"Paste"
"Evaluate"
"EvaluateCell"
"CopyEvaluate"
copy the current selection into a new cell, then paste and
evaluate in place
"CopyEvaluateCell"
copy the current selection into a new cell, then paste and
evaluate the whole cell
"Hyperlink"
Cell[BoxData[
ButtonBox[
RowBox[{"Expand", "[", ""[SelectionPlaceholder]", "]"}],
ButtonStyle->"CopyEvaluateCell"]], "Input",
Active->True]
1 x6
1 x6
In[1]:=
Expand1 x6
Out[1]=
1 6 x 15 x2 20 x3 15 x4 6 x5 x6
597
option
default value
ButtonFunction
(pasting function)
ButtonSource
Automatic
ButtonData
Automatic
ButtonEvaluator
None
ButtonNote
None
A particular ButtonStyle setting will specify defaults for all other button options. Some of these
options will affect the display of the button, as discussed on page 452. Others affect the action it
performs.
What ultimately determines the action of a button is the setting for the ButtonFunction option.
This setting gives the Mathematica function which is to be executed whenever the button is clicked.
Typically this function will be a combination of various notebook manipulation commands.
Thus, for example, in its most basic form, a Paste button will have a ButtonFunction given
effectively by NotebookApply[SelectedNotebook[ ], #]&, while a Hyperlink button will have a
ButtonFunction given effectively by NotebookLocate[#2]& .
When a button is clicked, two arguments are supplied to its ButtonFunction . The first is specified
by ButtonSource , and the second by ButtonData .
Typically ButtonData is set to be a fixed expression, defined when the button was first created.
ButtonSource , on the other hand, usually changes with the contents of the button, or the environment
in which the button appears.
598
Automatic
ButtonContents
ButtonData
CellContents
Cell
Notebook
n
For a simple Paste button, the setting for ButtonSource is typically ButtonContents . This means
that whatever is displayed in the button will be what is passed as the first argument of the button
function. The button function can then take this argument and feed it to NotebookApply , thereby
actually pasting it into the notebook.
By using settings other than ButtonContents for ButtonSource , you can create buttons which
effectively pull in various aspects of their environment for processing. Thus, for example, with the
setting ButtonSource->Cell , the first argument to the button function will be the expression that
represents the whole cell in which the button appears. By having the button function manipulate this
expression you can then make the button have a global effect on the whole cell, say by restructuring
it in some specified way.
None
Automatic
"name"
Once the arguments to a ButtonFunction have been found, and an expression has been constructed, there is then the question of where that expression should be sent for evaluation. The
ButtonEvaluator option for a ButtonBox allows you to specify this.
In general, if the expression involves a range of Mathematica functions, then there will be no choice
but to evaluate it in an actual Mathematica kernel. But if the expression involves only simple notebook
manipulation commands, then it may be possible to execute the expression directly in the front end,
without ever involving the kernel. You can specify that this should be done by setting the option
ButtonEvaluator->None .
FrontEndExecute[expr]
599
FrontEnd`NotebookApply[... ], etc.
As discussed in the previous section, the standard notebook front end can handle only a limited
set of commands, all identified as being in the FrontEnd` context. But these commands are sufficient
to be able to implement all of the actions associated with standard button styles such as Paste,
EvaluateCell and Hyperlink .
Note that even if an expression is sent to the front end, it will be executed only if it is wrapped in
a FrontEndExecute .
Cell[TextData[{
"Text with the formula ",
Cell[BoxData[
FormBox[
SuperscriptBox["xyz", ""[Alpha]"], TraditionalForm]]],
" inside."
}], "Text"]
600
"text"
TextData[{text , text , ... }]
BoxData[boxes]
GraphicsData["type", data]
plain text
text potentially in different styles, or containing cells
formatted Mathematica expressions
graphics or sounds
OutputFormData["itext", "otext"]
text as generated by InputForm and OutputForm
RawData["data"]
Cell
Selection
First Section
Some text in the first section.
Some more text in the first section.
601
First Section
Some text in the first section.
Some more text in the first section.
First Section
Some text in the first section.
First Section
Some text in the first section.
Some more text in the first section.
In the standard notebook front end, you can check and set options at any level by using the Option
Inspector menu item. If you do not set an option at a particular level, then its value will always be
inherited from the level above. Thus, for example, if a particular cell does not set the CellFrame
option, then the value used will be inherited from its setting for the style of the cell or for the whole
notebook that contains the cell.
As a result, if you set CellFrame->True at the level of a whole notebook, then all the cells in the
notebook will have frames drawn around themunless the style of a particular cell, or the cell itself,
explicitly overrides this setting.
602
Depending on what you intend to use your Mathematica notebook for, you may want to choose
different basic default styles for the notebook. In the standard notebook front end, you can do this
using the Edit Style Sheet menu item.
"Report"
"Tutorial"
"Book"
With each choice of basic default styles, the styles that are provided will change. Thus, for example,
only in the Book default styles is there a Box style which sets up the gray boxes used in this book.
Here is a notebook that uses Book
default styles.
MiscellaneousChemicalElements
Abbreviation
element
AtomicNumber
element
AtomicWeight
element
StableIsotopes
element
Elements
This gives the atomic weight of tungsten using the data in the package.
In[2]:= AtomicWeight[Tungsten]
Out[2]= 183.85
option
default value
ScreenStyleEnvironment
"Working"
PrintingStyleEnvironment
"Printout"
Within a particular set of basic default styles, Mathematica allows for two different style environments: one for display on the screen, and another for output to a printer. The existence of separate
screen and printing style environments allows you to set up styles which are separately optimized
both for low-resolution display on a screen, and high-resolution printing.
"Working"
"Presentation"
"Condensed"
"Printout"
603
log x
x
x3
1
3
3
logx log! 1 x 1" Li2 ! 1 x"
log1 x logx Li2 x
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
3
3
1 12#3 ! 1 12#3 "
!1 1 " 1 12#3
log x
x
x3
1
3
3
logx log! 1 x 1" Li2 ! 1 x"
logx log1 12#3 x Li2 12#3 x
log1 x logx Li2 x
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
3
3
3
3
!1 1 " 1 12#3
!1 1 " ! 1 12#3 "
1 12#3 ! 1 12#3 "
The way that Mathematica actually sets up the definitions for styles is by using style definition cells.
These cells can either be given in separate style definition notebooks, or can be included in the options of
a specific notebook. In either case, you can access style definitions by using the Edit Style Sheet menu
item in the standard notebook front end.
"name.nb"
Section
604
Cell[StyleData["style"], options]
Cell[StyleData["Section"], NotebookDefault,
CellFrame->False,
CellDingbat->"-[GraySquare]",
CellMargins->{{22, Inherited}, {Inherited, 20}},
CellGroupingRules->{"SectionGrouping", 30},
PageBreakBelow->False,
CounterIncrements->"Section",
CounterAssignments->{{"Subsection", 0}, {"Subsubsection", 0}},
FontFamily->"Times",
FontSize->18,
FontWeight->"Bold"]
option
CellDingbat
""
CellFrame
False
Background
GrayLevel[1]
ShowCellBracket
True
Magnification
CellOpen
True
605
A Heading
A Heading
A Heading
option
CellMargins
CellFrameMargins
CellElementSpacings
list of rules
CellBaseline
Baseline
The option CellMargins allows you to specify both horizontal and vertical margins to put around a
cell. You can set the horizontal margins interactively by using the margin stops in the ruler displayed
when you choose the Show Ruler menu item in the front end.
Whenever an option can refer to all four edges of a cell, Mathematica follows the convention that
the setting for the option takes the form {{left, right}, {bottom, top}}. By giving non-zero values for
the top and bottom elements, CellMargins can specify gaps to leave above and below a particular cell.
The values are always taken to be in printers points.
606
A Heading
A Heading
First text
Almost every aspect of Mathematica notebooks can be controlled by some option or another. More
detailed aspects are typically handled by aggregate options such as CellElementSpacings . The
settings for these options are lists of Mathematica rules, which effectively give values for a sequence of
suboptions. The names of these suboptions are usually strings rather than symbols.
This shows the settings for all the
suboptions associated with
CellElementSpacings .
Mathematica allows you to embed cells inside pieces of text. The option CellBaseline determines
how such inline cells will be aligned vertically with respect to the text around them. In direct
analogy with the option GridBaseline for a GridBox, the option CellBaseline specifies what aspect
of the cell should be considered its baseline.
Here is a cell containing an inline
formula. The baseline of the formula is
aligned with the baseline of the text
around it.
x
the
fraction
y
the
x
y
fraction
Cell[TextData[{
"the ",
Cell[BoxData[
RowBox[{
FractionBox["x", "y"], " "}]],
CellBaseline->Bottom],
"fraction "
}], "Section"]
607
option
CellLabel
""
ShowCellLabel
True
CellLabelAutoDelete
True
CellTags
{}
ShowCellTags
False
ConversionRules
{}
In addition to the actual contents of a cell, it is often useful to associate various kinds of ancillary
data with cells.
In a standard Mathematica session, cells containing successive lines of kernel input and output are
given labels of the form In[n]:= and Out[n]=. The option ShowCellLabel determines whether such
labels should be displayed. CellLabelAutoDelete determines whether the label on a cell should be
removed if the contents of the cell are modified. Doing this ensures that In[n]:= and Out[n]= labels
are only associated with unmodified pieces of kernel input and output.
Cell tags are typically used to associate keywords or other attributes with cells, that can be searched
for using functions like NotebookFind . Destinations for hyperlinks in Mathematica notebooks are
usually implemented using cell tags.
The option ConversionRules allows you to give a list containing entries such as "TeX" -> data
which specify how the contents of a cell should be converted to external formats. This is particularly
relevant if you want to keep a copy of the original form of a cell that has been converted in Mathematica
notebook format from some external format.
option
Deletable
True
Copyable
True
Selectable
True
Editable
True
CellEditDuplicate
False
Active
False
608
The options Deletable , Copyable , Selectable and Editable allow you to control what interactive
operations should be allowed on cells. By setting these options to False at the notebook level, you
can protect all the cells in a notebook.
Even if you allow a particular cell to be edited, you can set CellEditDuplicate->True to get
Mathematica to make a copy of the contents of the cell before they are actually changed. Styles for
cells that contain output from Mathematica kernel evaluations usually make use of this option.
option
Evaluator
"Local"
Evaluatable
False
CellEvaluationDuplicate
False
CellAutoOverwrite
False
GeneratedCell
False
InitializationCell
False
Mathematica makes it possible to specify a different evaluator for each cell in a notebook. But most
often, the Evaluator option is set only at the notebook level, typically using the Kernel menu item in
the front end.
The option CellAutoOverwrite is typically set to True for styles that represent Mathematica output.
Doing this means that when you re-evaluate a particular piece of input, Mathematica will automatically
delete the output that was previously generated from that input, and will overwrite it with new
output.
The option GeneratedCell is set whenever a cell is generated by an external request to the front
end rather than by an interactive operation within the front end. Thus, for example, any cell obtained
as output from a kernel evaluation, or created using a function like CellPrint or NotebookWrite ,
will have GeneratedCell->True .
609
option
PageBreakAbove
Automatic
PageBreakWithin
False
PageBreakBelow
Automatic
GroupPageBreakWithin
False
When you display a notebook on the screen, you can scroll continuously through it. But if you
print the notebook out, you have to decide where page breaks will occur. A setting of Automatic for
a page break option tells Mathematica to make a page break if necessary; True specifies that a page
break should always be made, while False specifies that it should never be.
PageWidth
WindowWidth
TextAlignment
Left
TextJustification
Hyphenation
True
ParagraphIndent
If you have a large block of text containing no explicit RETURN characters, then Mathematica will
automatically break your text into a sequence of lines. The option PageWidth specifies how long each
line should be allowed to be.
610
WindowWidth
PaperWidth
Infinity
n
The option TextAlignment allows you to specify how you want successive lines of text to be
aligned. Since Mathematica normally breaks text only at space or punctuation characters, it is common
to end up with lines of different lengths. Normally the variation in lengths will give your text a
ragged boundary. But Mathematica allows you to adjust the spaces in successive lines of text so as to
make the lines more nearly equal in length. The setting for TextJustification gives the fraction of
extra space which Mathematica is allowed to add. TextJustification->1 leads to full justification
in which all complete lines of text are adjusted to be exactly the same length.
Left
Right
Center
x
Like other objects in Mathematica, the cells in a notebook, and in fact the whole notebook itself, are all ultimately
represented as Mathematica expressions. With the standard notebook front end, you can use the command Show
Expression to see the text of the Mathematica expression that corresponds to any particular cell.
Like other objects in Mathematica, the cells in a notebook, and in fact the whole notebook itself, are all ultimately
represented as Mathematica expressions. With the standard notebook front end, you can use the command Show
Expression to see the text of the Mathematica expression that corresponds to any particular cell.
Like other objects in Mathematica, the cells in a notebook, and in fact the whole notebook itself, are all ultimately
represented as Mathematica expressions. With the standard notebook front end, you can use the command Show
Expression to see the text of the Mathematica expression that corresponds to any particular cell.
Like other objects in Mathematica, the cells in a notebook, and in fact the whole notebook itself, are all ultimately
represented as Mathematica expressions. With the standard notebook front end, you can use the command Show
Expression to see the text of the Mathematica expression that corresponds to any particular cell.
611
When you enter a block of text in a Mathematica notebook, Mathematica will treat any explicit RETURN
characters that you type as paragraph breaks. The option ParagraphIndent allows you to specify
how much you want to indent the first line in each paragraph. By giving a negative setting for
ParagraphIndent , you can make the first line stick out to the left relative to subsequent lines.
LineSpacing->{c, 0}
leave space so that the total height of each line is c times the
height of its contents
LineSpacing->{0, n}
LineSpacing->{c, n}
make the total height c times the height of the contents plus
n printers points
ParagraphSpacing->{c, 0}
ParagraphSpacing->{0, n}
ParagraphSpacing->{c, n}
Like other objects in Mathematica, the cells in a notebook, and in fact the whole notebook itself, are all ultimately
represented as Mathematica expressions. With the standard notebook front end, you can use the command Show
Expression to see the text of the Mathematica expression that corresponds to any particular cell.
Like other objects in Mathematica, the cells in a notebook, and in fact the whole notebook itself, are all ultimately
represented as Mathematica expressions. With the standard notebook front end, you can use the command Show
Expression to see the text of the Mathematica expression that corresponds to any particular cell.
Like other objects in Mathematica, the cells in a notebook, and in fact the whole notebook itself, are all ultimately
represented as Mathematica expressions. With the standard notebook front end, you can use the command Show
Expression to see the text of the Mathematica expression that corresponds to any particular cell.
Like other objects in Mathematica, the cells in a notebook, and in fact the whole notebook itself, are all ultimately
represented as Mathematica expressions. With the standard notebook front end, you can use the command Show
Expression to see the text of the Mathematica expression that corresponds to any particular cell.
612
option
FontFamily
"Courier"
FontSubstitutions
{}
FontSize
12
FontWeight
"Bold"
FontSlant
"Plain"
FontTracking
"Plain"
FontColor
GrayLevel[0]
Background
GrayLevel[1]
"Courier"
"Times"
"Helvetica"
FontWeight->"Plain"
FontWeight->"Bold"
FontWeight->"ExtraBold"
FontSlant->"Oblique"
Mathematica allows you to specify the font that you want to use in considerable detail. Sometimes,
however, the particular combination of font families and variations that you request may not be available on your computer system. In such cases, Mathematica will try to find the closest approximation
it can. There are various additional options, such as FontPostScriptName , that you can set to help
Mathematica find an appropriate font. In addition, you can set FontSubstitutions to be a list of rules
that give replacements to try for font family names.
613
There are a great many fonts available for ordinary text. But for special technical characters, and
even for Greek letters, far fewer fonts are available. The Mathematica system includes fonts that
were built to support all of the various special characters that are used by Mathematica. There are
three versions of these fonts: ordinary (like Times), monospaced (like Courier), and sans serif (like
Helvetica).
For a given text font, Mathematica tries to choose the special character font that matches it best. You
can help Mathematica to make this choice by giving rules for "FontSerifed" and "FontMonospaced"
in the setting for the FontProperties option. You can also give rules for "FontEncoding" to specify
explicitly from what font each character is to be taken.
AutoIndent
Automatic
DelimiterFlashTime
0.3
ShowAutoStyles
True
ShowCursorTracker
True
ShowSpecialCharacters
True
ShowStringCharacters
False
SingleLetterItalics
False
ZeroWidthTimes
False
InputAliases
{}
InputAutoReplacements
AutoItalicWords
{"Mathematica", ... }
LanguageCategory
Automatic
614
The options SingleLetterItalics and ZeroWidthTimes are typically set whenever a cell uses
TraditionalForm .
Here is an expression entered with
default options for a StandardForm
input cell.
x6 6 x5 y 15 x4 y2 20 x3 y3 15 x2 y4 6 x y5 y6
Built into Mathematica are a large number of aliases for common special characters. InputAliases
allows you to add your own aliases for further special characters or for any other kind of Mathematica
input. A rule of the form "name"->expr specifies that HnameH should immediately be replaced on input
by expr.
Aliases are delimited by explicit characters. The option InputAutoReplacements allows you to
specify that certain kinds of input sequences should be immediately replaced even when they have
no explicit delimiters. By default, for example, -> is immediately replaced by . You can give a rule
of the form "seq"->"rhs" to specify that whenever seq appears as a token in your input, it should
immediately be replaced by rhs.
"NaturalLanguage"
"Mathematica"
"Formula"
None
The option LanguageCategory allows you to tell Mathematica what type of contents it should assume cells have. This determines how spelling and structure should be checked, and how hyphenation
should be done.
option
StructuredSelection
False
DragAndDrop
False
615
Mathematica normally allows you to select any part of an expression that you see on the screen. Occasionally, however, you may find it useful to get Mathematica to allow only selections which correspond
to complete subexpressions. You can do this by setting the option StructuredSelection->True .
Here is an expression with a piece
selected.
With StructuredSelection->True
only complete subexpressions can ever
be selected.
1 x 1 x 1 x x2 x3 x4 1 x x2 x3 x4
1 x 1 x 1 x x2 x3 x4 1 x x2 x3 x4
1 x 1 x 1 x x2 x3 x4 1 x x2 x3 x4
GridBox[data, opts]
StyleBox[boxes, opts]
Cell[contents, opts]
Cell[contents, GridBoxOptions->opts]
give default options settings for all GridBox objects in
contents
Examples of specifying options for the display of expressions.
As discussed in Section 2.9, Mathematica provides many options for specifying how expressions
should be displayed. By using StyleBox[boxes, opts] you can apply such options to collections of
boxes. But Mathematica is set up so that any option that you can give to a StyleBox can also be given
to a complete Cell object, or even a complete Notebook. Thus, for example, options like Background
and LineIndent can be given to complete cells as well as to individual StyleBox objects.
There are some options that apply only to a particular type of box, such as GridBox. Usually these
options are best given separately in each GridBox where they are needed. But sometimes you may
want to specify default settings to be inherited by all GridBox objects that appear in a particular cell.
616
You can do this by giving these default settings as the value of the option GridBoxOptions for the
whole cell.
For each box type named XXXBox, Mathematica provides a cell option XXXBoxOptions that allows
you to specify the default options settings for that type of box.
AspectRatioFixed
True
ImageSize
{288, 288}
ImageMargins
Mathematica allows you to specify the final size of a graphic by setting the ImageSize option in kernel
graphics functions such as Plot and Display. Once a graphic is in a notebook, you can then typically
resize or move it just by using the mouse.
617
Use the Animate Selected Graphics menu item in the front end.
Use the kernel command SelectionAnimate[obj] .
Ways to generate animations in a notebook.
Mathematica generates animated graphics by taking a sequence of graphics cells, and then treating
them like frames in a movie. The option AnimationDisplayTime specifies how long a particular cell
should be displayed as part of the movie.
option
AnimationDisplayTime
0.1
AnimationDirection
Forward
In[1]:= NotebookCreate[WindowFrame->"ThinFrame",
WindowSize->{40, 30}]
618
option
StyleDefinitions
"DefaultStyles.nb"
ScreenStyleEnvironment
"Working"
PrintingStyleEnvironment
"Printout"
In giving style definitions for a particular notebook, Mathematica allows you either to reference another
notebook, or explicitly to include the Notebook expression that defines the styles.
option
CellGrouping
Automatic
ShowPageBreaks
False
NotebookAutoSave
False
Section heading
First text cell.
Second text cell.
Section heading
First text cell.
Second text cell.
619
option
DefaultNewCellStyle
"Input"
DefaultDuplicateCellStyle
"Input"
Mathematica allows you to take any cell option and set it at the notebook level, thereby specifying
a global default for that option throughout the notebook.
option
Editable
True
Selectable
True
Deletable
True
ShowSelection
True
Background
GrayLevel[1]
Magnification
PageWidth
WindowWidth
A few cell options that are often set at the notebook level.
620
option
Visible
True
WindowSize
{Automatic, Automatic}
WindowMargins
Automatic
WindowFrame
"Normal"
WindowElements
{"StatusArea", ... }
WindowTitle
Automatic
WindowToolbars
{}
WindowMovable
True
WindowFloating
False
WindowClickSelect True
WindowSize allows you to specify how large you want a window to be; WindowMargins allows you to specify where you want the window to be placed on your screen. The setting
WindowMargins->{{left, right}, {bottom, top}} gives the margins in printers points to leave around
your window on the screen. Often only two of the margins will be set explicitly; the others will be
Automatic , indicating that these margins will be determined from the particular size of screen that
you use.
"Normal"
"Palette"
"ModelessDialog"
"ModalDialog"
"MovableModalDialog"
621
an ordinary window
a palette window
a modeless dialog box window
a modal dialog box window
a modal dialog box window that can be moved around the
screen
"ThinFrame"
"Frameless"
"Generic"
Mathematica allows many different types of windows. The details of how particular windows are
rendered may differ slightly from one computer system to another, but their general form is always
the same. WindowFrame specifies the type of frame to draw around the window. WindowElements
gives a list of specific elements to include in the window.
"StatusArea"
"MagnificationPopUp"
"HorizontalScrollBar"
"VerticalScrollBar"
622
"RulerBar"
"EditBar"
style definitions
file locations
menu settings
dialog settings
system configuration
As discussed on page 592, you can access global front end options from the kernel by using
Options[$FrontEnd, name]. But more often, you will want to access these options interactively
using the Option Inspector in the front end.
623
<<file or Get["file"]
!!file
Reading files.
In[1]:= !!factors
In[2]:= <<factors
In[3]:= <<faxors
(* Factors of x^20 - 1 *)
(-1 + x)*(1 + x)*(1 + x^2)*(1 - x + x^2 - x^3 + x^4)*
(1 + x + x^2 + x^3 + x^4)*(1 - x^2 + x^4 - x^6 + x^8)
Out[2]= 1 x 1 x 1 x2 1 x x2 x3 x4
1 x x2 x3 x4 1 x2 x4 x6 x8
Out[3]= $Failed
Mathematica input files can contain any number of expressions. Each expression, however, must
start on a new line. The expressions may however continue for as many lines as necessary. Just as in
a standard interactive Mathematica session, the expressions are processed as soon as they are complete.
Note, however, that in a file, unlike an interactive session, you can insert a blank line at any point
without effect.
When you read in a file with <<file, Mathematica returns the last expression it evaluates in the file.
You can avoid getting any visible result from reading a file by ending the last expression in the file
with a semicolon, or by explicitly adding Null after that expression.
If Mathematica encounters a syntax error while reading a file, it reports the error, skips the remainder
of the file, then returns $Failed. If the syntax error occurs in the middle of a package which uses
BeginPackage and other context manipulation functions, then Mathematica tries to restore the context
to what it was before the package was read.
624
In[5]:= !!tmp
(-1 + x)*(1 + x)*(1 - x + x^2)*(1 + x + x^2)
In[7]:= !!tmp
(-1 + x)*(1 + x)*(1 - x + x^2)*(1 + x + x^2)
(-1 + x)*(1 + x)*(1 + x^2)*(1 + x^4)
When you use expr >>> file, Mathematica appends each new expression you give to the end of your
file. If you use expr >> file, however, then Mathematica instead wipes out anything that was in the file
before, and then puts expr into the file.
When you use either >> or >>> to write expressions to files, the expressions are usually given in
Mathematica input format, so that you can read them back into Mathematica. Sometimes, however,
you may want to save expressions in other formats. You can do this by explicitly wrapping a format
directive such as OutputForm around the expression you write out.
This writes an expression to the file
tmp in output format.
In[9]:= !!tmp
2
2
(-1 + x) (1 + x) (1 - x + x ) (1 + x + x )
One of the most common reasons for using files is to save definitions of Mathematica objects, to be
able to read them in again in a subsequent Mathematica session. The operators >> and >>> allow you
to save Mathematica expressions in files. You can use the function Save to save complete definitions
of Mathematica objects, in a form suitable for execution in subsequent Mathematica sessions.
Save["file", symbol]
Save["file", "form"]
Save["file", "context`"]
625
In[10]:= a = 2 - x^2
Out[10]= 2 x2
In[11]:= Save["afile", a]
In[12]:= !!afile
a = 2 - x^2
When you define a new object in Mathematica, your definition will often depend on other objects
that you defined before. If you are going to be able to reconstruct the definition of your new object in
a subsequent Mathematica session, it is important that you store not only its own definition, but also
the definitions of other objects on which it depends. The function Save looks through the definitions
of the objects you ask it to save, and automatically also saves all definitions of other objects on which it
can see that these depend. However, in order to avoid saving a large amount of unnecessary material,
Save never includes definitions for symbols that have the attribute Protected . It assumes that the
definitions for these symbols are also built in. Nevertheless, with such definitions taken care of, it
should always be the case that reading the output generated by Save back into a new Mathematica
session will set up the definitions of your objects exactly as you had them before.
This defines a function f which
depends on the symbol a defined
above.
In[14]:= Save["ffile", f]
In[15]:= !!ffile
f[z_] := a^2 - 2
a = 2 - x^2
The function Save makes use of the output forms Definition and FullDefinition , which print
as definitions of Mathematica symbols. In some cases, you may find it convenient to use these output
forms directly.
626
In[16]:= Definition[f]
In[17]:= FullDefinition[f]
Out[16]= f z_ := a2 2
Out[17]= f z_ := a2 2
a = 2 x2
When you create files for input to Mathematica, you usually want them to contain only plain text,
which can be read or modified directly. Sometimes, however, you may want the contents of a file to
be encoded so that they cannot be read or modified directly as plain text, but can be loaded into
Mathematica. You can create encoded files using the Mathematica function Encode.
Encode["source", "dest"]
<<dest
Get["dest", "key"]
In[20]:= !!tmp.x
In[21]:= <<tmp.x
(*!1N!*)mcm
_QZ9tcI1cfre*Wo8:) P
Out[21]= 1 x 1 x
DumpSave["file.mx", symbol]
DumpSave["file.mx", "context`"]
627
If you have to read in very large or complicated definitions, you will often find it more efficient
to store these definitions in internal Mathematica format, rather than as text. You can do this using
DumpSave .
This saves the definition for f in
internal Mathematica format.
In[22]:= DumpSave["ffile.mx", f]
In[23]:= <<ffile.mx
Out[22]= f
<< recognizes when a file contains definitions in internal Mathematica format, and operates accordingly. One subtlety is that the internal Mathematica format differs from one computer system to
another. As a result, .mx files created on one computer cannot typically be read on another.
If you use DumpSave["package`", ... ] then Mathematica will write out definitions to a file with a
name like package.mx/system/package.mx, where system identifies your type of computer system.
This creates a file with a name that
reflects the name of the computer
system being used.
In[24]:= DumpSave["gffile`", f]
In[25]:= <<gffile`
DumpSave["file.mx"]
DumpSave["package`"]
Out[24]= f
628
Mathematica supports two basic forms of communication with external programs: structured and
unstructured.
Structured communication
Unstructured communication
<< "!command"
In general, wherever you might use an ordinary file name, Mathematica allows you instead to give
a pipe, written as an external command, prefaced by an exclamation point. When you use the pipe,
Mathematica will execute the external command, and send or receive text from it.
This sends the result from
FactorInteger to the external
program lpr. On many Unix systems,
this program generates a printout.
One point to notice is that you can get away with dropping the double quotes around the name of
a pipe on the right-hand side of << or >> if the name does not contain any spaces or other special
characters.
Pipes in Mathematica provide a very general mechanism for unstructured communication with
external programs. On many computer systems, Mathematica pipes are implemented using pipe mechanisms in the underlying operating system; in some cases, however, other interprocess communication
mechanisms are used. One restriction of unstructured communication in Mathematica is that a given
629
pipe can only be used for input or for output, and not for both at the same time. In order to do
genuine two-way communication, you need to use MathLink.
Even with unstructured communication, you can nevertheless set up somewhat more complicated
arrangements by using temporary files. The basic idea is to write data to a file, then to read it as
needed.
OpenTemporary[ ]
Particularly when you work with temporary files, you may find it useful to be able to execute
external commands which do not explicitly send or receive data from Mathematica. You can do this
using the Mathematica function Run.
In[3]:= Run["date"]
Sat Jun 28 01:19:18 CDT 2003
Out[3]= 0
Note that when you use Run, you must not preface commands with exclamation points. Run simply
takes the textual forms of the arguments you specify, then joins them together with spaces in between,
and executes the resulting string as an external command.
It is important to realize that Run never captures any of the output from an external command.
As a result, where this output goes is purely determined by your operating system. Similarly, Run
does not supply input to external commands. This means that the commands can get input through
any mechanism provided by your operating system. Sometimes external commands may be able to
access the same input and output streams that are used by Mathematica itself. In some cases, this may
be what you want. But particularly if you are using Mathematica with a front end, this can cause
considerable trouble.
!command
Shell escapes in Mathematica.
630
If you use Mathematica with a text-based interface, there is usually a special mechanism for executing external commands. With such an interface, Mathematica takes any line of input that starts with
an exclamation point, and executes the text on the remainder of the line as an external command.
The way Mathematica uses !command is typical of the way shell escapes work in programs running under the Unix operating system. In most versions of Mathematica, you will be able to start an
interactive shell from Mathematica simply by typing a single exclamation point on its own on a line.
This line is taken as a shell escape,
and executes the Unix command date.
In[4]:= !date
Sat Jun 28 01:19:18 CDT 2003
Out[4]= 0
RunThrough["command", expr]
As discussed above, << and >> cannot be used to both send and receive data from an external
program at the same time. Nevertheless, by using temporary files, you can effectively both send and
receive data from an external program while still using unstructured communication.
The function RunThrough writes the text of an expression to a temporary file, then feeds this
file as input to an external program, and captures the output as input to Mathematica. Note that in
RunThrough , like Run, you should not preface the names of external commands with exclamation
points.
This feeds the expression 789 to the
external program cat, which in this
case simply echoes the text of the
expression. The output from cat is
then read back into Mathematica.
631
The basic low-level scheme for writing output to a stream in Mathematica is as follows. First, you
call OpenWrite or OpenAppend to open the stream, telling Mathematica that you want to write output
to a particular file or external program, and in what form the output should be written. Having
opened a stream, you can then call Write or WriteString to write a sequence of expressions or
strings to the stream. When you have finished, you call Close to close the stream.
"name"
"!name"
InputStream["name", n]
OutputStream["name", n]
Streams in Mathematica.
When you open a file or a pipe, Mathematica creates a stream object that specifies the open stream
associated with the file or pipe. In general, the stream object contains the name of the file or the
external command used in a pipe, together with a unique number.
The reason that the stream object needs to include a unique number is that in general you can
have several streams connected to the same file or external program at the same time. For example,
you may start several different instances of the same external program, each connected to a different
stream.
Nevertheless, when you have opened a stream, you can still refer to it using a simple file name or
external command name so long as there is only one stream associated with this object.
This opens an output stream to the file
tmp.
In[2]:= Write[stmp, a, b, c]
In[3]:= Write["tmp", x]
In[4]:= Close[stmp]
Out[4]= tmp
In[5]:= !!tmp
abc
x
632
OpenWrite["file"]
OpenAppend["file"]
OpenWrite["!command"]
Write[stream, expr , expr , ... ]
When you call Write[stream, expr], it writes an expression to the specified stream. The default is
to write the expression in Mathematica input form. If you call Write with a sequence of expressions,
it will write these expressions one after another to the stream. In general, it leaves no space between
the successive expressions. However, when it has finished writing all the expressions, Write always
ends its output with a newline.
This re-opens the file tmp.
In[8]:= !!tmp
Out[7]= tmp
a^21 + b^2
c^3
Write provides a way of writing out complete Mathematica expressions. Sometimes, however, you
may want to write out less structured data. WriteString allows you to write out any character string.
Unlike Write, WriteString adds no newlines or other characters.
This opens the stream.
In[12]:= !!tmp
633
Out[11]= tmp
Arbitrary output.
More output. Second line.
An important feature of the functions Write and WriteString is that they allow you to write
output not just to a single stream, but also to a list of streams.
In using Mathematica, it is often convenient to define a channel which consists of a list of streams.
You can then simply tell Mathematica to write to the channel, and have it automatically write the same
object to several streams.
In a standard interactive Mathematica session, there are several output channels that are usually
defined. These specify where particular kinds of output should be sent. Thus, for example, $Output
specifies where standard output should go, while $Messages specifies where messages should go. The
function Print then works essentially by calling Write with the $Output channel. Message works in
the same way by calling Write with the $Messages channel. Page 705 lists the channels used in a
typical Mathematica session.
Note that when you run Mathematica through MathLink, a different approach is usually used. All
output is typically written to a single MathLink link, but each piece of output appears in a packet
which indicates what type it is.
In most cases, the names of files or external commands that you use in Mathematica correspond exactly with those used by your computers operating system. On some systems, however, Mathematica
supports various streams with special names.
"stdout"
standard output
"stderr"
standard error
634
The special stream "stdout" allows you to give output to the standard output provided by the
operating system. Note however that you can use this stream only with simple text-based interfaces
to Mathematica. If your interaction with Mathematica is more complicated, then this stream will not
work, and trying to use it may cause considerable trouble.
option name
default value
FormatType
InputForm
PageWidth
78
NumberMarks
$NumberMarks
CharacterEncoding $CharacterEncoding
You can associate a number of options with output streams. You can specify these options when
you first open a stream using OpenWrite or OpenAppend .
This opens a stream, specifying that
the default output format used should
be OutputForm .
In[15]:= !!tmp
Out[14]= tmp
2
x
2
+ y
2
z
Note that you can always override the output format specified for a particular stream by wrapping
a particular expression you write to the stream with an explicit Mathematica format directive, such as
OutputForm or TeXForm.
The option PageWidth gives the width of the page available for textual output from Mathematica.
All lines of output are broken so that they fit in this width. If you do not want any lines to be
broken, you can set PageWidth -> Infinity . Usually, however, you will want to set PageWidth to
the value appropriate for your particular output device. On many systems, you will have to run an
external program to find out what this value is. Using SetOptions , you can make the default rule
for PageWidth be, for example, PageWidth :> <<"!devicewidth" , so that an external program is run
automatically to find the value of the option.
This opens a stream, specifying that
the page width is 20 characters.
In[18]:= !!tmp
635
Out[17]= tmp
1 + 5*x + 10*x^2 +
10*x^3 + 5*x^4 +
x^5
The option CharacterEncoding allows you to specify a character encoding that will be used for
all strings containing special characters which are sent to a particular output stream, whether by
Write or WriteString . You will typically need to use CharacterEncoding if you want to modify
an international character set, or prevent a particular output device from receiving characters that it
cannot handle.
Options[stream]
In[21]:= Options[stmp]
In[22]:= Close[stmp]
Out[22]= tmp
Options[$Output]
find the options set for all streams in the channel $Output
At every point in your session, Mathematica maintains a list Streams[ ] of all the input and output
streams that are currently open, together with their options. In some cases, you may find it useful to
look at this list directly. Mathematica will not, however, allow you to modify the list, except indirectly
through OpenRead and so on.
636
Directory[ ]
SetDirectory["dir"]
ResetDirectory[ ]
Manipulating directories.
In[1]:= Directory[ ]
In[2]:= SetDirectory["Packages"]
In[3]:= Directory[ ]
In[4]:= ResetDirectory[ ]
Out[1]= /users/sw
Out[2]= /users/sw/Packages
Out[3]= /users/sw/Packages
Out[4]= /users/sw
When you call SetDirectory , you can give any directory name that is recognized by your operating system. Thus, for example, on Unix-based systems, you can specify a directory one level up in
the directory hierarchy using the notation .., and you can specify your home directory as M.
Whenever you go to a new directory using SetDirectory , Mathematica always remembers what
the previous directory was. You can return to this previous directory using ResetDirectory . In
general, Mathematica maintains a stack of directories, given by DirectoryStack[ ]. Every time you
call SetDirectory , it adds a new directory to the stack, and every time you call ResetDirectory it
removes a directory from the stack.
ParentDirectory[ ]
$InitialDirectory
637
$HomeDirectory
$BaseDirectory
$UserBaseDirectory
$InstallationDirectory
Special directories.
Whenever you ask for a particular file, Mathematica in general goes through several steps to try and
find the file you want. The first step is to use whatever standard mechanisms exist in your operating
system or shell.
Mathematica scans the full name you give for a file, and looks to see whether it contains any of the
metacharacters *, $, M, ?, [, ", \ and '. If it finds such characters, then it passes the full name to your
operating system or shell for interpretation. This means that if you are using a Unix-based system,
then constructions like name* and $VAR will be expanded at this point. But in general, Mathematica
takes whatever was returned by your operating system or shell, and treats this as the full file name.
For output files, this is the end of the processing that Mathematica does. If Mathematica cannot find
a unique file with the name you specified, then it will proceed to create the file.
If you are trying to get input from a file, however, then there is another round of processing that
Mathematica does. What happens is that Mathematica looks at the value of the Path option for the
function you are using to determine the names of directories relative to which it should search for the
file. The default setting for the Path option is the global variable $Path.
In general, the global variable $Path is defined to be a list of strings, with each string representing
a directory. Every time you ask for an input file, what Mathematica effectively does is temporarily to
638
make each of these directories in turn your current working directory, and then from that directory to
try and find the file you have requested.
Here is a typical setting for $Path. The
current directory (.) and your home
directory (M) are listed first.
In[5]:= $Path
Out[5]= {., M, /users/math/bin, /users/math/Packages}
FileNames[ ]
FileNames["form"]
In[6]:= FileNames["*.m"]
FileNames returns a list of strings corresponding to file names. When it returns a file that is not
in your current directory, it gives the name of the file relative to the current directory. Note that all
names are given in the format appropriate for the particular computer system on which they were
generated.
639
DirectoryName["file"]
ToFileName["directory", "name"]
ParentDirectory["directory"]
You should realize that different computer systems may give file names in different ways. Thus,
for example, Windows systems typically give names in the form dir:\dir\#dir\#name , Unix systems
in the form dir/dir/name and Macintosh systems in the form :dir:dir:name. The function ToFileName
assembles file names in the appropriate way for the particular computer system you are using.
This gives the directory portion of the
file name.
In[8]:= DirectoryName["Packages/Math/test.m"]
Out[8]= PackagesMath
Out[9]= PackagesMathabc.m
If you want to set up a collection of related files, it is often convenient to be able to refer to one file
when you are reading another one. The global variable $Input gives the name of the file from which
input is currently being taken. Using DirectoryName and ToFileName you can then conveniently
specify the names of other related files.
$Input
640
<<context`
name.mx
name.mx/$SystemID/name.mx
name.m
name/init.m
dir/...
In[1]:= <<Graphics`Colors`
Mathematica is set up so that <<name` will automatically try to load the appropriate version of a
file. It will first try to load a name.mx file that is optimized for your particular computer system. If
it finds no such file, then it will try to load a name.m file containing ordinary system-independent
Mathematica input.
If name is a directory, then Mathematica will try to load the initialization file init.m in that directory.
The purpose of the init.m file is to provide a convenient way to set up Mathematica packages that
involve many separate files. The idea is to allow you to give just the command <<name`, but then to
load init.m to initialize the whole package, reading in whatever other files are necessary.
This reads in the file Graphics/init.m ,
which initializes all standard
Mathematica graphics packages.
In[2]:= <<Graphics`
641
Different operating systems have different commands for manipulating files. Mathematica provides
a simple set of file manipulation functions, intended to work in the same way under all operating
systems.
Notice that CopyFile and RenameFile give the final file the same modification date as the original one. FileDate returns modification dates in the {year, month, day, hour, minute, second} format
used by Date.
CreateDirectory["name"]
DeleteDirectory["name"]
642
Import["file", "List"]
Export["file", list, "List"]
Import["file", "Table"]
Export["file", list, "Table"]
Import["file", "CSV"]
In[2]:= !!out1.dat
Out[1]= out1.dat
Out[2]= 6.7
8.2
5.3
If you want to use data purely within Mathematica, then the best way to keep it in a file is usually
as a complete Mathematica expression, with all its structure preserved, as discussed on page 623. But
if you want to exchange data with other programs, it is often more convenient to have the data in a
simple list or table format.
This exports a two-dimensional array
of data.
In[5]:= !!out2.dat
Out[4]= out2.dat
5.6e12
3
5
Out[6]=
7.2e12
If you have a file in which each line consists of a single number, then you can use
Import["file", "List"] to import the contents of the file as a list of numbers. If each line consists of
a sequence of numbers separated by tabs or spaces, then Import["file", "Table"] will yield a list of
lists of numbers. If the file contains items that are not numbers, then these are returned as Mathematica
strings.
643
In[8]:= !!out3.dat
Out[7]= out3.dat
first
second
3.4
7.8
In[10]:= InputForm[%]
Import["file", "List"]
Import["file", "Table"]
Import["file", "Text"]
Import["file", "Lines"]
Import["file", "Words"]
In[11]:= Export["out4.dat",
{"The first line.", "The second line."}, "Lines"]
Out[11]= out4.dat
In[12]:= !!out4.dat
The first line.
The second line.
Out[15]//InputForm=
{"The", "first", "line.", "The", "second", "line."}
644
ReadList["file", Number]
In[1]:= !!numbers
11.1
44.4
22.2
55.5
33.3
66.6
ReadList can handle numbers which are given in Fortran-like E notation. Thus, for example,
ReadList will read 2.5E+5 as . Note that ReadList can handle numbers with any number of
digits of precision.
645
In[5]:= !!bignum
ReadList["file", type]
ReadList["file", type, n]
4.5E-5
2.5E2
7.8E4
-8.9
ReadList can read not only numbers, but also a variety of other types of object. Each type of object
is specified by a symbol such as Number.
Here is a file containing text.
In[7]:= !!strings
Here is text.
And more text.
Out[8]= H, e, r, e, , i, s, , t, e, x, t, ., ,
, A, n, d, , m, o, r, e, , t, e, x, t, .,
Out[9]= 72, 101, 114, 101, 32, 105, 115, 32, 116, 101,
120, 116, 46, 32, 10, 65, 110, 100, 32, 109,
111, 114, 101, 32, 116, 101, 120, 116, 46, 10
Out[10]= 72, 101, 114, 101, 32, 105, 115, 32, 116, 101,
120, 116, 46, 32, 65, 110, 100, 32, 109,
111, 114, 101, 32, 116, 101, 120, 116, 46
646
Byte
Character
Real
Number
Word
Record
String
Expression
Hold[Expression]
ReadList allows you to read words from a file. It considers a word to be any sequence of
characters delimited by word separators. You can set the option WordSeparators to specify the strings
you want to treat as word separators. The default is to include spaces and tabs, but not to include, for
example, standard punctuation characters. Note that in all cases successive words can be separated
by any number of word separators. These separators are never taken to be part of the actual words
returned by ReadList .
option name
default value
RecordLists
False
RecordSeparators
{"\n"}
WordSeparators
NullRecords
False
NullWords
False
TokenWords
{}
647
Mathematica considers any data file to consist of a sequence of records. By default, each line is
considered to be a separate record. In general, you can set the option RecordSeparators to give a list
of separators for records. Note that words can never cross record separators. As with word separators,
any number of record separators can exist between successive records, and these separators are not
considered to be part of the records themselves.
By default, each line of the file is
considered to be a record.
In[14]:= !!sentences
In[17]:= !!source
f[x] (: function f :)
g[x] (: function g :)
In[18]:= InputForm[
ReadList["source", Record, RecordSeparators -> { }]
]
Out[18]//InputForm=
{"f[x] (: function f :)\ng[x] (: function g :)\n"}
648
Mathematica usually allows any number of appropriate separators to appear between successive
records or words. Sometimes, however, when several separators are present, you may want to assume
that a null record or null word appears between each pair of adjacent separators. You can do this
by setting the options NullRecords -> True or NullWords -> True.
Here is a file containing words
separated by colons.
In[21]:= !!words
first:second::fourth:::seventh
Out[22]= first, second, fourth, seventh
In most cases, you want words to be delimited by separators which are not themselves considered
as words. Sometimes, however, it is convenient to allow words to be delimited by special token
words, which are themselves words. You can give a list of such token words as a setting for the
option TokenWords .
Here is some text.
In[24]:= !!language
22*a*b+56*c+13*a*d
Out[25]= 22, [, a, [, b, , 56, [, c, , 13, [, a, [, d
You can use ReadList to read Mathematica expressions from files. In general, each expression must
end with a newline, although a single expression may go on for several lines.
Here is a file containing text that can
be used as Mathematica input.
In[26]:= !!exprs
x + y +
z
2^8
Out[27]= x y z, 256
649
ReadList can insert the objects it reads into any Mathematica expression. The second argument
to ReadList can consist of any expression containing symbols such as Number and Word specifying
objects to read. Thus, for example, ReadList["file", {Number, Number}] inserts successive pairs of
numbers that it reads into lists. Similarly, ReadList["file", Hold[Expression]] puts expressions that
it reads inside Hold.
If ReadList reaches the end of your file before it has finished reading a particular set of objects
you have asked for, then it inserts the special symbol EndOfFile in place of the objects it has not yet
read.
Here is a file of numbers.
In[29]:= !!numbers
11.1
44.4
ReadList["!command", type]
ReadList[stream, type]
22.2
55.5
33.3
66.6
OpenRead["file"]
OpenRead["!command"]
Read[stream, type]
Skip[stream, type]
Skip[stream, type, n]
Close[stream]
ReadList allows you to read all the data in a particular file or input stream. Sometimes, however,
you want to get data a piece at a time, perhaps doing tests to find out what kind of data to expect
next.
When you read individual pieces of data from a file, Mathematica always remembers the current
point that you are at in the file. When you call OpenRead , Mathematica sets up an input stream from
650
a file, and makes your current point the beginning of the file. Every time you read an object from
the file using Read, Mathematica sets your current point to be just after the object you have read.
Using Skip, you can advance the current point past a sequence of objects without actually reading
the objects.
Here is a file of numbers.
In[32]:= !!numbers
11.1
44.4
22.2
55.5
33.3
66.6
Out[34]= 11.1
In[38]:= Close[snum]
Out[38]= numbers
You can use the options WordSeparators and RecordSeparators in Read and Skip just as you do
in ReadList .
Note that if you try to read past the end of file, Read returns the symbol EndOfFile .
get a list of all the lines in the file that contain the specified
text
get a list of the first n lines that contain the specified text
In[1]:= !!textfile
Here is the first line of text.
And the second.
And the third. Here is the end.
651
Out[3]=
By default, FindList scans successive lines of a file, and returns those lines which contain the text you
specify. In general, however, you can get FindList to scan successive records, and return complete
records which contain specified text. As in ReadList, the option RecordSeparators allows you to
tell Mathematica what strings you want to consider as record separators. Note that by giving a pair
of lists as the setting for RecordSeparators , you can specify different left and right separators. By
doing this, you can make FindList search only for text which is between specific pairs of separators.
This finds all sentences ending with
a period which contain And.
option name
default value
RecordSeparators
{"\n"}
AnchoredSearch
False
WordSeparators
WordSearch
False
IgnoreCase
False
In general, FindList finds text that appears anywhere inside a record. By setting the option
WordSearch -> True, however, you can tell FindList to require that the text it is looking for appears
as a separate word in the record. The option WordSeparators specifies the list of separators for words.
The text th does appear in the file, but
not as a word. As a result, the
FindList fails.
652
It is often useful to call FindList on lists of files generated by functions such as FileNames .
FindList["!command", ... ]
In[8]:= !date
Sat Jun 28 01:19:40 CDT 2003
Out[8]= 0
OpenRead["file"]
OpenRead["!command"]
Find[stream, text]
Close[stream]
FindList works by making one pass through a particular file, looking for occurrences of the text
you specify. Sometimes, however, you may want to search incrementally for successive occurrences
of a piece of text. You can do this using Find.
In order to use Find, you first explicitly have to open an input stream using OpenRead. Then, every
time you call Find on this stream, it will search for the text you specify, and make the current point in
the file be just after the record it finds. As a result, you can call Find several times to find successive
pieces of text.
This opens an input stream for
textfile .
653
In[13]:= Close[stext]
Out[13]= textfile
Once you have an input stream, you can mix calls to Find, Skip and Read. If you ever call
FindList or ReadList , Mathematica will immediately read to the end of the input stream.
This opens the input stream.
In[19]:= Close[stext]
Out[16]= And
Out[19]= textfile
StreamPosition[stream]
SetStreamPosition[stream, n]
SetStreamPosition[stream, 0]
SetStreamPosition[stream, Infinity]
set the current point to the end of a stream
Finding and setting the current point in a stream.
Functions like Read, Skip and Find usually operate on streams in an entirely sequential fashion.
Each time one of the functions is called, the current point in the stream moves on.
Sometimes, you may need to know where the current point in a stream is, and be able to reset it.
On most computer systems, StreamPosition returns the position of the current point as an integer
giving the number of bytes from the beginning of the stream.
654
In[21]:= StreamPosition[stext]
Out[21]= 0
In[23]:= StreamPosition[stext]
Out[23]= 31
In[24]:= SetStreamPosition[stext, 5]
Out[24]= 5
In[26]:= Close[stext]
Out[26]= textfile
StringToStream["string"]
Close[stream]
Out[2]= A
655
In[4]:= Close[str]
Out[4]= String
Input streams associated with strings work just like those with files. At any given time, there is a current position in the stream, which advances when you use functions like Read. The current position is
given as the number of bytes from the beginning of the string by the function StreamPosition[stream] .
You can explicitly set the current position using SetStreamPosition[stream, n].
Here is an input stream associated
with a string.
In[6]:= StreamPosition[str]
Out[6]= 0
Out[7]= 123
In[8]:= StreamPosition[str]
In[9]:= SetStreamPosition[str, 1]
In[13]:= Close[str]
Out[8]= 3
Out[9]= 1
Out[10]= 23
Out[11]= 11
Out[12]= EndOfFile
Out[13]= String
Particularly when you are processing large volumes of textual data, it is common to read fairly
long strings into Mathematica, then to use StringToStream to allow further processing of these strings
within Mathematica. Once you have created an input stream using StringToStream , you can read
and search the string using any of the functions discussed for files above.
This puts the whole contents of
textfile into a string.
656
In[17]:= SetStreamPosition[str, 0]
In[20]:= Close[str]
Out[17]= 0
Out[18]= the
Out[19]= first
Out[20]= String
657
MathLink provides a general interface for external programs to communicate with Mathematica.
Many standard software systems now have MathLink compatibility either built in or available in
add-on modules.
In addition, the MathLink Developer Kit bundled with most versions of Mathematica provides the
tools you need to create your own MathLink-compatible programs.
Once you have a MathLink-compatible program, you can transparently establish a link between it
and Mathematica.
The link can either be on a single computer, or it can be over a network, potentially with a different
type of computer at each end.
658
MathLink-compatible programs range from very simple to very complex. A minimal MathLinkcompatible program is just a few lines long. But it is also possible to build very large and sophisticated MathLink-compatible programs. Indeed, the Mathematica notebook front end is one example of
a sophisticated MathLink-compatible program.
Much of the power of MathLink comes from its use of Mathematica expressions. The basic idea
is that MathLink provides a way to exchange Mathematica expressions between programs, and such
expressions can represent absolutely any kind of data.
An array of numbers.
A collection of geometrical objects.
A sequence of commands.
A stream of text.
Records in a database.
The cells of a Mathematica notebook.
A few examples of data represented by Mathematica expressions in MathLink.
The MathLink library consists of a collection of routines that allow external programs to send and
receive Mathematica expressions.
The MathLink Developer Kit provides utilities for incorporating these routines into external programs. Utilities are included for a variety of languages, although in this chapter we discuss mainly
the case of C.
An important feature of the MathLink library is that it is completely platform independent: it can
transparently use any interprogram communication mechanism that exists on your computer system.
Install["prog"]
Uninstall[link]
659
In[1]:= Install["bitprog"]
In[2]:= BitShift[111, 3]
Out[2]= 13
When you have a package written in the Mathematica language a single version will run unchanged
on any computer system. But external programs typically need to be compiled separately for every
different type of computer.
Mathematica has a convention of keeping versions of external programs in directories that are named
after the types of computers on which they will run. And assuming that this convention has been
followed, Install["prog"] should always install the version of prog appropriate for the particular
kind of computer that you are currently using.
Install["name`"]
When you ask to read in a Mathematica language file using <<name`, Mathematica will automatically
search all directories in the list $Path in order to find a file with the appropriate name. Similarly, if
you use Install["name`"] Mathematica will automatically search all directories in $Path in order to
find an external program with the name name.exe. Install["name`"] allows you to install programs
that are stored in a central directory without explicitly having to specify their location.
660
:Begin:
:Function:
f
:Pattern:
f[x_Integer, y_Integer]
:Arguments:
{x, y}
:ArgumentTypes: {Integer, Integer}
:ReturnType:
Integer
:End:
A file f.tm containing a MathLink template for an external function f.
:Begin:
:Function:
:Pattern:
:Arguments:
:ArgumentTypes:
:ReturnType:
:End:
:Evaluate:
Once you have constructed a MathLink template for a particular external function, you have to
combine this template with the actual source code for the function. Assuming that the source code is
written in the C programming language, you can do this just by adding a line to include the standard
MathLink header file, and then inserting a small main program.
Include the standard MathLink header
file.
#include "mathlink.h"
661
Note that the form of main required on different systems may be slightly different. The release
notes included in the MathLink Developer Kit on your particular computer system should give the
appropriate form.
mcc
mprep
MathLink templates are conventionally put in files with names of the form file.tm. Such files can
also contain C source code, interspersed between templates for different functions.
Once you have set up the appropriate files, you then need to process the MathLink template information, and compile all of your source code. Typically you do this by running various external
programs, but the details will depend on your computer system.
Under Unix, for example, the MathLink Developer Kit includes a program named mcc which will
preprocess MathLink templates in any file whose name ends with .tm, and then call cc on the resulting
C source code. mcc will pass command-line options and other files directly to cc.
This preprocesses f.tm, then compiles
the resulting C source file together
with the file f.c.
In[1]:= Install["f.exe"]
In[2]:= f[6, 9]
In[3]:= f[2^31-1, 5]
Out[2]= 15
Out[3]= 2147483644
On systems other than Unix, the MathLink Developer Kit typically includes a program named
mprep, which you have to call directly, giving as input all of the .tm files that you want to preprocess.
mprep will generate C source code as output, which you can then feed to a C compiler.
662
Install["prog"]
Uninstall[link]
Links["prog"]
Links[ ]
LinkPatterns[link]
In[4]:= Links["f.exe"]
In[5]:= LinkPatterns[%[[1]]]
In[6]:= ?f
Global`f
f[x_Integer, y_Integer] := ExternalCall[
LinkObject["f.exe", 4, 4], CallPacket[0, {x, y}]]
When a MathLink template file is processed, two basic things are done. First, the :Pattern: and
:Arguments: specifications are used to generate a Mathematica definition that calls an external function
via MathLink. And second, the :Function: , :ArgumentTypes: and :ReturnType: specifications are
used to generate C source code that calls your function within the external program.
:Begin:
:Function:
prog_add
:Pattern:
SkewAdd[x_Integer, y_Integer:1]
:Arguments:
:ReturnType:
:End:
Integer
663
Both the :Pattern: and :Arguments: specifications in a MathLink template can be any Mathematica
expressions. Whatever you give as the :Arguments: specification will be evaluated every time you
call the external function. The result of the evaluation will be used as the list of arguments to pass to
the function.
Sometimes you may want to set up Mathematica expressions that should be evaluated not when an
external function is called, but instead only when the external function is first installed.
You can do this by inserting :Evaluate: specifications in your MathLink template. The expression
you give after :Evaluate: can go on for several lines: it is assumed to end when there is first a blank
line, or a line that does not begin with spaces or tabs.
This specifies that a usage message for
SkewAdd should be set up when the
external program is installed.
:Evaluate:
SkewAdd::usage = "SkewAdd[x, y] performs
a skew addition in an external program."
When an external program is installed, the specifications in its MathLink template file are used in
the order they were given. This means that any expressions given in :Evaluate: specifications that
appear before :Begin: will have been evaluated before definitions for the external function are set up.
Here are Mathematica expressions to be
evaluated before the definitions for
external functions are set up.
:Evaluate:
:Evaluate:
:Evaluate:
:Evaluate:
:Begin:
:Function:
:Pattern:
:Arguments:
:ArgumentTypes:
:ReturnType:
:End:
f
XF1[x_Integer, y_Integer]
x, y
Integer, Integer
Integer
:Begin:
:Function:
:Pattern:
:Arguments:
:ArgumentTypes:
:ReturnType:
:End:
g
XF2[x_?NumberQ]
x
Real
Real
:Evaluate:
:Evaluate:
BeginPackage["XPack`"]
XF1::usage = "XF1[x, y] is one external function."
XF2::usage = "XF2[x] is another external function."
Begin["`Private`"]
End[ ]
EndPackage[ ]
664
double g(double x)
return x*x;
By using :Evaluate: specifications, you can evaluate Mathematica expressions when an external
program is first installed. You can also execute code inside the external program at this time simply
by inserting the code in main() before the call to MLMain(). This is sometimes useful if you need to
initialize the external program before any functions in it are used.
MLEvaluateString(stdlink, "string")
return i - j;
}
In[7]:= Install["diffprog"]
In[8]:= diff[4, 7]
negative
Out[8]= 3
Note that any results generated in the evaluation requested by MLEvaluateString() are ignored.
To make use of such results requires full two-way communication between Mathematica and external
programs, as discussed on page 687.
665
Mathematica specification
C specification
Integer
integer
int
Real
floating-point number
double
IntegerList
list of integers
int *, long
RealList
double *, long
String
character string
char *
Symbol
symbol name
char *
Manual
void
:Begin:
:Function:
:Pattern:
:Arguments:
:ArgumentTypes:
:ReturnType:
:End:
h
h[a_List]
a
IntegerList
Integer
int i, tot=0;
for(i=0; i<alen; i++)
tot += a[i];
return tot;
In[1]:= Install["hprog"]
Out[1]= LinkObject
hprog, 4, 4
666
In[3]:= h[67]
Out[3]= h 67
Out[4]= $Failed
You can mix basic types of arguments in any way you want. Whenever you use IntegerList or
RealList, however, you have to include an extra argument in your C program to represent the length
of the list.
IntegerList, RealList, Integer
Here is an :ArgumentTypes:
specification.
:ArgumentTypes:
void f(int *a, long alen, double *b, long blen, int c)
Note that when a list is passed to a C program by MathLink its first element is assumed to be at
position 0, as is standard in C, rather than at position 1, as is standard in Mathematica.
In addition, following C standards, character strings specified by String are passed as char *
objects, terminated by \0 null bytes. Page 679 discusses how to handle special characters.
MLPutInteger(stdlink, int i)
MLPutReal(stdlink, double x)
667
When you use a MathLink template file, what mprep and mcc actually do is to create a C program
that includes explicit calls to MathLink library functions. If you want to understand how MathLink
works, you can look at the source code of this program. Note when you use mcc, you typically need
to give a -g option, otherwise the source code that is generated is automatically deleted.
If your external function just returns a single integer or floating-point number, then you can specify
this just by giving Integer or Real as the :ReturnType: in your MathLink template file. But because
of the way memory allocation and deallocation work in C, you cannot directly give :ReturnType:
specifications such as IntegerList or RealList. And instead, to return such structures, you must explicitly call MathLink library functions within your C program, and give Manual as the :ReturnType:
specification.
668
:Begin:
:Function:
:Pattern:
:Arguments:
:ArgumentTypes:
:ReturnType:
:End:
void bits(int i) {
bits
bits[i_Integer]
i
Integer
Manual
int a[32], k;
for(k=0; k<32; k++)
a[k] = i%2;
i >>= 1;
if (i==0) break;
if (k<32) k++;
MLPutIntegerList(stdlink, a, k);
return ;
}
In[5]:= Install["bitsprog"]
In[6]:= bits[14]
Out[6]= 0, 1, 1, 1
If you declare an array in C as int a[n1][n2][n3] then you can use MLPutIntegerArray() to
send it to Mathematica as a depth 3 list.
669
...
int a[8][16][100];
...
You can use MathLink functions to create absolutely any Mathematica expression. The basic idea is
to call a sequence of MathLink functions that correspond directly to the FullForm representation of
the Mathematica expression.
This sets up the Mathematica function
Plus with 2 arguments.
MLPutInteger(stdlink, 77);
MLPutSymbol(stdlink, "x");
In general, you first call MLPutFunction() , giving the head of the Mathematica function you want
to create, and the number of arguments it has. Then you call other MathLink functions to fill in each
of these arguments in turn. Section 2.1 discusses the general structure of Mathematica expressions and
the notion of heads.
This creates a Mathematica list with 2
elements.
MLPutIntegerList(stdlink, r, 10);
MLPutReal(stdlink, 4.5);
MLPutInteger(stdlink, 11);
670
MLPutIntegerArray() and MLPutRealArray() allow you to send arrays which are laid out in
memory in the one-dimensional way that C pre-allocates them. But if you create arrays during the
execution of a C program, it is more common to set them up as nested collections of pointers. You
can send such arrays to Mathematica by using a sequence of MLPutFunction() calls, ending with an
MLPutIntegerList() call.
...
int ***a;
...
It is important to realize that any expression you create using MathLink functions will be evaluated as soon as it is sent to Mathematica. This means, for example, that if you wanted to transpose
an array that you were sending back to Mathematica, all you would need to do is to wrap a
Transpose around the expression representing the array. You can then do this simply by calling
MLPutFunction(stdlink, "Transpose", 1); just before you start creating the expression that represents the array.
The idea of post-processing data that you send back to Mathematica has many uses. One example
is as a way of sending lists whose length you do not know in advance.
This creates a list in Mathematica by
explicitly appending successive
elements.
In[9]:= Flatten[t]
671
In order to call MLPutIntegerList() , you need to know the length of the list you want to send.
But by creating a sequence of nested Sequence objects, you can avoid having to know the length of
your whole list in advance.
This sets up the List around your
result.
MLPutInteger(stdlink, i );
}
Just as MathLink provides functions like MLPutInteger() to send data from an external program
into Mathematica, so also MathLink provides functions like MLGetInteger() that allow you to get data
from Mathematica into an external program.
The list that you give for :ArgumentTypes: in a MathLink template can end with Manual, indicating that after other arguments have been received, you will call MathLink functions to get additional
expressions.
672
:Begin:
:Function:
:Pattern:
:Arguments:
i, x, y
:ArgumentTypes:
Integer, Manual
:ReturnType:
:End:
Real
double f(int i) {
double x, y;
MLGetReal(stdlink, &x);
MLGetReal(stdlink, &y);
return i+x+y;
}
MathLink functions such as MLGetInteger(link, pi) work much like standard C library functions
such as fscanf(fp, "%d", pi). The first argument specifies the link from which to get data. The last
argument gives the address at which the data that is obtained should be stored.
673
:Begin:
:Function:
:Pattern:
f[a:___Integer]
:Arguments:
a
:ArgumentTypes:
Manual
:ReturnType:
:End:
Integer
int f(void) {
long n, i;
int a[MAX];
In simple cases, it is usually possible to ensure on the Mathematica side that the data you send
to an external program has the structure that is expected. But in general the return value from
MLCheckFunction() will be non-zero only if the data consists of a function with the name you
specify.
Note that if you want to get a nested collection of lists or other objects, you can do this by making
an appropriate sequence of calls to MLCheckFunction() .
674
When an external program gets data from Mathematica, it must set up a place to store the data. If
the data consists of a single integer, as in MLGetInteger(stdlink, &n), then it suffices just to have
declared this integer using int n.
But when the data consists of a list of integers of potentially any length, memory must be allocated
to store this list at the time when the external program is actually called.
int f(void) {
long n;
int *a;
...
MLDisownIntegerList(stdlink, a, n);
...
}
675
676
If you use String as an :ArgumentTypes: specification, then MathLink will automatically disown
the memory that is used to store the string after your function exits. This means that if you want to
continue to refer to the string, you must allocate memory for it, and explicitly copy each character in
it.
If you get a string using MLGetString() , however, then MathLink will not automatically disown the
memory used for the string when your function exits. As a result, you can continue referring to the
string. When you no longer need the string, you must nevertheless explicitly call MLDisownString()
in order to disown the memory associated with it.
If you know what function to expect in your external program, then it is usually simpler to call
MLCheckFunction() . But if you do not know what function to expect, you have no choice but to
call MLGetFunction() . If you do this, you need to be sure to call MLDisownSymbol() to disown the
memory associated with the name of the function that is found by MLGetFunction() .
Install["file"]
677
Install["file", LinkProtocol->"type"]
use the specified protocol for low-level data transport
$SystemID
Install["dir"]
Mathematica follows the convention that if prog is an ordinary file, then Install["prog"] will just
try to execute it. But if prog is a directory, then Mathematica will look for a subdirectory of that
directory whose name agrees with the current value of $SystemID , and will then try to execute a file
named prog within that subdirectory.
Even though the executable binary of an external program is inevitably different on different computer systems, it can still be the case that the source code in a language such as C from which this
binary is obtained can be essentially the same.
But to achieve portability in your C source code there are several points that you need to watch.
For a start, you should never make use of extra features of the C language or C run-time libraries
that happen to be provided on a particular system, but are not part of standard C. In addition, you
should try to avoid dealing with segmented or otherwise special memory models.
The include file mathlink.h contains standard C prototypes for all the functions in the MathLink
library. If your compiler does not support such prototypes, you can ignore them by giving the directive #define MLPROTOTYPES 0 before #include "mathlink.h" . But assuming that it does support
prototypes, your compiler will always be able to check that the calls you make to functions in the
MathLink library have arguments of appropriate types.
678
MLPutInteger()
MLGetInteger()
MLPutShortInteger()
MLGetShortInteger()
MLPutLongInteger()
MLGetLongInteger()
MLPutReal()
MLGetReal()
MLPutFloat()
MLGetFloat()
MLPutDouble()
MLGetDouble()
On some computer systems and with some compilers, a C language int may be equivalent to a
long. But the standard for the C language equally well allows int to be equivalent to short. And
if you are going to call MathLink library functions in a portable way, it is essential that you use the
same types as they do.
Once you have passed your data into the MathLink library functions, these functions then take care
of all further issues associated with differences between data representations on different computer
systems. Thus, for example, MathLink automatically swaps bytes when it sends data between big and
little endian machines, and converts floating-point formats losing as little precision as possible.
679
In simple C programs, it is typical to use strings that contain only ordinary ASCII characters. But
in Mathematica it is possible to have strings containing all sorts of special characters. These characters
are specified within Mathematica using Unicode character codes, as discussed on page 420.
C language char * strings typically use only 8 bits to store the code for each character. Unicode
character codes, however, require 16 bits. As a result, the functions MLPutUnicodeString() and
MLGetUnicodeString() work with arrays of unsigned short integers.
If you know that your program will not have to handle special characters, then you may find it
convenient to use MLPutByteString() and MLGetByteString() . These functions represent all characters directly using 8-bit character codes. If a special character is sent from Mathematica, then it will
be converted by MLGetByteString() to a fixed code that you specify.
Computer systems and compilers that have C run-time libraries based on the Unix model allow MathLink programs to have a main program of the form main(argc, argv) which simply calls
MLMain(argc, argv).
Some computer systems or compilers may however require main programs of a different form.
You should realize that you can do whatever initialization you want inside main() before calling
MLMain() . Once you have called MLMain(), however, your program will effectively go into an infinite
loop, responding to requests from Mathematica until the link to it is closed.
680
Session A
This starts up a link on port number
8000.
Session B
This connects to the link on port 8000.
Session A
This evaluates 15! and writes it to the
link.
Session B
This reads from the link, getting the
15! that was sent.
In[2]:= LinkRead[link]
In[3]:= LinkRead[link]
Out[2]= 1307674368000
Session A
Out[3]= 5.00032 1072
One use of MathLink connections between Mathematica sessions is simply as a way to transfer data
without using intermediate files.
681
Session B
This reads the expression from the link,
immediately wrapping it in Hold.
In[5]:= ReleaseHold[%]
Out[4]= Hold[2 + 2]
Out[5]= 4
When you call LinkWrite , it writes an expression to the MathLink connection and immediately
returns. But when you call LinkRead , it will not return until it has read a complete expression from
the MathLink connection.
You can tell whether anything is ready to be read by calling LinkReadyQ[link] . If LinkReadyQ returns True, then you can safely call LinkRead and expect immediately to start reading an expression.
But if LinkReadyQ returns False, then LinkRead would block until an expression for it to read had
been written by a LinkWrite in your other Mathematica session.
Session A
There is nothing waiting to be read on
the link, so if LinkRead were to be
called, it would block.
In[5]:= LinkReadyQ[link]
In[6]:= LinkWrite[link, x + y]
Out[5]= False
Session B
Session A
Now there is an expression waiting to
be read on the link.
In[6]:= LinkReadyQ[link]
In[7]:= LinkRead[link]
Out[6]= True
Out[7]= x + y
682
LinkCreate[ ]
LinkCreate["number"]
LinkConnect["number"]
LinkConnect["number@host"]
MathLink can use whatever mechanism for interprogram communication your computer system
supports. In setting up connections between concurrent Mathematica sessions, the most common
mechanism is internet TCP ports.
Most computer systems have a few thousand possible numbered ports, some of which are typically
allocated to standard system services.
You can use any of the unallocated ports for MathLink connections.
Session on frog.wolfram.com
This finds an unallocated port on
frog.wolfram.com .
Session on toad.wolfram.com
This connects to the port on
frog.wolfram.com .
Out[7]= LinkObject["2981@frog.wolfram.com", 5, 5]
Session on frog.wolfram.com
This reads the expression written on
toad.
In[9]:= LinkRead[link]
Out[9]= toad
By using internet ports for MathLink connections, you can easily transfer data between Mathematica
sessions on different machines. All that is needed is that an internet connection exists between the
machines.
Note that because MathLink is completely system independent, the computers at each end of a
MathLink connection do not have to be of the same type. MathLink nevertheless notices when they
are, and optimizes data transmission in this case.
683
In[2]:= LinkRead[link]
In[4]:= LinkRead[link]
In[5]:= LinkRead[link]
Out[2]= InputNamePacket[In[1]:= ]
Out[4]= OutputNamePacket[Out[1]= ]
Out[5]= ReturnTextPacket[3628800]
The basic way that the various different objects involved in a Mathematica session are kept organized
is by using MathLink packets. A MathLink packet is simply an expression with a definite head that
indicates its role or meaning.
EnterTextPacket["input"]
ReturnTextPacket["output"]
InputNamePacket["name"]
OutputNamePacket["name"]
In[6]:= LinkRead[link]
Out[6]= InputNamePacket[In[2]:= ]
684
In[8]:= LinkRead[link]
Out[8]= TextPacket[a
]
In[9]:= LinkRead[link]
In[10]:= LinkRead[link]
TextPacket["string"]
MessagePacket[symb, "tag"]
DisplayPacket["string"]
DisplayEndPacket["string"]
Out[9]= TextPacket[b
]
Out[10]= InputNamePacket[In[3]:= ]
If you enter input to Mathematica using EnterTextPacket["input"] , then Mathematica will automatically generate a string version of your output, and will respond with ReturnTextPacket["output"] .
But if you instead enter input using EnterExpressionPacket[expr] then Mathematica will respond
with ReturnExpressionPacket[expr] and will not turn your output into a string.
EnterExpressionPacket[expr]
ReturnExpressionPacket[expr]
InputNamePacket and OutputNamePacket packets are often convenient for making it possible to
tell the current state of a subsidiary Mathematica session. But you can suppress the generation of these
packets by calling the subsidiary Mathematica session with a string such as
"math -mathlink -batchoutput" .
685
Even if you suppress the explicit generation of InputNamePacket and OutputNamePacket packets,
Mathematica will still process any input that you give with EnterTextPacket or
EnterExpressionPacket as if you were entering an input line. This means for example that Mathematica will call $Pre and $Post, and will assign values to In[$Line] and Out[$Line] .
EvaluatePacket[expr]
ReturnPacket[expr]
In[14]:= LinkRead[link]
Out[14]= ReturnPacket
3628800
In[16]:= LinkRead[link]
In[17]:= LinkRead[link]
Out[16]= TextPacket[x
]
Out[17]= ReturnPacket[Null]
In[18]:= LinkWrite[link,
Unevaluated[EvaluatePacket[2 + Input["data ="]]]]
In[19]:= LinkRead[link]
In[20]:= LinkReadyQ[link]
In[22]:= LinkRead[link]
Out[19]= InputPacket[data =]
Out[20]= False
Out[22]= ReturnPacket[2 + x + y]
686
LinkInterrupt[link]
In[23]:= LinkWrite[link,
EnterTextPacket["FactorInteger[2^777-1]"]]
In[24]:= LinkReadyQ[link]
Out[24]= False
In[25]:= LinkInterrupt[link]
In[26]:= LinkRead[link]
Out[26]= MenuPacket[1, Interrupt> ]
$ParentLink
The global variable $ParentLink specifies the MathLink connection that a particular kernel will use
for input and output.
It is sometimes useful to reset $ParentLink in the middle of a Mathematica session, thereby effectively changing the front end to which the kernel is connected.
Session A
This creates a link on port 8000.
Session B
This connects to the link opened in
session A.
In[1]:= LinkConnect["8000"]
In[2]:= $ParentLink = %
Out[1]= LinkObject[8000@frog.wolfram.com, 4, 4]
687
Session A
Session A now acts as a front end to
session B and gets all output from it.
Much like the Mathematica kernel, the standard notebook front end for Mathematica is set up to
handle a certain set of MathLink packets.
Usually it is best to use functions like NotebookWrite and FrontEndExecute if you want to control
the Mathematica front end from the kernel. But in some cases you may find it convenient to send
packets directly to the front end using LinkWrite .
In[2]:= ?bits
Global`bits
bits[i_Integer] := ExternalCall[LinkObject[
"bitsprog", 4, 4], CallPacket[0, {i}]]
In[4]:= LinkRead[link]
Out[4]= 1, 1, 0, 0, 0, 0, 1
If you use Install several times on a single external program, Mathematica will open several
MathLink connections to the program. Each connection will however always correspond to a unique
LinkObject . Note that on some computer systems, you may need to make an explicit copy of the file
containing the external program in order to be able to call it multiple times.
688
$CurrentLink
:Begin:
:Function:
addto
:Pattern:
addto[$CurrentLink, n_Integer]
:Arguments:
n
:ArgumentTypes: Integer
:ReturnType:
Integer
:End:
int counter = 0;
int addto(int n)
counter += n;
return counter;
Out[7]= 10
Out[8]= 15
Out[9]= 30
If an external program maintains information about its state then you can use different instances of
the program to represent different states. $CurrentLink then provides a way to refer to each instance
of the program.
The value of $CurrentLink is temporarily set every time a particular instance of the program is
called, as well as when each instance of the program is first installed.
689
MLEvaluateString(stdlink, "string")
send input to Mathematica but return no results
Sending a string for evaluation by Mathematica.
The two-way nature of MathLink connections allows you not only to have Mathematica call an
external program, but also to have that external program call back to Mathematica.
In the simplest case, you can use the MathLink function MLEvaluateString() to send a string to
Mathematica. Mathematica will evaluate this string, producing whatever effects the string specifies, but
it will not return any results from the evaluation back to the external program.
To get results back you need explicitly to send an EvaluatePacket to Mathematica, and then read
the contents of the ReturnPacket that comes back.
...
MLEndPacket(stdlink);
MLGetInteger(stdlink, &ans);
...
MLEndPacket(stdlink)
When you can send Mathematica an EvaluatePacket[input] , it may in general produce many
packets in response, but the final packet should be ReturnPacket[output] . Page 695 will discuss how
to handle sequences of packets and expressions whose structure you do not know in advance.
690
In[1]:= Install[LinkConnect["2976@toad.wolfram.com"]]
In[2]:= f[16]
Out[1]= LinkObject[2976@toad.wolfram.com, 1]
Out[2]= 561243
External programs that are created using mcc or mprep always contain the code that is needed to
set up MathLink connections. If you start such programs directly from your operating system, they
will prompt you to specify what kind of connection you want. Alternatively, if your operating system
supports it, you can also give this information as a command-line argument to the external program.
prog -linkcreate
Install[LinkConnect["port@host"]]
Running an external program on a remote computer.
691
In debugger:
In Mathematica:
run -linkcreate
Install[LinkConnect["port"]]
Note that in order to get a version of an external program that can be run under a debugger, you
may need to specify -g or other flags when you compile the program.
Debugger
Set a breakpoint in the C function f.
(debug) break f
Breakpoint set: f: line 1
Mathematica session
This connects to the program running
under the debugger.
In[1]:= Install[LinkConnect["2981@frog.wolfram.com"]]
In[2]:= f[16]
Out[1]= LinkObject[2981@frog.wolfram.com, 1]
Debugger
(debug) Breakpoint: f(16)
(debug) continue
Now f returns.
Out[2]= 561243
Mathematica session
692
close a link
...
ml = MLLoopbackOpen(stdenv, &errno);
MLClose(ml);
You can use MLTransferExpression() to take an expression that you get via stdlink from
Mathematica, and save it in a local loopback link for later processing.
You can also use MLTransferExpression() to take an expression that you have built up on a local
loopback link, and transfer it back to Mathematica via stdlink .
693
...
MLTransferExpression(stdlink, ml);
You can put any sequence of expressions onto a loopback link. Usually you get the expressions off
the link in the same order as you put them on.
And once you have got an expression off the link it is usually no longer saved. But by using
MLCreateMark() you can mark a particular position in a sequence of expressions on a link, forcing
MathLink to save every expression after the mark so that you can go back to it later.
694
...
MLPutInteger(ml, 45);
MLPutInteger(ml, 33);
MLPutInteger(ml, 76);
MLGetInteger(ml, &i);
mark = MLCreateMark(ml);
MLGetInteger(ml, &i);
MLGetInteger(ml, &i);
MLGetInteger(ml, &i);
MLDestroyMark(ml, mark);
The way the MathLink library is implemented, it is very efficient to open and close loopback links,
and to create and destroy marks in them. The only point to remember is that as soon as you create
a mark on a particular link, MathLink will save subsequent expressions that are put on that link, and
will go on doing this until the mark is destroyed.
MLTKFUNC
MLTKSYM
Mathematica symbol
MLTKINT
integer
MLTKREAL
MLTKSTR
695
floating-point number
character string
switch(MLGetNext(ml)) {
case MLTKFUNC:
MLGetArgCount(ml, &n);
recurse for head
for (i = 0; i < n; i++)
recurse for each argument
...
case MLTKSYM:
MLGetSymbol(ml, &name);
...
case MLTKINT:
MLGetInteger(ml, &i);
...
}
By using MLGetNext() it is straightforward to write programs that can read any expression. The
way MathLink works, the head and arguments of a function appear as successive expressions on the
link, which you read one after another.
Note that if you know that the head of a function will be a symbol, then you can use
MLGetFunction() instead of MLGetNext() . In this case, however, you still need to call
MLDisownSymbol() to disown the memory used to store the symbol name.
696
MLPutNext() specifies types of expressions using constants such as MLTKFUNC from the mathlink.h
header filejust like MLGetNext() .
When you do complicated operations, it is often convenient to check for errors only at the end. If
you find that an error occurred, you must then call MLClearError() to activate MathLink again.
697
After an error, it is common to want to discard the remainder of the packet or expression that you
are currently processing. You can do this using MLNewPacket() .
In some cases, you may want to set it up so that if an error occurs while you are processing
particular data, you can then later go back and reprocess the data in a different way. You can do
this by calling MLCreateMark() to create a mark before you first process the data, and then calling
MLSeekMark() to seek back to the mark if you need to reprocess the data. You should not forgot to call
MLDestroyMark() when you have finally finished with the dataotherwise MathLink will continue to
store it.
int MLAbort
If you interrupt Mathematica while it is in the middle of executing an external function, it will
typically give you the opportunity to try to abort the external function. If you choose to do this, what
will happen is that the global variable MLAbort will be set to 1 inside your external program.
MathLink cannot automatically back out of an external function call that has been made. So if
you have a function that can take a long time, you should explicitly check MLAbort every so often,
returning from the function if you find that the variable has been set.
698
MLENV MLInitialize(0)
#include "mathlink.h"
env = MLInitialize(0);
MLActivate(link);
...
}
Often the argv that you pass to MLOpenArgv() will come directly from the argv that is passed to
main() when your whole program is started. Note that MLOpenArgv() takes pointers to the beginning
and end of the argv array. By not using argc directly it avoids having to know the size of an int.
699
The elements in the argv array are character strings which mirror the arguments and options used
in the Mathematica functions LinkLaunch , LinkCreate and LinkConnect .
"-linklaunch"
"-linkcreate"
"-linkconnect"
"-linkname", "name"
"-linkprotocol", "protocol"
As an alternative to MLOpenArgv() you can use MLOpenString() , which takes parameters concatenated into a single character string with spaces in between.
Once you have successfully opened a MathLink connection to the Mathematica kernel, you can then
use standard MathLink functions to exchange data with it.
Once you have sent all the pieces of a packet using MLPutFunction() etc., MathLink requires you
to call MLEndPacket() to ensure synchronization and consistency.
One of the main issues in writing an external program which communicates directly with the
Mathematica kernel is handling all the various kinds of packets that the kernel can generate.
The function MLNextPacket() finds the head of the next packet that comes from the kernel, and
returns a constant that indicates the type of the packet.
700
Mathematica packet
constant
ReturnPacket[expr]
RETURNPKT
ReturnTextPacket["string"]
RETURNTEXTPKT
InputNamePacket["name"]
INPUTNAMEPKT
OutputNamePacket["name"]
OUTPUTNAMEPKT
TextPacket["string"]
TEXTPKT
MessagePacket[symb, "tag"]
MESSAGEPKT
DisplayPacket["string"]
DISPLAYPKT
DisplayEndPacket["string"]
DISPLAYENDPKT
InputPacket["prompt"]
INPUTPKT
CallPacket[i, list]
CALLPKT
If you want to write a complete front end to Mathematica, you will need to handle all of the possible
types of packets that the kernel can generate. Typically you can do this by setting up an appropriate
switch on the value returned by MLNextPacket() .
The MathLink Developer Kit contains sample source code for several simple but complete front
ends.
One feature of more sophisticated external programs such as front ends is that they may need to
perform operations while they are waiting for data to be sent to them by Mathematica. When you call
701
a standard MathLink library function such as MLNextPacket() your program will normally block until
all the data needed by this function is available.
You can avoid blocking by repeatedly calling MLReady() , and only calling functions like
MLNextPacket() when MLReady() no longer returns 0. MLReady() is the analog of the Mathematica
function LinkReadyQ .
Note that MathLink sometimes buffers the data that you tell it to send. To make sure that all
necessary data has been sent you should call MLFlush() . Only after doing this does it make sense to
call MLReady() and wait for data to be sent back.
702
In[n]
InString[n]
%n or Out[n]
Out[{n , n , ... }]
%% ... % (n times) or Out[-n]
MessageList[n]
$Line
In a standard interactive session, there is a sequence of input and output lines. Mathematica stores
the values of the expressions on these lines in In[n] and Out[n].
As indicated by the usual In[n]:= prompt, the input expressions are stored with delayed assignments. This means that whenever you ask for In[n], the input expression will always be re-evaluated
in your current environment.
This assigns a value to x.
In[1]:= x = 7
Out[1]= 7
In[2]:= x - x^2 + 5x - 1
Out[2]= 8
In[3]:= x =.
In[4]:= In[2]
Out[4]= 1 6 x x2
703
$HistoryLength
Mathematica by default stores all your input and output lines for the duration of the session. In
a very long session, this may take up a large amount of computer memory. You can nevertheless get rid of the input and output lines by explicitly clearing the values of In and Out, using
Unprotect[In, Out], followed by Clear[In, Out]. You can also tell Mathematica to keep only a
limited number of lines of history by setting the global variable $HistoryLength .
Note that at any point in a session, you can reset the line number counter $Line, so that for
example new lines are numbered so as to overwrite previous ones.
$PreRead
$Pre
$Post
$PrePrint
$SyntaxHandler
Mathematica provides a variety of hooks that allow you to insert functions to be applied to
expressions at various stages in the main loop. Thus, for example, any function you assign as the
value of the global variable $Pre will automatically be applied before evaluation to any expression
you give as input.
For a particular input line, the standard main loop begins by getting a text string of input. Particularly if you need to deal with special characters, you may want to modify this text string before it is
further processed by Mathematica. You can do this by assigning a function as the value of the global
variable $PreRead . This function will be applied to the text string, and the result will be used as the
actual input string for the particular input line.
704
In[8]:= $PreRead =.
Out[7]= 4, 5, 6
Once any $PreRead processing on an input string is finished, the string is read by Mathematica.
At this point, Mathematica may find that there is a syntax error in the string. If this happens, then
Mathematica calls whatever function you have specified as the value of $SyntaxHandler . It supplies
two arguments: the input string, and the character position at which the syntax error was detected.
With $SyntaxHandler you can, for example, generate an analysis of the syntax error, or call an editor.
If your function returns a string, then Mathematica will use this string as a new input string.
This specifies what Mathematica should
do when it gets a syntax error.
In[9]:= $SyntaxHandler =
(Print[StringForm["Error at char `1` in `2`",
#2, #1]]; $Failed)&
Out[9]= Print
Error at char #2 in #1; $Failed &
In[10]:= 3 +/+ 5
Syntax::sntxf: "3 +" cannot be followed by "/+ 5".
Once Mathematica has successfully read an input expression, it then evaluates this expression. Before
doing the evaluation, Mathematica applies any function you have specified as the value of $Pre, and
after the evaluation, it applies any function specified as the value of $Post. Note that unless the $Pre
function holds its arguments unevaluated, the function will have exactly the same effect as $Post.
$Post allows you to specify arbitrary post processing to be done on results obtained from Mathematica. Thus, for example, to make Mathematica get a numerical approximation to every result it
generates, all you need do is to set $Post = N.
This tells Mathematica to apply N to
every result it generates.
In[10]:= $Post = N
In[11]:= Sqrt[7]
In[12]:= $Post =.
Out[10]= N
Out[11]= 2.64575
As soon as Mathematica has generated a result, and applied any $Post function you have specified,
it takes the result, and assigns it as the value of Out[$Line] . The next step is for Mathematica to
705
print the result. However, before doing this, it applies any function you have specified as the value
of $PrePrint .
This tells Mathematica to shorten all
output to two lines.
In[15]:= $PrePrint =.
There are various kinds of output generated in a typical Mathematica session. In general, each kind
of output is sent to a definite output channel, as discussed on page 633. Associated with each output
channel, there is a global variable which gives a list of the output streams to be included in that
output channel.
$Output
$Echo
$Urgent
$Messages
$Display
$SoundDisplay
By modifying the list of streams in a given output channel, you can redirect or copy particular
kinds of Mathematica output. Thus, for example, by opening an output stream to a file, and including
that stream in the $Echo list, you can get each piece of input you give to Mathematica saved in a file.
Streams[ ]
Streams["name"]
$Input
The function Streams shows you all the input, output and other streams that are open at a particular point in a Mathematica session. The variable $Input gives the name of the current stream from
706
which Mathematica input is being taken at a particular point. $Input is reset, for example, during the
execution of a Get command.
$MessagePrePrint
$Language
There are various global parameters which determine the form of messages generated by Mathematica.
As discussed in Section 2.9.21, typical messages include a sequence of expressions which are combined with the text of the message through StringForm . $MessagePrePrint gives a function to be
applied to the expressions before they are printed. The default value of $MessagePrePrint is Short.
As discussed in Section 2.9.22, Mathematica allows you to specify the language in which you want
messages to be produced. In a particular Mathematica session, you can assign a list of language names
as the value of $Language .
Exit[ ] or Quit[ ]
$Epilog
Mathematica will continue in its main loop until you explicitly tell it to exit. Most Mathematica
interfaces provide special ways to do this. Nevertheless, you can always do it by explicitly calling
Exit or Quit.
Mathematica allows you to give a value to the global variable $Epilog to specify operations to
perform just before Mathematica actually exits. In this way, you can for example make Mathematica
always save certain objects before exiting.
$IgnoreEOF
As discussed in Section 2.8.5, Mathematica usually does not treat special characters in a special way.
There is one potential exception, however. With the default setting $IgnoreEOF = False, Mathematica
recognizes end-of-file characters. If Mathematica receives an end-of-file character as the only thing on
a particular input line in a standard interactive Mathematica session, then it will exit the session.
2.14.2 Dialogs
707
Exactly how you enter an end-of-file character depends on the computer system you are using.
Under Unix, for example, you typically press CONTROL-D.
Note that if you use Mathematica in a batch mode, with all its input coming from a file, then it
will automatically exit when it reaches the end of the file, regardless of the value of $IgnoreEOF .
2.14.2 Dialogs
Within a standard interactive session, you can create subsessions or dialogs using the Mathematica
command Dialog. Dialogs are often useful if you want to interact with Mathematica while it is in the
middle of doing a calculation. As mentioned in Section 2.6.11, TraceDialog for example automatically calls Dialog at specified points in the evaluation of a particular expression. In addition, if you
interrupt Mathematica during a computation, you can typically inspect its state using a dialog.
Dialog[ ]
Dialog[expr]
Return[ ]
Return[expr]
In[1]:= Dialog[ ]
In[2]:= 2^41
In[3]:= Return[ ]
Out[2]= 2199023255552
Out[1]= 2199023255552
When you exit a dialog, you can return a value for the dialog using Return[expr]. If you do not
want to return a value, and you have set $IgnoreEOF = False, then you can also exit a dialog simply
by giving an end-of-file character, at least on systems with text-based interfaces.
To evaluate this expression, Mathematica
initiates a dialog.
The value a + b returned from the
dialog is now inserted in the original
expression.
In[3]:= Return[a + b]
2
Out[2]= 1 a b
In starting a dialog, you will often find it useful to have some initial expression. If you use
Dialog[expr] , then Mathematica will start a dialog, using expr as the initial expression, accessible for
example as the value of %.
708
In[6]:= Return[%]
In[5]:= Return[444]
Out[4]= b c
Out[3]= 1 a4 , 444
Dialog effectively works by running a subsidiary version of the standard Mathematica main loop.
Each dialog you start effectively inherits various values from the overall main loop. Some of the
values are, however, local to the dialog, so their original values are restored when you exit the dialog.
Thus, for example, dialogs inherit the current line number $Line when they start. This means that
the lines in a dialog have numbers that follow the sequence used in the main loop. Nevertheless, the
value of $Line is local to the dialog. As a result, when you exit the dialog, the value of $Line reverts
to what it was in the main loop.
If you start a dialog on line 10 of your Mathematica session, then the first line of the dialog will be
labeled In[11]. Successive lines of the dialog will be labeled In[12], In[13] and so on. Then, when
you exit the dialog, the next line in your main loop will be labeled In[11]. At this point, you can
still refer to results generated within the dialog as Out[11], Out[12] and so on. These results will be
overwritten, however, when you reach lines In[12], In[13], and so on in the main loop.
In a standard Mathematica session, you can tell whether you are in a dialog by seeing whether
your input and output lines are indented. If you call a dialog from within a dialog, you will get two
levels of indentation. In general, the indentation you get inside d nested dialogs is determined by the
output form of the object DialogIndent[d] . By defining the format for this object, you can specify
how dialogs should be indicated in your Mathematica session.
709
Whatever setting you give for DialogSymbols , Dialog will always treat the values of $Line,
$Epilog and $MessageList as local. Note that if you give a value for $Epilog , it will automatically
be evaluated when you exit the dialog.
When you call Dialog, its first step is to localize the values of variables. Then it evaluates any
expression you have set for the option DialogProlog . If you have given an explicit argument to the
Dialog function, this is then evaluated next. Finally, the actual dialog is started.
When you exit the dialog, you can explicitly specify the return value using Return[expr]. If you
do not do this, the return value will be taken to be the last value generated in the dialog.
Date[z]
TimeZone[ ]
In[1]:= Date[ ]
Out[1]= 2003, 6, 28, 1, 20, 53.518907
The Mathematica Date function returns whatever your computer system gives as the current date and
time. It assumes that any corrections for daylight saving time and so on have already been done
by your computer system. In addition, it assumes that your computer system has been set for the
appropriate time zone.
The function TimeZone[ ] returns the current time zone assumed by your computer system. The
time zone is given as the number of hours which must be added to Greenwich mean time (GMT)
to obtain the correct local time. Thus, for example, U.S. eastern standard time (EST) corresponds to
time zone . Note that daylight saving time corrections must be included in the time zone, so U.S.
eastern daylight time (EDT) corresponds to time zone
.
This gives the current time zone
assumed by your computer system.
In[2]:= TimeZone[ ]
In[3]:= Date[9]
Out[2]= 5.
710
AbsoluteTime[ ]
SessionTime[ ]
TimeUsed[ ]
$TimeUnit
Time functions.
You should realize that on any computer system, there is a certain granularity in the times that
can be measured. This granularity is given as the value of the global variable $TimeUnit . Typically
or
of a second.
it is either about
Pause[n]
FromDate[date]
ToDate[time]
In[6]:= d = Date[ ]
Out[6]= 2003, 6, 28, 1, 21, 4.162634
Timing[expr]
,
AbsoluteTiming[expr]
711
Timing allows you to measure the CPU time, corresponding to the increase in TimeUsed , associated
with the evaluation of a single Mathematica expression. Note that only CPU time associated with the
actual evaluation of the expression within the Mathematica kernel is included. The time needed to
format the expression for output, and any time associated with external programs, is not included.
AbsoluteTiming allows you to measure absolute total elapsed time. You should realize, however,
that the time reported for a particular calculation by both AbsoluteTiming and Timing depends on
many factors.
First, the time depends in detail on the computer system you are using. It depends not only on
instruction times, but also on memory caching, as well as on the details of the optimization done in
compiling the parts of the internal code of Mathematica used in the calculation.
The time also depends on the precise state of your Mathematica session when the calculation was
done. Many of the internal optimizations used by Mathematica depend on details of preceding calculations. For example, Mathematica often uses previous results it has obtained, and avoids unnecessarily
re-evaluating expressions. In addition, some Mathematica functions build internal tables when they are
first called in a particular way, so that if they are called in that way again, they run much faster. For
all of these kinds of reasons, it is often the case that a particular calculation may not take the same
amount of time if you run it at different points in the same Mathematica session.
This gives the CPU time needed for
the calculation. The semicolon causes
the result of the calculation to be given
as Null.
In[9]:= Timing[100000!;]
In[10]:= Timing[100000!;]
In[11]:= AbsoluteTiming[100000!;]
Note that the results you get from Timing are only accurate to the timing granularity $TimeUnit
of your computer system. Thus, for example, a timing reported as 0 could in fact be as much as
$TimeUnit .
712
TimeConstrained[expr, t]
TimeConstrained[expr, t, failexpr]
Time-constrained calculation.
When you use Mathematica interactively, it is quite common to try doing a calculation, but to abort
the calculation if it seems to be taking too long. You can emulate this behavior inside a program by
using TimeConstrained . TimeConstrained tries to evaluate a particular expression for a specified
amount of time. If it does not succeed, then it aborts the evaluation, and returns either $Aborted , or
an expression you specify.
You can use TimeConstrained , for example, to have Mathematica try a particular approach to a
problem for a certain amount of time, and then to switch to another approach if the first one has
not yet succeeded. You should realize however that TimeConstrained may overrun the time you
specify if Mathematica cannot be interrupted during a particular part of a calculation. In addition,
you should realize that because different computer systems run at different speeds, programs that use
TimeConstrained will often give different results on different systems.
Particularly for symbolic computations, memory is usually the primary resource which limits the size
of computations you can do. If a computation runs slowly, you can always potentially let it run longer.
But if the computation generates intermediate expressions which simply cannot fit in the memory of
your computer system, then you cannot proceed with the computation.
Mathematica is careful about the way it uses memory. Every time an intermediate expression you
have generated is no longer needed, Mathematica immediately reclaims the memory allocated to it.
This means that at any point in a session, Mathematica stores only those expressions that are actually
needed; it does not keep unnecessary objects which have to be garbage collected later.
This gives the number of bytes of
memory currently being used by
Mathematica.
In[1]:= MemoryInUse[ ]
Out[1]= 947712
713
In[3]:= MemoryInUse[ ]
In[5]:= MemoryInUse[ ]
Out[3]= 989616
Out[5]= 954408
In[6]:= MaxMemoryUsed[ ]
Out[6]= 1467536
One issue that often comes up is exactly how much memory Mathematica can actually use on a
particular computer system. Usually there is a certain amount of memory available for all processes
running on the computer at a particular time. Sometimes this amount of memory is equal to the
physical number of bytes of RAM in the computer. Often, it includes a certain amount of virtual
memory, obtained by swapping data on and off a mass storage device.
When Mathematica runs, it needs space both for data and for code. The complete code of Mathematica is typically several megabytes in size. For any particular calculation, only a small fraction of
this code is usually used. However, in trying to work out the total amount of space available for
Mathematica data, you should not forget what is needed for Mathematica code. In addition, you must
include the space that is taken up by other processes running in the computer. If there are fewer jobs
running, you will usually find that your job can use more memory.
It is also worth realizing that the time needed to do a calculation can depend very greatly on how
much physical memory you have. Although virtual memory allows you in principle to use large
amounts of memory space, it is usually hundreds or even thousands of times slower to access than
physical memory. As a result, if your calculation becomes so large that it needs to make use of virtual
memory, it may run much more slowly.
MemoryConstrained[expr, b]
MemoryConstrained[expr, b, failexpr]
return failexpr if the memory constraint is not met
Memory-constrained computation.
MemoryConstrained works much like TimeConstrained. If more than the specified amount of
memory is requested, MemoryConstrained attempts to abort your computation. As with
714
TimeConstrained , there may be some overshoot in the actual amount of memory used before the
computation is aborted.
ByteCount[expr]
LeafCount[expr]
Although you may find ByteCount useful in estimating how large an expression of a particular kind
you can handle, you should realize that the specific results given by ByteCount can differ substantially
from one version of Mathematica to another.
Another important point is that ByteCount always gives you the maximum amount of memory
needed to store a particular expression. Often Mathematica will actually use a much smaller amount of
memory to store the expression. The main issue is how many of the subexpressions in the expression
can be shared.
In an expression like f[1 + x, 1 + x], the two subexpressions 1 + x are identical, but they may or
may not actually be stored in the same piece of computer memory. ByteCount gives you the number
of bytes needed to store expressions with the assumption that no subexpressions are shared. You
should realize that the sharing of subexpressions is often destroyed as soon as you use an operation
like the /. operator.
Nevertheless, you can explicitly tell Mathematica to share subexpressions using the function Share.
In this way, you can significantly reduce the actual amount of memory needed to store a particular
expression.
Share[expr]
Share[ ]
On most computer systems, the memory used by a running program is divided into two parts:
memory explicitly allocated by the program, and stack space. Every time an internal routine is
called in the program, a certain amount of stack space is used to store parameters associated with the
call. On many computer systems, the maximum amount of stack space that can be used by a program
must be specified in advance. If the specified stack space limit is exceeded, the program usually just
exits.
In Mathematica, one of the primary uses of stack space is in handling the calling of one Mathematica
function by another. All such calls are explicitly recorded in the Mathematica Stack discussed in Sec-
715
tion 2.6.12. You can control the size of this stack by setting the global parameter $RecursionLimit .
You should be sure that this parameter is set small enough that you do not run out of stack space on
your particular computer system.
$Notebooks
Mathematica is usually used interactively, but it can also operate in a batch modesay taking input
from a file and writing output to a file. In such a case, a program cannot for example expect to get
interactive input from the user.
$BatchInput
$BatchOutput
The Mathematica kernel is a process that runs under the operating system on your computer. Within
Mathematica there are several global variables that allow you to find the characteristics of this process
and its environment.
716
$CommandLine
$ParentLink
$ProcessID
$ParentProcessID
$UserName
Environment["var"]
If you have a variable such as x in a particular Mathematica session, you may or may not want
that variable to be the same as an x in another Mathematica session. In order to make it possible to
maintain distinct objects in different sessions, Mathematica supports the variable $SessionID , which
uses information such as starting time, process ID and machine ID to try to give a different value for
every single Mathematica session, whether it is run on the same computer or a different one.
$SessionID
Mathematica provides various global variables that allow you to tell which version of the kernel you
are running. This is important if you write programs that make use of features that are, say, new in
Version 5. You can then check $VersionNumber to find out if these features will be available.
$Version
$ReleaseNumber
$InstallationDate
,
$VersionNumber
$CreationDate
$ProductInformation
717
Mathematica itself is set up to be as independent of the details of the particular computer system on
which it is run as possible. However, if you want to access external aspects of your computer system,
then you will often need to find out its characteristics.
$System
$SystemID
$ProcessorType
$MachineType
$ByteOrdering
$OperatingSystem
$SystemCharacterEncoding
Mathematica uses the values of $SystemID to label directories that contain versions of files for different computer systems, as discussed on pages 627 and 677. Computer systems for which $SystemID
is the same will normally be binary compatible.
$OperatingSystem has values such as "Unix" and "MacOS". By testing $OperatingSystem you can
determine whether a particular external program is likely to be available on your computer system.
This gives some characteristics of the
computer system used to generate the
examples for this book.
718
$MachineName
$MachineDomain
$MachineID
$LicenseID
$LicenseExpirationDate
$NetworkLicense
$LicenseServer
$LicenseProcesses
$MaxLicenseProcesses
$PasswordFile
Variables associated with license management.
Part 3
Part 1 described how to do basic mathematics with Mathematica.
For many kinds of calculations, you will need to know nothing
more. But if you do want to use more advanced mathematics, this
part discusses how to do it in Mathematica.
This part goes through the various mathematical functions and
methods that are built into Mathematica. Some calculations can be
done just by using these built-in mathematical capabilities. For
many specific calculations, however, you will need to use application
packages that have been written in Mathematica. These packages
build on the mathematical capabilities discussed in this part, but
add new functions for doing special kinds of calculations.
Much of what is said in this part assumes a knowledge of mathematics at an advanced undergraduate level. If you do not understand a particular section, then you can probably assume that you
will not need to use that section.
Part 3
Advanced Mathematics in
Mathematica
3.1
Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . 722
3.2
3.3
3.4
3.5
Calculus . . . . . . . . . . . . . . . . . . . . . . . . . . . 853
3.6
3.7
3.8
3.9
3.10
722
3.1 Numbers
3.1.1 Types of Numbers
Four underlying types of numbers are built into Mathematica.
Integer
Rational
Real
Complex
In[1]:= 12344/2222
In[2]:= 5456.
In[3]:= 4.54543523454543523453452345234543
In[4]:= 4 + 7/8 I
In[5]:= 4 + 5.6 I
Out[2]= 5456.
123
123.
123.0000000000000
123. + 0. I
6172
Out[1]=
1111
Out[3]= 4.5454352345454352345345234523454
7
Out[4]= 4
8
Out[5]= 4 5.6
an exact integer
an approximate real number
an approximate real number with a certain precision
a complex number with approximate real number
components
723
You can distinguish different types of numbers in Mathematica by looking at their heads. (Although
numbers in Mathematica have heads like other expressions, they do not have explicit elements which
you can extract.)
The object 123 is taken to be an exact
integer, with head Integer .
In[6]:= Head[123]
In[7]:= Head[123.]
NumberQ[x]
IntegerQ[x]
Out[6]= Integer
Out[7]= Real
EvenQ[x]
OddQ[x]
PrimeQ[x]
Head[x]===type
In[8]:= NumberQ[5.6]
In[9]:= IntegerQ[5.]
Out[8]= True
Out[9]= False
If you use complex numbers extensively, there is one subtlety you should be aware of. When you
enter a number like 123., Mathematica treats it as an approximate real number, but assumes that its
imaginary part is exactly zero. Sometimes you may want to enter approximate complex numbers with
imaginary parts that are zero, but only to a certain precision.
When the imaginary part is the exact
integer 0, Mathematica simplifies
complex numbers to real ones.
Out[10]= Integer
Out[11]= Complex
The distinction between complex numbers whose imaginary parts are exactly zero, or are only zero
to a certain precision, may seem like a pedantic one. However, when we discuss, for example, the
interpretation of powers and roots of complex numbers in Section 3.2.7, the distinction will become
significant.
724
One way to find out the type of a number in Mathematica is just to pick out its head using
Head[expr]. For many purposes, however, it is better to use functions like IntegerQ which explicitly
test for particular types. Functions like this are set up to return True if their argument is manifestly
of the required type, and to return False otherwise. As a result, IntegerQ[x] will give False, unless
x has an explicit integer value.
NumericQ[expr]
Pi is a symbol, so Pi + 3 is not
explicitly a number.
In[1]:= NumberQ[Pi + 3]
In[2]:= NumericQ[Pi + 3]
In[3]:= N[Pi + 3]
Out[1]= False
Out[2]= True
Out[3]= 6.14159
Mathematica knows that constants such as Pi are numeric quantities. It also knows that standard mathematical functions such as Log and Sin have numerical values when their arguments are numerical.
Log[2 + x] contains x, and is therefore
not a numeric quantity.
Out[5]= Log 2
In general, Mathematica assumes that any function which has the attribute NumericFunction will
yield numerical values when its arguments are numerical. All standard mathematical functions in
Mathematica already have this attribute. But when you define your own functions, you can explicitly
set the attribute to tell Mathematica to assume that these functions will have numerical values when
their arguments are numerical.
725
RealDigits[x, b]
RealDigits[x, b, len]
RealDigits[x, b, len, n]
FromDigits[list]
FromDigits[list, b]
In[2]:= RealDigits[123.4567890123456]
In[3]:= IntegerDigits[56, 2, 8]
In[4]:= FromDigits[%, 2]
b^^nnnn
BaseForm[x, b]
Numbers in other bases.
Out[3]= 0, 0, 1, 1, 1, 0, 0, 0
Out[4]= 56
a number in base b
print with x in base b
726
When the base is larger than 10, extra digits are represented by letters az.
The number in base 2 is
in
base 10.
In[5]:= 2^^100101
In[6]:= BaseForm[37, 2]
Out[5]= 37
Out[6]//BaseForm= 1001012
In[7]:= 16^^ffffaa00
Out[7]= 4294945280
Out[8]= 16776096
Out[9]//BaseForm= fffba016
in
In[10]:= 2^^101.100101
Out[10]= 5.57813
In[11]:= BaseForm[N[Sqrt[2], 30], 8]
Out[11]//BaseForm= 1.3240474631771674622042627661154678
Section 2.9.7 describes how to print numbers in various formats. If you want to create your own
formats, you will often need to use MantissaExponent to separate the pieces of real numbers.
MantissaExponent[x]
MantissaExponent[x, b]
727
Precision[x]
Accuracy[x]
In[2]:= Precision[x]
Out[1]= 93648.0474760830209737166901849
Out[2]= 30.
In[3]:= Accuracy[x]
In[4]:= x / 10^6
Out[3]= 25.0285
Out[4]= 0.0936480474760830209737166901849
An approximate real number always has some uncertainty in its value, associated with digits
beyond those known. One can think of precision as providing a measure of the relative size of this
uncertainty. Accuracy gives a measure of the absolute size of the uncertainty.
Mathematica is set up so that if a number x has uncertainty , then its true value can lie anywhere
in an interval of size from x to x . An approximate number with accuracy a is defined
to have uncertainty a , while a non-zero approximate number with precision p is defined to have
uncertainty /x/p .
728
Precision[x]
Accuracy[x]
log /x/
log
N[expr, n]
N[expr]
Mathematica distinguishes two kinds of approximate real numbers: arbitrary-precision numbers, and
machine-precision numbers or machine numbers. Arbitrary-precision numbers can contain any number
of digits, and maintain information on their precision. Machine numbers, on the other hand, always
contain the same number of digits, and maintain no information on their precision.
Here is a machine-number
approximation to .
In[7]:= N[Pi]
Out[7]= 3.14159
As discussed in more detail below, machine numbers work by making direct use of the numerical
capabilities of your underlying computer system. As a result, computations with them can often be
done more quickly. They are however much less flexible than arbitrary-precision numbers, and difficult numerical analysis can be needed to determine whether results obtained with them are correct.
Machine numbers.
MachinePrecision
$MachinePrecision
MachineNumberQ[x]
729
In[10]:= $MachinePrecision
Out[9]= MachinePrecision
Out[10]= 15.9546
When you enter an approximate real number, Mathematica has to decide whether to treat it as a
machine number or an arbitrary-precision number. Unless you specify otherwise, then if you give less
than $MachinePrecision digits, Mathematica will treat the number as machine precision, and if you
give more digits, it will treat the number as arbitrary precision.
123.4
123.45678901234567890
123.45678901234567890`
a machine-precision number
an arbitrary-precision number on some computer systems
a machine-precision number on all computer systems
123.456`200
123.456``200
1.234*^6
1.234`200*^6
2^^101.111`200
2^^101.111`200*^6
When Mathematica prints out numbers, it usually tries to give them in a form that will be as easy
as possible to read. But if you want to take numbers that are printed out by Mathematica, and then
later use them as input to Mathematica, you need to make sure that no information gets lost.
In standard output form, Mathematica
prints a number like this to six digits.
In[11]:= N[Pi]
In[12]:= InputForm[%]
Out[11]= 3.14159
Out[12]//InputForm= 3.141592653589793
Out[13]= 3.1415926535897932385
730
In[14]:= InputForm[%]
Out[14]//InputForm= 3.1415926535897932384626433832795028842`20.
Out[15]//InputForm= 3.1415926535897932385
InputForm[expr, NumberMarks->True]
use ` marks in all approximate numbers
InputForm[expr, NumberMarks->Automatic]
use ` only in arbitrary-precision numbers
InputForm[expr, NumberMarks->False]
never use ` marks
Controlling printing of numbers.
The default setting for the NumberMarks option, both in InputForm and in functions such as
ToString and OpenWrite is given by the value of $NumberMarks . By resetting $NumberMarks , therefore, you can globally change the way that numbers are printed in InputForm .
This makes Mathematica by default
always include number marks in input
form.
In[17]:= InputForm[N[Pi]]
Out[16]= True
Out[17]//InputForm= 3.141592653589793`
Out[18]//InputForm= 3.7730203009299398234*^260
In doing numerical computations, it is inevitable that you will sometimes end up with results that
are less precise than you want. Particularly when you get numerical results that are very close to
zero, you may well want to assume that the results should be exactly zero. The function Chop allows
you to replace approximate real numbers that are close to zero by the exact integer 0.
Chop[expr]
Chop[expr, dx]
Removing numbers close to zero.
731
In[20]:= Chop[%]
Out[20]= 1.
When you do a computation, Mathematica keeps track of which digits in your result could be
affected by unknown digits in your input. It sets the precision of your result so that no affected digits
are ever included. This procedure ensures that all digits returned by Mathematica are correct, whatever
the values of the unknown digits may be.
This evaluates to 30-digit
precision.
In[4]:= Precision[%]
Out[3]= 6.54806294024782443771409334943
Out[4]= 30.
Out[5]= 6.58965
Out[6]= 6.58964729492039788328481917496
In many computations, the precision of the results you get progressively degrades as a result of
roundoff error. A typical case of this occurs if you subtract two numbers that are close together.
The result you get depends on high-order digits in each number, and typically has far fewer digits of
precision than either of the original numbers.
732
The precision of the output from a function can depend in a complicated way on the precision of
the input. Functions that vary rapidly typically give less precise output, since the variation of the
output associated with uncertainties in the input is larger. Functions that are close to constants can
actually give output that is more precise than their input.
Functions like Sin that vary rapidly
typically give output that is less precise
than their input.
Here is e
evaluated to 20-digit
precision.
The result you get by adding the exact
integer 1 has a higher precision.
In[9]:= Sin[111111111.0000000000000000]
Out[9]= 0.2975351033349432
In[10]:= N[Exp[-40], 20]
Out[10]= 4.2483542552915889953 1018
In[11]:= 1 + %
Out[11]= 1.0000000000000000042483542552915889953
It is worth realizing that different ways of doing the same calculation can end up giving you results
with very different precisions. Typically, if you once lose precision in a calculation, it is essentially
impossible to regain it; in losing precision, you are effectively losing information about your result.
Here is a 40-digit number that is close
to 1.
In[13]:= 1 + x
In[14]:= Precision[%]
Out[12]= 0.9999999999999999999999999999990000000000
Out[13]= 1.999999999999999999999999999999000000000
Out[14]= 40.301
In[15]:= (x^2 - 1) / (x - 1)
Out[15]= 2.000000000
In[16]:= Precision[%]
Out[16]= 9.69897
The fact that different ways of doing the same calculation can give you different numerical answers
means, among other things, that comparisons between approximate real numbers must be treated with
care. In testing whether two real numbers are equal, Mathematica effectively finds their difference,
and tests whether the result is consistent with zero to the precision given.
733
In[17]:= 3 == 3.000000000000000000
Out[17]= True
The internal algorithms that Mathematica uses to evaluate mathematical functions are set up to
maintain as much precision as possible. In most cases, built-in Mathematica functions will give you
results that have as much precision as can be justified on the basis of your input. In some cases,
however, it is simply impractical to do this, and Mathematica will give you results that have lower
precision. If you give higher-precision input, Mathematica will use higher precision in its internal
calculations, and you will usually be able to get a higher-precision result.
N[expr]
N[expr, n]
Numerical evaluation.
If you start with an expression that contains only integers and other exact numeric quantities,
then N[expr, n] will in almost all cases succeed in giving you a result to n digits of precision. You
should realize, however, that to do this Mathematica sometimes has to perform internal intermediate
calculations to much higher precision.
The global variable $MaxExtraPrecision specifies how many additional digits should be allowed
in such intermediate calculations.
variable
default value
$MaxExtraPrecision
50
Out[18]= 0.569633400953636327308034181574
Out[19]= 0.
734
In[22]:= $MaxExtraPrecision = 50
Out[22]= 50
Even when you are doing computations that give exact results, Mathematica still occasionally uses
approximate numbers for some of its internal calculations, so that the value of $MaxExtraPrecision
can thus have an effect.
Mathematica works this out using
bounds from approximate numbers.
Out[23]= True
Temporarily resetting
$MaxExtraPrecision allows
Mathematica to get the result.
In doing calculations that degrade precision, it is possible to end up with numbers that have no
significant digits at all. But even in such cases, Mathematica still maintains information on the accuracy
of the numbers. Given a number with no significant digits, but accuracy a, Mathematica can then still
tell that the actual value of the number must be in the range 10a , 10a 2 . Mathematica by
default prints such numbers in the form 0. 10e .
Here is a number with 20-digit
precision.
In[27]:= Sin[x]/x
Out[27]= 0. 1022
In[28]:= Accuracy[%]
In[29]:= 1 + %
Out[28]= 21.7147
Out[29]= 22.7147
One subtlety in characterizing numbers by their precision is that any number that is consistent with
zero must be treated as having zero precision. The reason for this is that such a number has no digits
that can be recognized as significant, since all its known digits are just zero.
This gives a number whose value is
consistent with zero.
735
In[31]:= Precision[d]
In[32]:= Accuracy[d]
Out[31]= 0.
Out[32]= 19.2089
If you do computations whose results are likely to be near zero, it can be convenient to specify the
accuracy, rather than the precision, that you want to get.
N[expr, p]
,
1
Out[33]= ArcCot
3 ArcTan
3
This shows that the expression is
equivalent to zero.
In[34]:= FullSimplify[u]
Out[34]= 0
Out[35]= 0. 1071
When Mathematica works out the potential effect of unknown digits in arbitrary-precision numbers,
it assumes by default that these digits are completely independent in different numbers. While this
assumption will never yield too high a precision in a result, it may lead to unnecessary loss of
precision.
In particular, if two numbers are generated in the same way in a computation, some of their
unknown digits may be equal. Then, when these numbers are, for example, subtracted, the unknown digits may cancel. By assuming that the unknown digits are always independent, however,
Mathematica will miss such cancellations.
Here is a number computed to 20-digit
precision.
736
In[38]:= Precision[1 + d]
In[39]:= Precision[(1 + d) - d]
Out[38]= 34.3136
Out[39]= 34.0126
Numerical algorithms sometimes rely on cancellations between unknown digits in different numbers
yielding results of higher precision. If you can be sure that certain unknown digits will eventually
cancel, then you can explicitly introduce fixed digits in place of the unknown ones. You can carry
these fixed digits through your computation, then let them cancel, and get a result of higher precision.
SetPrecision[x, n]
SetAccuracy[x, n]
In[41]:= (1 + d) - d
In[42]:= Precision[%]
Out[41]= 1.00000000000000000000000000000000000000000000
Out[42]= 44.0126
SetPrecision works by adding digits which are zero in base 2. Sometimes, Mathematica stores
slightly more digits in an arbitrary-precision number than it displays, and in such cases, SetPrecision
will use these extra digits before introducing zeros.
This creates a number with a precision
of 40 decimal digits. The extra digits
come from conversion to base 10.
variable
default value
$MaxPrecision
Infinity
$MinPrecision
-Infinity
737
In[45]:= Evaluate[1 + k] - 1
In[47]:= Evaluate[1 + k] - 1
Out[46]= 20
Out[1]= 8.13382
Out[2]= 1.02338
Out[3]= 1.02337547922702991086041788103
When you do calculations with arbitrary-precision numbers, as discussed in the previous section,
Mathematica always keeps track of the precision of your results, and gives only those digits which
are known to be correct, given the precision of your input. When you do calculations with machineprecision numbers, however, Mathematica always gives you a machine-precision result, whether or not
all the digits in the result can, in fact, be determined to be correct on the basis of your input.
738
In[5]:= Precision[diff]
In[6]:= InputForm[diff]
Out[5]= MachinePrecision
Out[6]//InputForm= 1.1099999999153454*^-6
The fact that you can get spurious digits in machine-precision numerical calculations with Mathematica is in many respects quite unsatisfactory. The ultimate reason, however, that Mathematica uses
fixed precision for these calculations is a matter of computational efficiency.
Mathematica is usually set up to insulate you as much as possible from the details of the computer
system you are using. In dealing with machine-precision numbers, you would lose too much, however,
if Mathematica did not make use of some specific features of your computer.
The important point is that almost all computers have special hardware or microcode for doing
floating-point calculations to a particular fixed precision. Mathematica makes use of these features
when doing machine-precision numerical calculations.
The typical arrangement is that all machine-precision numbers in Mathematica are represented
as double-precision floating-point numbers in the underlying computer system. On most current
computers, such numbers contain a total of 64 binary bits, typically yielding 16 decimal digits of
mantissa.
The main advantage of using the built-in floating-point capabilities of your computer is speed.
Arbitrary-precision numerical calculations, which do not make such direct use of these capabilities,
are usually many times slower than machine-precision calculations.
There are several disadvantages of using built-in floating-point capabilities. One already mentioned
is that it forces all numbers to have a fixed precision, independent of what precision can be justified
for them.
A second disadvantage is that the treatment of machine-precision numbers can vary slightly from
one computer system to another. In working with machine-precision numbers, Mathematica is at the
mercy of the floating-point arithmetic system of each particular computer. If floating-point arithmetic
is done differently on two computers, you may get slightly different results for machine-precision
Mathematica calculations on those computers.
$MachinePrecision
$MachineEpsilon
739
$MaxMachineNumber
$MinMachineNumber
$MaxNumber
$MinNumber
Since machine-precision numbers on any particular computer system are represented by a definite
number of binary bits, numbers which are too close together will have the same bit pattern, and so
cannot be distinguished. The parameter $MachineEpsilon gives the distance between 1.0 and the
closest number which has a distinct binary representation.
This gives the value of
$MachineEpsilon for the computer
system on which these examples are
run.
In[7]:= $MachineEpsilon
In[8]:= 1. + $MachineEpsilon
In[9]:= % - 1.
Out[8]= 1.
In[10]:= 1. + $MachineEpsilon/2
Out[10]= 1.
In[11]:= % - 1.
Out[11]= 0.
Machine numbers have not only limited precision, but also limited magnitude. If you generate
a number which lies outside the range specified by $MinMachineNumber and $MaxMachineNumber ,
Mathematica will automatically convert the number to arbitrary-precision form.
This is the maximum machine-precision
number which can be handled on the
computer system used for this
example.
In[12]:= $MaxMachineNumber
Out[12]= 1.79769 10308
740
In[13]:= Exp[1000.]
Out[13]= 1.970071114017 10434
In[4]:= Abs[%]
1
1
Out[3]= Interval ,
, ,
2
5
1
Out[4]= Interval ,
5
4
Out[5]= x Interval , 1
741
IntervalMemberQ[interval , interval ]
test whether interval lies completely within interval
Operations on intervals.
In[8]:= Max[%]
In[9]:= IntervalMemberQ[
Table[Interval[{i, i+1}], {i, 1, 20, 3}], 7]
Out[8]= 5
You can use intervals not only with exact quantities but also with approximate numbers. Even with
machine-precision numbers, Mathematica always tries to do rounding in such a way as to preserve the
validity of results.
This shows explicitly the interval
treated by Mathematica as the
machine-precision number 0.
In[10]:= Interval[0.]
In[13]:= Sin[N[Pi]]
In[14]:= Sin[Interval[N[Pi]]]
742
In[1]:= 0/0
1
Power::infy: Infinite expression - encountered.
0
Infinity::indet:
Indeterminate expression 0 ComplexInfinity encountered.
Out[1]= Indeterminate
An expression like 0/0 is an example of an indeterminate numerical result. If you type in 0/0, there
is no way for Mathematica to know what answer you want. If you got 0/0 by taking the limit of
xx as x # , then you might want the answer 1. On the other hand, if you got 0/0 instead as the
limit of xx, then you probably want the answer 2. The expression 0/0 on its own does not contain
enough information to choose between these and other cases. As a result, its value must be considered
indeterminate.
Whenever an indeterminate result is produced in an arithmetic computation, Mathematica prints
a warning message, and then returns Indeterminate as the result of the computation. If you ever
try to use Indeterminate in an arithmetic computation, you always get the result Indeterminate .
A single indeterminate expression effectively poisons any arithmetic computation. (The symbol
Indeterminate plays a role in Mathematica similar to the not a number object in the IEEE Floating
Point Standard.)
The usual laws of arithmetic
simplification are suspended in the
case of Indeterminate .
When you do arithmetic computations inside Mathematica programs, it is often important to be able
to tell whether indeterminate results were generated in the computations. You can do this by using
the function Check discussed on page 481 to test whether any warning messages associated with
indeterminate results were produced.
You can use Check inside a program to
test whether warning messages are
generated in a computation.
Out[4]= meaningless
Indeterminate
Infinity
-Infinity
DirectedInfinity[r]
ComplexInfinity
DirectedInfinity[ ]
743
There are many situations where it is convenient to be able to do calculations with infinite quantities. The symbol Infinity in Mathematica represents a positive infinite quantity. You can use it to
specify such things as limits of sums and integrals. You can also do some arithmetic calculations with
it.
Here is an integral with an infinite
limit.
In[6]:= 1/Infinity
1
Out[5]=
2
Out[6]= 0
Out[7]= Indeterminate
There are a number of subtle points that arise in handling infinite quantities. One of them concerns the direction of an infinite quantity. When you do an infinite integral, you typically think of
performing the integration along a path in the complex plane that goes to infinity in some direction.
In this case, it is important to distinguish different versions of infinity that correspond to different
directions in the complex plane. and are two examples, but for some purposes one also needs
i and so on.
In Mathematica, infinite quantities can have a direction, specified by a complex number. When
you type in the symbol Infinity , representing a positive infinite quantity, this is converted internally
to the form DirectedInfinity[1] , which represents an infinite quantity in the direction. Similarly, -Infinity becomes DirectedInfinity[-1] , and I Infinity becomes DirectedInfinity[I] .
Although the DirectedInfinity form is always used internally, the standard output format for
DirectedInfinity[r] is r Infinity .
Infinity is converted internally to
DirectedInfinity[1] .
744
Although the notion of a directed infinity is often useful, it is not always available. If you type
in 1/0, you get an infinite result, but there is no way to determine the direction of the infinity.
Mathematica represents the result of 1/0 as DirectedInfinity[ ]. In standard output form, this
undirected infinity is printed out as ComplexInfinity .
1/0 gives an undirected form of
infinity.
In[9]:= 1/0
1
Power::infy: Infinite expression - encountered.
0
Out[9]= ComplexInfinity
2
Out[3]= f , 3.14159
3
745
integer part of x
fractional part of x
Round[x]
Floor[x]
Ceiling[x]
Sign[x]
UnitStep[x]
Abs[x]
1 for x c , -1 for x )
1 for x ! , 0 for x )
absolute value /x/ of x
746
IntegerPart[x]
FractionalPart[x]
Round[x]
Floor[x]
Ceiling[x]
2.4
0.4
2.5
0.5
2.6
0.6
-2.4
-2
-0.4
-2
-3
-2
-2.5
-2
-0.5
-2
-3
-2
-2.6
-2
-0.6
-3
-3
-2
IntegerPart[x] and FractionalPart[x] can be thought of as extracting digits to the left and right
of the decimal point. Round[x] is often used for forcing numbers that are close to integers to be
exactly integers. Floor[x] and Ceiling[x] often arise in working out how many elements there will
be in sequences of numbers with non-integer spacings.
x+Iy
Re[z]
Im[z]
Conjugate[z]
Abs[z]
Arg[z]
Rationalize[x]
Rationalize[x, dx]
Finding rational approximations.
747
0 or 1 with probability
SeedRandom[ ]
SeedRandom[s]
$RandomState
Out[2]= 0.748823044099679773836330229338
If you call Random[ ] repeatedly, you should get a typical sequence of numbers, with no particular
pattern. There are many ways to use such numbers.
One common way to use pseudorandom numbers is in making numerical tests of hypotheses. For
example, if you believe that two symbolic expressions are mathematically equal, you can test this by
plugging in typical numerical values for symbolic parameters, and then comparing the numerical
results. (If you do this, you should be careful about numerical accuracy problems and about functions
of complex variables that may not have unique values.)
748
Other common uses of pseudorandom numbers include simulating probabilistic processes, and
sampling large spaces of possibilities. The pseudorandom numbers that Mathematica generates are
always uniformly distributed over the range you specify.
Random is unlike almost any other Mathematica function in that every time you call it, you potentially
get a different result. If you use Random in a calculation, therefore, you may get different answers on
different occasions.
The sequences that you get from Random[ ] are not in most senses truly random, although they
should be random enough for practical purposes. The sequences are in fact produced by applying
a definite mathematical algorithm, starting from a particular seed. If you give the same seed, then
you get the same sequence.
When Mathematica starts up, it takes the time of day (measured in small fractions of a second) as
the seed for the pseudorandom number generator. Two different Mathematica sessions will therefore
almost always give different sequences of pseudorandom numbers.
If you want to make sure that you always get the same sequence of pseudorandom numbers, you
can explicitly give a seed for the pseudorandom generator, using SeedRandom .
This reseeds the pseudorandom
generator.
In[6]:= SeedRandom[143]
Every single time Random is called, the internal state of the pseudorandom generator that it uses is
changed. This means that calls to Random made in subsidiary calculations will have an effect on the
numbers returned by Random in your main calculation. To avoid any problems associated with this,
you can save the value of $RandomState before you do subsidiary calculations, and then restore it
afterwards.
By localizing the value of
$RandomState using Block, the internal
state of the pseudorandom generator is
restored after generating the first list.
749
Quotient[m, n]
GCD[n , n , ... ]
LCM[n , n , ... ]
KroneckerDelta[n , n , ... ]
IntegerDigits[n, b]
IntegerExponent[n, b]
In[1]:= Mod[17, 3]
Out[1]= 2
In[2]:= Quotient[17, 3]
Out[2]= 5
For any integers a and b, it is always true that b*Quotient[a, b] + Mod[a, b] is equal to a.
Mod[k, n]
Mod[k, n, 1]
Mod[k, n, -n/2]
Mod[k, n, d]
Particularly when you are using Mod to get indices for parts of objects, you will often find it
convenient to specify an offset.
This effectively extracts the 18th part of
the list, with the list treated cyclically.
750
The greatest common divisor function GCD[n , n , ... ] gives the largest integer that divides all
the ni exactly. When you enter a ratio of two integers, Mathematica effectively uses GCD to cancel out
common factors, and give a rational number in lowest terms.
The least common multiple function LCM[n , n , ... ] gives the smallest integer that contains all
the factors of each of the ni .
The largest integer that divides both 24
and 15 is 3.
The Kronecker delta or Kronecker symbol KroneckerDelta[n , n , ... ] is equal to 1 if all the ni
are equal, and is 0 otherwise. n n can be thought of as a totally symmetric tensor.
This gives a totally symmetric tensor of
rank 3.
FactorInteger[n]
Divisors[n]
Prime[k]
PrimePi[x]
PrimeQ[n]
FactorInteger[n, GaussianIntegers->True]
a list of the Gaussian prime factors of the Gaussian integer
n, and their exponents
PrimeQ[n, GaussianIntegers->True]
give True if n is a Gaussian prime, and False otherwise
Integer factoring and related functions.
In[8]:= FactorInteger[24]
Out[8]= 2, 3, 3, 1
In[9]:= FactorInteger[111111111111111111]
Out[9]= 3, 2, 7, 1, 11, 1, 13, 1,
19, 1, 37, 1, 52579, 1, 333667, 1
You should realize that according to current mathematical thinking, integer factoring is a fundamentally difficult computational problem. As a result, you can easily type in an integer that Mathematica
will not be able to factor in anything short of an astronomical length of time. But as long as the
integers you give are less than about 50 digits long, FactorInteger should have no trouble. And
751
in special cases it will be able to deal with much longer integers. (You can make some factoring
problems go faster by setting the option FactorComplete->False , so that FactorInteger[n] tries to
pull out only easy factors from n.)
Here is a rather special long integer.
In[10]:= 30!
Out[10]= 265252859812191058636308480000000
In[11]:= FactorInteger[%]
Out[11]= 2, 26, 3, 14, 5, 7, 7, 4, 11, 2,
13, 2, 17, 1, 19, 1, 23, 1, 29, 1
Although Mathematica may not be able to factor a large integer, it can often still test whether or not
the integer is a prime. In addition, Mathematica has a fast way of finding the kth prime number.
It is often much faster to test whether
a number is prime than to factor it.
In[12]:= PrimeQ[234242423]
Out[12]= False
500
400
300
200
100
20
40
60
80
100
In[14]:= Prime[1000000]
Out[14]= 15485863
Particularly in number theory, it is often more important to know the distribution of primes than
their actual values. The function PrimePi[x] gives the number of primes x that are less than or
equal to x.
This gives the number of primes less
than a billion.
In[15]:= PrimePi[10^9]
Out[15]= 50847534
By default, FactorInteger allows only real integers. But with the option setting
GaussianIntegers -> True, it also handles Gaussian integers, which are complex numbers with
integer real and imaginary parts. Just as it is possible to factor uniquely in terms of real primes, it
is also possible to factor uniquely in terms of Gaussian primes. There is nevertheless some potential
ambiguity in the choice of Gaussian primes. In Mathematica, they are always chosen to have positive
real parts, and non-negative imaginary parts, except for a possible initial factor of or Mi.
Over the Gaussian integers, 2 can be
factored as i i .
752
PowerMod[a, b, n]
EulerPhi[n]
MoebiusMu[n]
the Mobius
function n
DivisorSigma[k, n]
JacobiSymbol[n, m]
-
ExtendedGCD[n , n , ... ]
MultiplicativeOrder[k, n]
The modular power function PowerMod[a, b, n] gives exactly the same results as Mod[a^b, n] for
b c . PowerMod is much more efficient, however, because it avoids generating the full form of a^b.
You can use PowerMod not only to find positive modular powers, but also to find modular inverses.
For negative b, PowerMod[a, b, n] gives, if possible, an integer k such that kab Q mod n. (Whenever
such an integer exists, it is guaranteed to be unique modulo n.) If no such integer k exists, Mathematica
leaves PowerMod unevaluated.
PowerMod is equivalent to using Power,
then Mod, but is much more efficient.
In[20]:= Mod[3 %, 7]
Out[18]= 2
Out[19]= 5
Out[20]= 1
The Euler totient function n gives the number of integers less than n that are relatively prime
to n. An important relation (Fermats Little Theorem) is that an Q mod n for all a relatively prime
to n.
The Mobius
inversion formula,
753
which states that if gn d / n fd for all n, then fn d / n dgnd, where the sums are over all
positive integers d that divide n.
The divisor function k n is the sum of the kth powers of the divisors of n. The function n
gives the total number of divisors of n, and is often denoted dn. The function n, equal to the
sum of the divisors of n, is often denoted n.
For prime n, n n .
In[21]:= EulerPhi[17]
Out[21]= 16
In[23]:= Divisors[24]
Out[22]= 1
Out[24]= 8
The Jacobi symbol JacobiSymbol[n, m] reduces to the Legendre symbol mn when m is an odd
prime. The Legendre symbol is equal to zero if n is divisible by m, otherwise it is equal to if n is
a quadratic residue modulo the prime m, and to if it is not. An integer n relatively prime to m
is said to be a quadratic residue modulo m if there exists an integer k such that k Q n mod m. The
full Jacobi symbol is a product of the Legendre symbols ! pn " for each of the prime factors pi such that
i
m i pi .
The extended gcd ExtendedGCD[n , n , ... ] gives a list {g, {r , r , ... }} where g is the greatest
common divisor of the ni , and the ri are integers such that g r n r n . The extended gcd is
important in finding integer solutions to linear Diophantine equations.
The first number in the list is the gcd
of 105 and 196.
Out[26]= 7
The multiplicative order function MultiplicativeOrder[k, n] gives the smallest integer m such
that km Q mod n. The function is sometimes known as the index or discrete log of k. The notation
ordn k is occasionally used.
The generalized multiplicative order function MultiplicativeOrder[k, n, {r , r , ... }] gives
the smallest integer m such that km Q ri mod n for some i. MultiplicativeOrder[k, n, {-1, 1}] is
sometimes known as the suborder function of k modulo n, denoted sordn k.
The Carmichael function or least universal exponent n gives the smallest integer m such that
km Q mod n for all integers k relatively prime to n.
754
The lattice reduction function LatticeReduce[{v , v , ... }] is used in several kinds of modern
algorithms. The basic idea is to think of the vectors vk of integers as defining a mathematical lattice.
Any vector representing a point in the lattice can be written as a linear combination of the form
ck vk , where the ck are integers. For a particular lattice, there are many possible choices of the basis
vectors vk . What LatticeReduce does is to find a reduced set of basis vectors v k for the lattice, with
certain special properties.
Three unit vectors along the three
coordinate axes already form a reduced
basis.
In[27]:= LatticeReduce[{{1,0,0},{0,1,0},{0,0,1}}]
Out[28]= 1, 0, 1, 9, 9, 1, 10, 0, 85, 143, 59, 6
Notice that in the last example, LatticeReduce replaces vectors that are nearly parallel by vectors
that are more perpendicular. In the process, it finds some quite short basis vectors.
ContinuedFraction[x, n]
FromContinuedFraction[list]
Rationalize[x, dx]
Continued fractions.
In[30]:= FromContinuedFraction[%]
In[31]:= N[%]
1146408
Out[30]=
364913
Out[31]= 3.14159
201
Out[32]=
64
Continued fractions appear in many number-theoretical settings. Rational numbers have terminating continued fraction representations. Quadratic irrational numbers have continued fraction
representations that become repetitive.
ContinuedFraction[x]
RealDigits[x]
RealDigits[x, b]
In[33]:= ContinuedFraction[Sqrt[79]]
In[34]:= FromContinuedFraction[%]
Out[34]=
79
In[35]:= RealDigits[3/7]
In[36]:= FromDigits[%]
DigitCount[n, b, d]
755
3
Out[36]=
7
In[37]:= IntegerDigits[77, 2]
In[38]:= DigitCount[77, 2, 1]
Out[37]= 1, 0, 0, 1, 1, 0, 1
Out[38]= 4
756
BitAnd[n , n , ... ]
BitOr[n , n , ... ]
BitXor[n , n , ... ]
BitNot[n]
40
60
80
100
120
Bitwise operations.
Bitwise operations act on integers represented as binary bits. BitAnd[n , n , ... ] yields the integer
whose binary bit representation has ones at positions where the binary bit representations of all of the
ni have ones. BitOr[n , n , ... ] yields the integer with ones at positions where any of the ni have
ones. BitXor[n , n ] yields the integer with ones at positions where n or n but not both have ones.
BitXor[n , n , ... ] has ones where an odd number of the ni have ones.
This finds the bitwise AND of the
numbers 23 and 29 entered in base 2.
Bitwise operations are used in various combinatorial algorithms. They are also commonly used in
manipulating bitfields in low-level computer languages. In such languages, however, integers normally have a limited number of digits, typically a multiple of 8. Bitwise operations in Mathematica in
effect allow integers to have an unlimited number of digits. When an integer is negative, it is taken to
be represented in twos complement form, with an infinite sequence of ones on the left. This allows
BitNot[n] to be equivalent simply to n.
757
Binomial[n, m]
Multinomial[n , n , ... ]
Fibonacci[n]
Fibonacci[n, x]
HarmonicNumber[n]
HarmonicNumber[n, r]
BernoulliB[n]
BernoulliB[n, x]
EulerE[n]
EulerE[n, x]
factorial nn n
double factorial nn n
binomial coefficient mn ndemdn mdf
multinomial coefficient n n dn dn d
Fibonacci number Fn
Fibonacci polynomial Fn x
harmonic number Hn
harmonic number Hnr of order r
Bernoulli number Bn
Bernoulli polynomial Bn x
Euler number En
Euler polynomial En x
StirlingS1[n, m]
StirlingS2[n, m]
PartitionsP[n]
PartitionsQ[n]
Signature[{i , i , ... }]
Combinatorial functions.
The factorial function n! gives the number of ways of ordering n objects. For non-integer n, the
numerical value of nd is obtained from the gamma function, discussed in Section 3.2.10.
The binomial coefficient Binomial[n, m] can be written as mn ndemdn mdf. It gives the
number of ways of choosing m objects from a collection of n objects, without regard to order. The
Catalan numbers, which appear in various tree enumeration problems, are given in terms of binomial
coefficients as cn n
n (n .
758
In[1]:= 30!
In[2]:= 3.6!
In[3]:= Binomial[n, 2]
In[4]:= Multinomial[6, 5]
Out[1]= 265252859812191058636308480000000
Out[2]= 13.3813
1
Out[3]= 1 n n
2
Out[4]= 462
In[5]:= Binomial[11, 6]
Out[5]= 462
The Fibonacci numbers Fibonacci[n] satisfy the recurrence relation Fn Fn Fn with
F F . They appear in a wide range of discrete mathematical problems. For large n, Fn Fn
approaches the golden ratio.
The Fibonacci polynomials Fibonacci[n, x] appear as the coefficients of tn in the expansion of
n
t xt t
n Fn xt .
The harmonic numbers HarmonicNumber[n] are given by Hn ni i; the harmonic numbers
of order r HarmonicNumber[n, r] are given by Hnr ni ir . Harmonic numbers appear in many
combinatorial estimation problems, often playing the role of discrete analogs of logarithms.
The Bernoulli polynomials BernoulliB[n, x] satisfy the generating function relation text et
The Bernoulli numbers BernoulliB[n] are given by Bn Bn . The Bn appear as
the coefficients of the terms in the Euler-Maclaurin summation formula for approximating integrals.
n Bn xtn nd .
Numerical values for Bernoulli numbers are needed in many numerical algorithms. You can always
get these numerical values by first finding exact rational results using BernoulliB[n] , and then
applying N.
n
The Euler polynomials EulerE[n, x] have generating function ext et
n En xt nd , and
n
the Euler numbers EulerE[n] are given by En En . The Euler numbers are related to the
Genocchi numbers by Gn n nEn .
In[6]:= BernoulliB[2, x]
1
Out[6]= x x2
6
759
In[8]:= BernoulliB[20]
1
x x2 % 2 " x
x2
1
x3 % 3
"
Out[7]= 1 x t $
'
t $ '
t
12
2
12
2
2
4
6 &
#
&
#
1
x2
x3
x4
"
$ %
' t4 O
t5
720
24
12
24
#
&
174611
Out[8]=
330
Stirling numbers show up in many combinatorial enumeration problems. For Stirling numbers
gives the number of permutations of n elements
of the first kind StirlingS1[n, m], nm Sm
n
which contain exactly m cycles. These Stirling numbers satisfy the generating function relation
m
m
xx x n nm Sm
differ by a factor nm
n x . Note that some definitions of the Sn
from what is used in Mathematica.
Stirling numbers of the second kind StirlingS2[n, m] give the number of ways of partitioning a
set of n elements into m non-empty subsets. They satisfy the relation xn nm m
n xx x m .
The partition function PartitionsP[n] gives the number of ways of writing the integer n as a sum
of positive integers, without regard to order. PartitionsQ[n] gives the number of ways of writing n
as a sum of positive integers, with the constraint that all the integers in each sum are distinct.
This gives a table of Stirling numbers
of the first kind.
Out[10]= 24 x 50 x2 35 x3 10 x4 x5
15
10
20
40
60
80
100
760
The functions in this section allow you to enumerate various kinds of combinatorial objects. Functions like Permutations allow you instead to generate lists of various combinations of elements.
The signature function Signature[{i , i , ... }] gives the signature of a permutation. It is equal
to for even permutations (composed of an even number of transpositions), and to for odd
permutations. The signature function can be thought of as a totally antisymmetric tensor, Levi-Civita
symbol or epsilon symbol.
Clebsch-Gordan coefficients and n-j symbols arise in the study of angular momenta in quantum mechanics, and in other applications of the rotation group. The Clebsch-Gordan coefficients
ClebschGordan[{j , m }, {j , m }, {j, m}] give the coefficients in the expansion of the quantum
mechanical angular momentum state /j m in terms of products of states /j m /j m .
The 3-j symbols or Wigner coefficients ThreeJSymbol[{j , m }, {j , m }, {j
, m
}] are a more
symmetrical form of Clebsch-Gordan coefficients. In Mathematica,
the Clebsch-Gordan coefficients are
!
j j j
j j
j
m
j j
j
! m m m
".
given in terms of 3-j symbols by Cm m m
exponential function ez
Log[z]
logarithm loge z
Log[b, z]
the argument of x iy
In[3]:= N[ Log[-2] ]
Out[1]= 10
Out[2]= 0.6931471805599453094172321214581765680755
In[4]:= N[ Log[2 + 8 I] ]
In[5]:= Sin[Pi/2]
Out[5]= 1
Out[6]= 0.5
761
762
0.5
-7.5
-5
-2.5
2.5
7.5
-0.5
-1
There are a number of additional trigonometric and hyperbolic functions that are sometimes used.
The versine function is defined as versz cosz. The haversine is simply havz versz.
The complex exponential eix is sometimes written as cisx. The gudermannian function is defined as
gdz tan ez . The inverse gudermannian is gd z logesecz tanzf. The gudermannian
satisfies such relations as sinhz tanegdxf.
In[1]:= Sqrt[4]
Out[1]= 2
In[2]:= Sqrt[(-2)^2]
Out[2]= 2
When you evaluate i, there are again two possible answers: i and i. In this case,
however, it is less clear which one to choose.
There is in fact no way to choose z so that it is continuous for all complex values of z. There
has to be a branch cuta line in the complex plane across which the function z is discontinuous.
Mathematica adopts the usual convention of taking the branch cut for z to be along the negative real
axis.
763
In[3]:= N[ Sqrt[-2 I] ]
Out[3]= 1. 1.
In[5]:= %^2
2
1
0
-1
-2
-4
4
2
0
-2
-2
0
2
4 -4
When you find an nth root using zn , there are, in principle, n possible results. To get a single
value, you have to choose a particular principal root. There is absolutely no guarantee that taking the
nth root of an nth power will leave you with the same number.
This takes the tenth power of a
complex number. The result is unique.
In[8]:= %^(1/10)
There are many mathematical functions which, like roots, essentially give solutions to equations.
The logarithm function and the inverse trigonometric functions are examples. In almost all cases,
there are many possible solutions to the equations. Unique principal values nevertheless have to
be chosen for the functions. The choices cannot be made continuous over the whole complex plane.
Instead, lines of discontinuity, or branch cuts, must occur. The positions of these branch cuts are often
quite arbitrary. Mathematica makes the most standard mathematical choices for them.
764
Exp[z]
none
Log[z]
f
trigonometric functions
none
ArcSinh[z]
ArcCosh[z]
ArcTanh[z]
ArcCsch[z]
i i
ArcSech[z]
ArcCoth[z]
e f
In[9]:= ArcSin[Sin[4.5]]
Out[9]= 1.35841
765
In[11]:= Plot3D[ Im[ArcSin[x + I y]], {x, -4, 4}, {y, -4, 4}]
2
4
0
2
-2
-4
0
-2
-2
0
2
4 -4
i
: degrees to radians conversion factor
e
EulerGamma
Catalan
Khinchin
Khinchins constant
Glaisher
Mathematical constants.
Eulers constant EulerGamma is given by the limit limm# m
k k log m. It appears in many
integrals, and asymptotic formulas. It is sometimes known as the Euler-Mascheroni constant, and
denoted C.
k
Catalans constant Catalan is given by the sum
k k . It often appears in asymptotic
estimates of combinatorial functions.
766
Glaishers constant Glaisher A (sometimes called the Glaisher-Kinkelin constant) satisfies logA
where is the Riemann zeta function. It appears in various sums and integrals, particularly
those involving gamma and zeta functions.
$
,
In[2]:= IntegerPart[GoldenRatio^100]
Out[1]= 0.5772156649015328606065120900824024310422
Out[2]= 792070839848372253126
Legendre polynomials Pn x
associated Legendre polynomials Pm
n x
spherical harmonics Ylm
Gegenbauer polynomials Cm
n x
Chebyshev polynomials Tn x and Un x of the first
and second kinds
HermiteH[n, x]
Hermite polynomials Hn x
LaguerreL[n, x]
Laguerre polynomials Ln x
LaguerreL[n, a, x]
JacobiP[n, a, b, x]
Orthogonal polynomials.
767
In[1]:= LegendreP[8, x]
3465 x4
3003 x6
6435 x8
35
315 x2
Out[1]=
32
64
32
128
128
Out[2]= 0
2
Out[3]=
17
1
0.8
0.6
0.4
0.2
-1
-0.5
0.5
-0.2
-0.4
In[5]:= LegendreP[8, 3, x]
In[6]:= LegendreP[8.1, 0]
3465
1 x
2
1 x 1 x 3 x 26 x3 39 x5
Out[5]=
8
1 x
Out[6]= 0.268502
They are normalized so that Tn . They satisfy the orthogonality relation Tm xTn x
768
x dx for m ^ n. The Tn x also satisfy an orthogonality relation under summation at discrete
points in x corresponding to the roots of Tn x.
The Chebyshev polynomials of the second kind ChebyshevU[n, z] are defined by Un cos
sinen fsin . With this definition, Un n . The Un satisfy the orthogonality relation
Um xUn x x dx for m ^ n.
The name Chebyshev is a transliteration from the Cyrillic alphabet; several other spellings, such
as Tschebyscheff, are sometimes used.
Hermite polynomials HermiteH[n, x] arise as the quantum-mechanical wave functions for a harmonic oscillator. They satisfy the differential equation y$$ xy$ ny , and the orthogonality
relation Hm xHn xex dx for m ^ n. An alternative form of Hermite polynomials sometimes
used is Hen x n Hn x (a different overall normalization of the Hen x is also sometimes used).
The Hermite polynomials are related to the parabolic cylinder functions or Weber functions Dn x
by Dn x n ex
Hn x .
This gives the density for an excited
state of a quantum-mechanical
harmonic oscillator. The average of the
wiggles is roughly the classical physics
result.
25000
20000
15000
10000
5000
-6
-4
-2
Generalized Laguerre polynomials LaguerreL[n, a, x] are related to hydrogen atom wave functions in quantum mechanics. They satisfy the differential equation xy$$ a xy$ ny ,
and the orthogonality relation Lam xLan xxa ex dx for m ^ n. The Laguerre polynomials
LaguerreL[n, x] correspond to the special case a .
Jacobi polynomials JacobiP[n, a, b, x] occur in studies of the rotation group, particularly in
ab
a
b
quantum mechanics. They satisfy the orthogonality relation Pab
m xPn x x x dx
for m ^ n. Legendre, Gegenbauer and Chebyshev polynomials can all be viewed as special cases of
Jacobi polynomials. The Jacobi polynomials are sometimes given in the alternative form Gn p q x
pqq
nd n pn p Pn
x .
In[8]:= LaguerreL[2, a, x]
1
Out[8]= 2 3 a a2 4 x 2 a x x2
2
769
In[1]:= Gamma[15/2]
In[2]:= Gamma[15/7]
135135
Out[1]=
128
15
Out[2]= Gamma
7
A numerical result, to arbitrary
precision, can nevertheless be found.
Out[3]= 1.069071500448624397994137689702693267367
3
15
Out[5]= , ,
2
4
8
Out[7]= x 2.40483
Special functions in Mathematica can usually be evaluated for arbitrary complex values of their
arguments. Often, however, the defining relations given below apply only for some special choices of
arguments. In these cases, the full function corresponds to a suitable extension or analytic continuation of these defining relations. Thus, for example, integral representations of functions are valid only
when the integral exists, but the functions themselves can usually be defined elsewhere by analytic
continuation.
As a simple example of how the domain of a function can be extended, consider the function
k
represented by the sum
k x . This sum converges only when /x/ ) . Nevertheless, it is easy to
show analytically that for any x, the complete function is equal to x. Using this form, you can
easily find a value of the function for any x, at least so long as x ^ .
770
Beta[a, b]
Beta[z, a, b]
BetaRegularized[z, a, b]
Gamma[z]
Gamma[a, z]
Gamma[a, z , z ]
GammaRegularized[a, z]
InverseBetaRegularized[s, a, b]
InverseGammaRegularized[a, s]
Pochhammer[a, n]
PolyGamma[z]
PolyGamma[n, z]
The Euler gamma function Gamma[z] is defined by the integral z tz et dt. For positive integer
n, n n d . z can be viewed as a generalization of the factorial function, valid for complex
arguments z.
There are some computations, particularly in number theory, where the logarithm of the gamma
function often appears. For positive real arguments, you can evaluate this simply as Log[Gamma[z]] .
For complex arguments, however, this form yields spurious discontinuities. Mathematica therefore
includes the separate function LogGamma[z] , which yields the logarithm of the gamma function with
a single branch cut along the negative real axis.
The Euler beta function Beta[a, b] is ha b aba b ta tb dt.
The Pochhammer symbol or rising factorial Pochhammer[a, n] is an aa a n
a na. It often appears in series expansions for hypergeometric functions. Note that the
Pochhammer symbol has a definite value even when the gamma functions which appear in its
definition are infinite.
The incomplete gamma function Gamma[a, z] is defined by the integral a z z ta et dt. Mathez
matica includes a generalized incomplete gamma function Gamma[a, z , z ] defined as z ta et dt.
771
The alternative incomplete gamma function a z can therefore be obtained in Mathematica as
Gamma[a, 0, z].
z
The incomplete beta function Beta[z, a, b] is given by hz a b ta tb dt. Notice that in
the incomplete beta function, the parameter z is an upper limit of integration, and appears as the first
argument of the function. In the incomplete gamma function, on the other hand, z is a lower limit of
integration, and appears as the second argument of the function.
In certain cases, it is convenient not to compute the incomplete beta and gamma functions on
their own, but instead to compute regularized forms in which these functions are divided by complete beta and gamma functions. Mathematica includes the regularized incomplete beta function
BetaRegularized[z, a, b] defined for most arguments by Iz a b hz a bha b, but taking
into account singular cases. Mathematica also includes the regularized incomplete gamma function
GammaRegularized[a, z] defined by Qa z a za, with singular cases taken into account.
The incomplete beta and gamma functions, and their inverses, are common in statistics. The inverse
beta function InverseBetaRegularized[s, a, b] is the solution for z in s Iz a b. The inverse
gamma function InverseGammaRegularized[a, s] is similarly the solution for z in s Qa z.
Derivatives of the gamma function often appear in summing rational series. The digamma function
PolyGamma[z] is the logarithmic derivative of the gamma function, given by z $ zz. For
integer arguments, the digamma function satisfies the relation n Hn , where is Eulers
constant (EulerGamma in Mathematica) and Hn are the harmonic numbers.
The polygamma functions PolyGamma[n, z] are given by n z dn zdzn . Notice that the
digamma function corresponds to z. The general form n z is the n th , not the nth , logarithmic derivative of the gamma function. The polygamma functions satisfy the relation n z
n
n nd
.
k z k
Many exact results for gamma and
polygamma functions are built into
Mathematica.
In[1]:= PolyGamma[6]
137
Out[1]= EulerGamma
60
-1
-2
-3
-2
-1
772
LerchPhi[z, s, a]
PolyLog[n, z]
PolyLog[n, p, z]
RiemannSiegelTheta[t]
RiemannSiegelZ[t]
StieltjesGamma[n]
Stieltjes constants n
Zeta[s]
Zeta[s, a]
There is an analytic continuation of s for arbitrary complex s ^ . The zeta function for complex arguments is central to number-theoretical studies of the distribution of primes. Of particular
importance are the values on the critical line Re s .
In studying it, it is often convenient to define the two analytic Riemann-Siegel functions RiemannSiegelZ[t] and RiemannSiegelTheta[z] according to Zt eiit it and it
Im log
it t log (for t real). Note that the Riemann-Siegel functions are both real as long
as t is real.
The Stieltjes constants StieltjesGamma[n] are generalizations of Eulers constant which appear in
the series expansion of s around its pole at s ; the coefficient of sn is n nd . Eulers constant
is .
The generalized Riemann zeta function or Hurwitz zeta function Zeta[s, a] is given by s a
as , where any term with k a is excluded.
k k
In[1]:= Zeta[6]
6
Out[1]=
945
773
20
30
10
0
20
-2
0
10
2
3
2.5
2
1.5
1
0.5
10
20
30
40
k n
The polylogarithm functions PolyLog[n, z] are given by Lin z
k z k . The polylogarithm function is sometimes known as Jonqui`eres function. The dilogarithm PolyLog[2, z] sat
isfies Li z z log tt dt. Sometimes Li z is known as Spences integral. The Nielsen
generalized polylogarithm functions or hyperlogarithms PolyLog[n, p, z] are given by Snp z
np n dpd logn t logp ztt dt. Polylogarithm functions appear in Feynman diagram
integrals in elementary particle physics, as well as in algebraic K-theory.
The Lerch transcendent LerchPhi[z, s, a] is a generalization of the zeta and polylogarithm funck
s
tions, given by Ez s a
k z a k , where any term with a k is excluded. Many sums of
reciprocal powers can be expressed in terms of the Lerch transcendent. For example, the Catalan beta
k
s
can be obtained as s E s .
function s
k k
The Lerch transcendent is related to integrals of the Fermi-Dirac distribution in statistical mechanics
by ks ek dk e s Ee s .
The Lerch transcendent can also be used to evaluate Dirichlet L-series which appear in number
s
theory. The basic L-series has the form Ls
k kk , where the character k is an integer
774
function with period m. L-series of this kind can be written as sums of Lerch functions with z a power
of eim .
k
s
LerchPhi[z, s, a, DoublyInfinite->True] gives the doubly infinite sum
k z a k .
CosIntegral[z]
CoshIntegral[z]
ExpIntegralE[n, z]
exponential integral En z
ExpIntegralEi[z]
LogIntegral[z]
SinIntegral[z]
SinhIntegral[z]
The second exponential integral function ExpIntegralEi[z] is defined by Eiz z et t dt (for
z c ), where the principal value of the integral is taken.
z
The logarithmic integral function LogIntegral[z] is given by liz dtlog t (for z c ), where
the principal value of the integral is taken. liz is central to the study of the distribution of primes
in number theory. The logarithmic integral function is sometimes also denoted by Liz. In some
z
number-theoretical applications, liz is defined as dtlog t, with no principal value taken. This
differs from the definition used in Mathematica by the constant li.
The sine and cosine integral functions SinIntegral[z] and CosIntegral[z] are defined by
z
Siz sintt dt and Ciz z costt dt. The hyperbolic sine and cosine integral funcz
tions SinhIntegral[z] and CoshIntegral[z] are defined by Shiz sinhtt dt and Chiz
z
775
Erf[z]
Erf[z , z ]
Erfc[z]
Erfi[z]
FresnelC[z]
FresnelS[z]
InverseErf[s]
InverseErfc[s]
The inverse error function InverseErf[s] is defined as the solution for z in the equation s erfz.
The inverse error function appears in computing confidence intervals in statistics as well as in some
algorithms for generating Gaussian random numbers.
Closely related to the error function are the Fresnel integrals FresnelC[z] defined by Cz
z
cos t dt and FresnelS[z] defined by Sz sin t dt. Fresnel integrals occur in diffraction theory.
z
776
The Bessel functions BesselJ[n, z] and BesselY[n, z] are linearly independent solutions to the
differential equation z y$$ zy$ z n y . For integer n, the Jn z are regular at z , while the
Yn z have a logarithmic divergence at z .
Bessel functions arise in solving differential equations for systems with cylindrical symmetry.
Jn z is often called the Bessel function of the first kind, or simply the Bessel function. Yn z is
referred to as the Bessel function of the second kind, the Weber function, or the Neumann function
(denoted Nn z).
The Hankel functions (or Bessel functions of the third kind) Hn z Jn z M iYn z give an
alternative pair of solutions to the Bessel differential equation.
In studying systems with spherical symmetry, spherical Bessel functions arise, defined by fn z
zFn z, where f and F can be j and J , y and Y, or hi and H i . For integer n, Mathematica gives
exact algebraic formulas for spherical Bessel functions.
The modified Bessel functions BesselI[n, z] and BesselK[n, z] are solutions to the differential
equation z y$$ zy$ z n y . For integer n, In z is regular at z ; Kn z always has a
logarithmic divergence at z . The In z are sometimes known as hyperbolic Bessel functions.
Particularly in electrical engineering, one often defines the Kelvin functions, according to
bern z i bein z eni Jn zei
, kern z i kein z eni Kn zei
.
The Airy functions AiryAi[z] and AiryBi[z] are the two independent solutions Aiz and Biz
to the differential equation y$$ zy . Aiz tends to zero for large positive z, while Biz increases
unboundedly. The Airy functions are related to modified Bessel functions with one-third-integer orders. The Airy functions often appear as the solutions to boundary value problems in electromagnetic
theory and quantum mechanics. In many cases the derivatives of the Airy functions AiryAiPrime[z]
and AiryBiPrime[z] also appear.
The Struve function StruveH[n, z] appears in the solution of the inhomogeneous Bessel equazn
; the general solution to this
tion which for integer n has the form z y$$ zy$ z n y ndd
equation consists of a linear combination of Bessel functions with the Struve function Hn z added.
The modified Struve function StruveL[n, z] is given in terms of the ordinary Struve function by
Ln z iein Hn z. Struve functions appear particularly in electromagnetic theory.
Here is a plot of J x. This is a
curve that an idealized chain hanging
from one end can form when you
wiggle it.
1
0.8
0.6
0.4
0.2
10
-0.2
-0.4
20
30
40
50
777
In[2]:= BesselK[3/2, x]
x
2 1 1x
Out[2]=
x
0.4
0.2
-10
-5
10
-0.2
-0.4
LegendreP[n, z]
LegendreP[n, m, z]
LegendreQ[n, z]
LegendreQ[n, m, z]
The Legendre functions and associated Legendre functions satisfy the differential equation z y$$
zy$ enn m z fy . The Legendre functions of the first kind, LegendreP[n, z] and
LegendreP[n, m, z], reduce to Legendre polynomials when n and m are integers. The Legendre
functions of the second kind LegendreQ[n, z] and LegendreQ[n, m, z] give the second linearly
independent solution to the differential equation. For integer m they have logarithmic singularities at
z M. The Pn z and Qn z solve the differential equation with m .
Legendre functions arise in studies of quantum-mechanical scattering processes.
778
LegendreP[n, m, z] or LegendreP[n, m, 1, z]
type 1 function containing z m
LegendreP[n, m, 2, z]
LegendreP[n, m, 3, z]
Legendre functions of type 1 are defined only when z lies inside the unit circle in the complex
plane. Legendre functions of type 2 have the same numerical values as type 1 inside the unit circle,
but are also defined outside. The type 2 functions have branch cuts from to and from to
m
. Legendre functions of type 3, sometimes denoted m
n z and n z, have a single branch cut
from to .
Toroidal functions or ring functions, which arise in studying systems with toroidal symmetry, can
P cos
ip
cos .
ip
and Q
When you use the function LegendreP[n, x] with an integer n, you get a Legendre polynomial. If
you take n to be an arbitrary complex number, you get, in general, a Legendre function.
In the same way, you can use the functions GegenbauerC and so on with arbitrary complex indices
to get Gegenbauer functions, Chebyshev functions, Hermite functions, Jacobi functions and Laguerre functions. Unlike for associated Legendre functions, however, there is no need to distinguish
different types in such cases.
Hypergeometric0F1[a, z]
hypergeometric function F g ag z
Hypergeometric0F1Regularized[a, z]
regularized hypergeometric function F g ag za
Hypergeometric1F1[a, b, z]
Hypergeometric1F1Regularized[a, b, z]
regularized confluent hypergeometric function
F ag bg zb
HypergeometricU[a, b, z]
Confluent hypergeometric functions.
779
Many of the special functions that we have discussed so far can be viewed as special cases of the
confluent hypergeometric function Hypergeometric1F1[a, b, z].
The confluent hypergeometric function can be obtained from the series expansion F ag bg z
k
azb aa bb z d & & &
k ak bk z kd . Some special results are obtained when a
and b are both integers. If a ) , and either b c or b ) a, the series yields a polynomial with a finite
number of terms.
If b is zero or a negative integer, then F ag bg z itself is infinite. But the regularized confluent
hypergeometric function Hypergeometric1F1Regularized[a, b, z] given by F ag bg zb has a
finite value in all cases.
Among the functions that can be obtained from F are the Bessel functions, error function, incomplete gamma function, and Hermite and Laguerre polynomials.
The function F ag bg z is sometimes denoted Eag bg z or Ma b z. It is often known as the
Kummer function.
The F function can be written in the integral representation F ag bg z beb aaf ezt ta
tba dt.
The F confluent hypergeometric function is a solution to Kummers differential equation zy$$
b zy$ ay , with the boundary conditions F ag bg and "e F ag bg zf"z/z ab.
The function HypergeometricU[a, b, z] gives a second linearly independent solution to Kummers
equation. For Re b c this function behaves like zb for small z. It has a branch cut along the negative
real axis in the complex z plane.
The function Ua b z has the integral representation Ua b z a ezt ta tba dt.
Ua b z, like F ag bg z, is sometimes known as the Kummer function. The U function is sometimes denoted by .
The Whittaker functions give an alternative pair of solutions to Kummers differential equation.
The Whittaker function M is related to F by M z ez z F g g z. The second
Whittaker function W obeys the same relation, with F replaced by U .
The parabolic cylinder functions are related to Whittaker functions by D z
z
W z . For integer , the parabolic cylinder functions reduce to Hermite polynomials.
The Coulomb wave functions are also special cases of the confluent hypergeometric function.
Coulomb wave functions give solutions to the radial Schrodinger
780
Bessel functions of the first kind can be expressed in terms of the F function.
Hypergeometric Functions and Generalizations
Hypergeometric2F1[a, b, c, z]
Hypergeometric2F1Regularized[a, b, c, z]
regularized hypergeometric function F a bg cg zc
HypergeometricPFQ[{a , ... , ap }, {b , ... , bq }, z]
generalized hypergeometric function p Fq ag bg z
HypergeometricPFQRegularized[{a , ... , ap }, {b , ... , bq }, z]
regularized generalized hypergeometric function
MeijerG[{{a , ... , an }, {an , ... , ap }}, {{b , ... , bm }, {bm , ... , bq }}, z]
Meijer G function
AppellF1[a, b , b , c, x, y]
b
t
tcb tza dt.
The hypergeometric function is also sometimes denoted by F, and is known as the Gauss series or
the Kummer series.
The Legendre functions, and the functions which give generalizations of other orthogonal polynomials, can be expressed in terms of the hypergeometric function. Complete elliptic integrals can also
be expressed in terms of the F function.
The Riemann P function, which gives solutions to Riemanns differential equation, is also a F
function.
781
p
defined by the contour integral representation Gmn
pq z b b
i
s
s bm san s ap s bm s bq s z ds, where the contour of integration
is set up to lie between the poles of ai s and the poles of bi s. MeijerG is a very general
function whose special cases cover most of the functions discussed in the past few sections.
The Appell hypergeometric function of two variables AppellF1[a, b , b , c, x, y] has series
m n
expansion F ag b b g cg x y
m n amn b m b n mdndcmn x y . This function appears for
example in integrating cubic polynomials to arbitrary powers.
ProductLog[z]
The product log function gives the solution for w in z wew . The function can be viewed as a
generalization of a logarithm. It can be used to represent solutions to a variety of transcendental
equations. The tree generating function for counting distinct oriented trees is related to the product
log by Tz Wz.
782
JacobiAmplitude[u, m]
EllipticNomeQ[m]
InverseEllipticNomeQ[q]
WeierstrassInvariants[{, $ }]
WeierstrassHalfPeriods[{g , g }]
783
Elliptic Integrals
EllipticK[m]
EllipticF[, m]
EllipticE[m]
EllipticE[, m]
EllipticPi[n, m]
EllipticPi[n, , m]
JacobiZeta[, m]
Elliptic integrals.
Integrals of the form Rx y dx, where R is a rational function, and y is a cubic or quartic polynomial in x, are known as elliptic integrals. Any elliptic integral can be expressed in terms of the three
standard kinds of Legendre-Jacobi elliptic integrals.
The elliptic integral of the first kind EllipticF[, m] is given for ) ) by F / m
sin
d
e t mt f dt. This elliptic integral arises in solving the equa e m sin f
tions of motion for a simple pendulum. It is sometimes known as an incomplete elliptic integral of
the first kind.
Note that the arguments of the elliptic integrals are sometimes given in the opposite order from
what is used in Mathematica.
The complete elliptic integral of the first kind EllipticK[m] is given by Km F / m. Note
that K is used to denote the complete elliptic integral of the first kind, while F is used for its incomplete
form. In many applications, the parameter m is not given explicitly, and Km is denoted simply by K.
The complementary complete elliptic integral of the first kind K$ m is given by K m. It is often
denoted K$ . K and iK$ give the real and imaginary quarter-periods of the corresponding Jacobi
elliptic functions discussed below.
The elliptic integral of the second kind EllipticE[, m] is given for ) ) by
sin
E / m e m sin f d
The complete elliptic integral of the second kind EllipticE[m] is given by Em E / m. It is
often denoted E. The complementary form is E$ m E m.
The Jacobi zeta function JacobiZeta[, m] is given by Z / m E / m EmF / mKm.
The Heuman lambda function is given by A / m F / mK m KmZ / m.
784
1.5
1.4
1.3
1.2
1.1
0.2
Here is K with .
0.6
0.4
0.8
-2
0.5
-4
0.5
.5
0
1
-0.5
1.5
2
2.5 -1
785
Elliptic Functions
JacobiAmplitude[u, m]
JacobiSN[u, m], JacobiCN[u, m], etc.
Rational functions involving square roots of quadratic forms can be integrated in terms of inverse
trigonometric functions. The trigonometric functions can thus be defined as inverses of the functions
obtained from these integrals.
By analogy, elliptic functions are defined as inverses of the functions obtained from elliptic integrals.
The amplitude for Jacobi elliptic functions JacobiAmplitude[u, m] is the inverse of the elliptic
integral of the first kind. If u F / m, then amu / m. In working with Jacobi elliptic functions,
the argument m is often dropped, so amu / m is written as amu.
The Jacobi elliptic functions JacobiSN[u, m] and JacobiCN[u, m] are given respectively by
sin and cnu cos, where amu / m. In addition, JacobiDN[u, m] is given by
snu !
dnu
m sin ?.
There are a total of twelve Jacobi elliptic functions JacobiPQ[u, m], with the letters P and Q
chosen from the set S, C, D and N. Each Jacobi elliptic function JacobiPQ[u, m] satisfies the relation
pqu pnuqnu, where for these purposes nnu .
There are many relations between the Jacobi elliptic functions, somewhat analogous to those between
trigonometric functions. In limiting cases, in fact, the Jacobi elliptic functions reduce to trigonometric
786
functions. So, for example, snu / sinu, snu / tanhu, cnu / cosu, cnu / sechu,
dnu / and dnu / sechu.
u
The notation Pqu is often used for the integrals pq t dt. These integrals can be expressed in
terms of the Jacobi zeta function defined above.
One of the most important properties of elliptic functions is that they are doubly periodic in the complex values of their arguments. Ordinary trigonometric functions are singly periodic, in the sense that
fz s fz for any integer s. The elliptic functions are doubly periodic, so that fz r s$ fz
for any pair of integers r and s.
The Jacobi elliptic functions snu / m, etc. are doubly periodic in the complex u plane. Their periods
include
Km and $
iK m, where K is the complete elliptic integral of the first kind.
The choice of p and q in the notation pqu / m for Jacobi elliptic functions can be understood in
terms of the values of the functions at the quarter periods K and iK$ .
This shows two complete periods in
each direction of the absolute value of
the Jacobi elliptic function snu /
.
0
0
Also built into Mathematica are the inverse Jacobi elliptic functions InverseJacobiSN[v, m],
InverseJacobiCN[v, m], etc. The inverse function sn v / m, for example, gives the value of u for
which v snu / m. The inverse Jacobi elliptic functions are related to elliptic integrals.
The four theta functions ia u q are obtained from EllipticTheta[a, u, q] by taking a to be
n nn
1, 2, 3 or 4. The functions are defined by: i u q q
sinen uf, i u q
n q
nn
n
n n
cosen uf, i
u q n q cosnu, i
u q
q n q
n q cosnu.
The theta functions are often written as ia u with the parameter q not explicitly given. The theta functions are sometimes written in the form iu / m, where m is related to q by q expeKmKmf. In
addition, q is sometimes replaced by , given by q ei . All the theta functions satisfy a diffusion-like
differential equation " iu "u
i "iu ".
787
The Jacobi elliptic functions can be expressed as ratios of the theta functions.
An alternative notation for theta functions is @u / m i
v / m, @ u / m i
v / m, Hu / m i v,
H u / m i v, where v uKm.
The Neville theta functions can be defined in terms of the theta functions as is u Kmi v / m
i$ / m, ic u i v / mi / m, id u i
v / mi
/ m, in u i
v / mi
/ m, where v
uKm. The Jacobi elliptic functions can be represented as ratios of the Neville theta functions.
The Weierstrass elliptic function WeierstrassP[u, {g , g
}] can be considered as the inverse of
x
an elliptic integral. The Weierstrass function jug g g
gives the value of x for which u
t
"
jug g g
.
g t g
dt. The function WeierstrassPPrime[u, {g , g
}] is given by j$ ug g g
"u
The Weierstrass functions are also sometimes written in terms of their fundamental half-periods and
$ , obtained from the invariants g and g
using WeierstrassHalfPeriods[{g , g
}].
The function InverseWeierstrassP[p, {g , g
}] finds one of the two values of u for which
p jug g g
. This value always lies in the parallelogram defined by the complex number halfperiods and $ .
InverseWeierstrassP[{p, q}, {g , g
}] finds the unique value of u for which p jug g g
and
q j$ ug g g
. In order for any such value of u to exist, p and q must be related by q
p
g p g
.
The Weierstrass zeta function WeierstrassZeta[u, {g , g
}] and Weierstrass sigma function
WeierstrassSigma[u, {g , g
}] are related to the Weierstrass elliptic functions by $ zg g g
jzg g g
and $ zg g g
zg g g
zg g g
.
The Weierstrass zeta and sigma functions are not strictly elliptic functions since they are not
periodic.
DedekindEta[]
KleinInvariantJ[]
ModularLambda[]
The modular lambda function ModularLambda[] relates the ratio of half-periods $ to the
parameter according to m .
The Klein invariant modular function KleinInvariantJ[] and the Dedekind eta function
DedekindEta[] satisfy the relations ? g
J
.
788
Modular elliptic functions are defined to be invariant under certain fractional linear transformations
of their arguments. Thus for example is invariant under any combination of the transformations
# and # .
Generalized Elliptic Integrals and Functions
ArithmeticGeometricMean[a, b]
EllipticExp[u, {a, b}]
EllipticLog[{x, y}, {a, b}]
The definitions for elliptic integrals and functions given above are based on traditional usage. For
modern algebraic geometry, it is convenient to use slightly more general definitions.
The function EllipticLog[{x, y}, {a, b}] is defined as the value of the integral
at bt dt, where the sign of the square root is specified by giving the value of y such
x
t
that y x
ax bx. Integrals of the form t at dt can be expressed in terms of the ordinary logarithm (and inverse trigonometric functions). You can think of EllipticLog as giving a
generalization of this, where the polynomial under the square root is now of degree three.
The function EllipticExp[u, {a, b}] is the inverse of EllipticLog . It returns the list {x, y} that
appears in EllipticLog . EllipticExp is an elliptic function, doubly periodic in the complex u plane.
789
MathieuS[b, q, z]
MathieuCharacteristicB[r, q]
MathieuCharacteristicExponent[a, q]
characteristic exponent r for Mathieu functions with
characteristic value a and parameter q
Mathieu and related functions.
The Mathieu functions MathieuC[a, q, z] and MathieuS[a, q, z] are solutions to the equation
y$$ ea q coszfy . This equation appears in many physical situations that involve elliptical
shapes or periodic potentials. The function MathieuC is defined to be even in z, while MathieuS is
odd.
When q the Mathieu functions are simply cos az and sin az. For non-zero q, the Mathieu
functions are only periodic in z for certain values of a. Such Mathieu characteristic values are given
by MathieuCharacteristicA[r, q] and MathieuCharacteristicB[r, q] with r an integer or rational
number. These values are often denoted by ar and br .
For integer r, the even and odd Mathieu functions with characteristic values ar and br are often
denoted cer z q and ser z q, respectively. Note the reversed order of the arguments z and q.
According to Floquets Theorem any Mathieu function can be written in the form eirz fz, where fz
has period and r is the Mathieu characteristic exponent MathieuCharacteristicExponent[a, q].
When the characteristic exponent r is an integer or rational number, the Mathieu function is therefore
periodic. In general, however, when r is not a real integer, ar and br turn out to be equal.
790
20
10
10
12
14
-10
-20
N[expr, n]
D[expr, x]
N[D[expr, x]]
Series[expr, {x, x , n}]
Integrate[expr, x]
NIntegrate[expr, x]
FindRoot[expr==0, {x, x }]
Most special functions have simpler forms when given certain specific arguments. Mathematica will
automatically simplify special functions in such cases.
Mathematica automatically writes this in
terms of standard mathematical
constants.
2
Log
2
Out[1]=
12
2
791
In[2]:= AiryAi[0]
1
Out[2]=
323 Gamma 23
For most choices of arguments, no exact reductions of special functions are possible. But in such
cases, Mathematica allows you to find numerical approximations to any degree of precision. The algorithms that are built into Mathematica cover essentially all values of parametersreal and complexfor
which the special functions are defined.
There is no exact result known here.
In[3]:= AiryAi[1]
Out[3]= AiryAi
1
Out[4]= 0.1352924163128814155241474235154663061749
Most special functions have derivatives that can be expressed in terms of elementary functions or
other special functions. But even in cases where this is not so, you can still use N to find numerical
approximations to derivatives.
This derivative comes out in terms of
elementary functions.
In[6]:= D[FresnelS[x], x]
In[7]:= Gamma'[3]
In[8]:= Zeta'[Pi]
In[9]:= N[%]
x2
Out[6]= Sin
2
3
Out[7]= 2 EulerGamma
2
Out[8]= Zeta<
Out[9]= 0.167603
3 x7
5 x11
7 x15
x3
16
Out[10]= O
x
6
336
42240 9676800
792
1
Out[11]=
2
23
3 Gamma 13
One feature of working with special functions is that there are a large number of relations between
different functions, and these relations can often be used in simplifying expressions.
FullSimplify[expr]
FunctionExpand[expr]
Out[12]= Csc x
1 2
Out[14]= 2 BesselI ,
3 3
1
1
"
% PolyGamma
2, x
'
Out[15]= 2 $
3
3
#x
1 x &
n
2 x xn BesselK
n, x
Out[16]= BesselI
n, x
n
n
x xn x xn Cos
n Csc
n
1 1
Out[17]= Coth
3
6 2
793
In[18]:= FunctionExpand[Zeta''[0]]
2
EulerGamma2
Out[18]=
2
24
1
2
Log
2 Log
StieltjesGamma
1
2
BetaDistribution[, ]
CauchyDistribution[a, b]
ChiSquareDistribution[n]
ExponentialDistribution[]
ExtremeValueDistribution[, ]
FRatioDistribution[n , n ]
GammaDistribution[, ]
NormalDistribution[, ]
LaplaceDistribution[, ]
LogNormalDistribution[, ]
LogisticDistribution[, ]
RayleighDistribution[]
Rayleigh distribution
StudentTDistribution[n]
UniformDistribution[min, max]
WeibullDistribution[, ]
Weibull distribution
794
Most of the continuous statistical distributions commonly used are derived from the normal
or Gaussian distribution NormalDistribution[, ]. This distribution has probability density
expex f. If you take random variables that follow any distribution with bounded
variance, then the Central Limit Theorem shows that the mean of a large number of these variables
always approaches a normal distribution.
The logarithmic normal distribution or lognormal distribution LogNormalDistribution[, ] is
the distribution followed by the exponential of a normal-distributed random variable. This distribution
arises when many independent random variables are combined in a multiplicative fashion.
The chi-square distribution ChiSquareDistribution[n] is the distribution of the quantity ni xi ,
where the xi are random variables which follow a normal distribution with mean zero and unit
variance. The chi-square distribution gives the distribution of variances of samples from a normal
distribution.
The Student t distribution StudentTDistribution[n] is the distribution followed by the ratio of
a variable that follows the normal distribution to the square root of one that follows the chi-square
distribution with n degrees of freedom. The t distribution characterizes the uncertainty in a mean
when both the mean and variance are obtained from data.
The F-ratio distribution, F-distribution or variance ratio distribution
FRatioDistribution[n , n ] is the distribution of the ratio of two chi-square variables with n and
n degrees of freedom. The F-ratio distribution is used in the analysis of variance for comparing
variances from different models.
The extreme value distribution ExtremeValueDistribution[, ] is the limiting distribution for
the smallest or largest values in large samples drawn from a variety of distributions, including the
normal distribution.
PDF[dist, x]
CDF[dist, x]
Quantile[dist, q]
Mean[dist]
Variance[dist]
StandardDeviation[dist]
qth quantile
mean
variance
standard deviation
Skewness[dist]
coefficient of skewness
Kurtosis[dist]
coefficient of kurtosis
CharacteristicFunction[dist, t]
Random[dist]
Functions of statistical distributions.
characteristic function t
pseudorandom number with specified distribution
795
The cumulative distribution function (cdf) CDF[dist, x] is given by the integral of the probability
density function for the distribution up to the point x. For the normal distribution, the cdf is usually
denoted Ex. Cumulative distribution functions are used in evaluating probabilities for statistical
hypotheses. For discrete distributions, the cdf is given by the sum of the probabilities up to the point
x. The cdf is sometimes called simply the distribution function. The cdf at a particular point x for a
given distribution is often denoted Px / , where the i are parameters of the distribution. The
upper tail area is given in terms of the cdf by Qx / i Px / i . Thus, for example, the upper
tail area for a chi-square distribution with degrees of freedom is denoted Q / and is given by
1 - CDF[ChiSquareDistribution[nu], chi2].
The quantile Quantile[dist, q] is effectively the inverse of the cdf. It gives the value of x at
which CDF[dist, x] reaches q. The median is given by Quantile[dist, 1/2]; quartiles, deciles and
percentiles can also be expressed as quantiles. Quantiles are used in constructing confidence intervals
for statistical parameter estimates.
The characteristic function CharacteristicFunction[dist, t] is given by t px expitx dx,
where px is the probability density for a distribution. The nth central moment of a distribution is
given by the nth derivative in n .
Random[dist] gives pseudorandom numbers that follow the specified distribution. The numbers can
be seeded as discussed in Section 3.2.3.
This loads the package which defines
continuous statistical distributions.
In[1]:= <<Statistics`ContinuousDistributions`
In[3]:= CDF[ndist, x]
Out[2]= NormalDistribution 0, 1
1
x
$1 Erf %
'
Out[3]= "
2 #
2 &
Out[4]= 1.28155
796
BernoulliDistribution[p]
BinomialDistribution[n, p]
DiscreteUniformDistribution[n]
GeometricDistribution[p]
Most of the common discrete statistical distributions can be derived by considering a sequence of
trials, each with two possible outcomes, say success and failure.
The Bernoulli distribution BernoulliDistribution[p] is the probability distribution for a single
trial in which success, corresponding to value 1, occurs with probability p, and failure, corresponding
to value 0, occurs with probability p.
The binomial distribution BinomialDistribution[n, p] is the distribution of the number of successes that occur in n independent trials when the probability for success in an individual trial is p.
The distribution is given by nkpk pnk .
The negative binomial distribution NegativeBinomialDistribution[r, p] gives the distribution
of the number of failures that occur in a sequence of trials before r successes have occurred, given
that the probability for success in each individual trial is p.
The geometric distribution GeometricDistribution[p] gives the distribution of the total number
of trials before the first success occurs in a sequence of trials where the probability for success in each
individual trial is p.
The hypergeometric distribution HypergeometricDistribution[n, nsucc , ntot ] is used in place
of the binomial distribution for experiments in which the n trials correspond to sampling without
replacement from a population of size ntot with nsucc potential successes.
The discrete uniform distribution DiscreteUniformDistribution[n] represents an experiment
with n outcomes that occur with equal probabilities.
797
Factor[poly]
factor completely
FactorTerms[poly]
FactorTerms[poly, {x, y, ... }]
Collect[poly, x]
Collect[poly, {x, y, ... }]
Out[1]= 1 x 2 4 x2
In[2]:= t = Expand[ % ]
In[3]:= Factor[ t ]
In[4]:= FactorTerms[ t ]
Out[2]= 4 12 x 28 x2 52 x3 64 x4 64 x5 48 x6 16 x7
Out[3]= 4 1 x 1 2 x2
Out[4]= 4 1 3 x 7 x2 13 x3 16 x4 16 x5 12 x6 4 x7
There are several ways to write any polynomial. The functions Expand, FactorTerms and Factor
give three common ways. Expand writes a polynomial as a simple sum of terms, with all products expanded out. FactorTerms pulls out common factors from each term. Factor does complete factoring,
writing the polynomial as a product of terms, each of as low degree as possible.
When you have a polynomial in more than one variable, you can put the polynomial in different forms by essentially choosing different variables to be dominant. Collect[poly, x] takes a
polynomial in several variables and rewrites it as a sum of terms containing different powers of the
dominant variable x.
Here is a polynomial in two variables.
798
In[6]:= Collect[ %, x ]
Expand[poly, patt]
Out[6]= 1 8 x3 3 y 3 y2 y3 x2 12 12 y x 6 12 y 6 y2
Out[7]= 1 x3 8 y3 9 z 27 z2 27 z3 x2 3 6 y 9 z
y2 12 36 z y 6 36 z 54 z2
x 3 12 y2 18 z 27 z2 y 12 36 z
Out[8]= 1 y 2 x 1 y x2 1 y
Out[9]= 1 a
1 a
2
2
2 1 a 1 a 2 b 1 1 a 1 a 2 b 1
PowerExpand[expr]
Expanding powers.
Mathematica does not automatically expand out expressions of the form (a b)^c except when c is an
integer. In general it is only correct to do this expansion if a and b are positive reals. Nevertheless,
the function PowerExpand does the expansion, effectively assuming that a and b are indeed positive
reals.
Mathematica does not automatically
expand out this expression.
In[10]:= (x y)^n
In[11]:= PowerExpand[%]
In[12]:= Log[%]
Out[10]= x y
Out[11]= xn yn
Out[12]= Log xn yn
In[13]:= PowerExpand[%]
Out[13]= n Log
x n Log
y
Collect[poly, patt]
Collect[poly, patt, h]
799
Out[14]= 3 x f 1 x2 f 1 y f 2 z f 2
Out[15]= 3 x x2 f 1 y z f 2
Out[16]= 3 x 1 x f 1 y z f 2
Coefficient[poly, expr, n]
Coefficient[poly, expr, 0]
Out[1]= 1 x 1 x y
In[2]:= Expand[t]
Out[2]= 1 x 2 x2 2 x3 x4 x5 2 y 4 x y
4 x3 y 2 x4 y y2 3 x y2 3 x2 y2 x3 y2
800
In[3]:= PolynomialQ[t, x]
In[5]:= Variables[t]
In[6]:= Exponent[t, x]
This is equivalent to
Coefficient[t, x^2].
In[8]:= Coefficient[t, x, 2]
Out[3]= True
Out[4]= False
Out[5]= x, y
Out[6]= 5
Out[7]= 2 3 y2
Out[8]= 2 3 y2
In[9]:= Coefficient[t, x, 0]
Out[9]= 1 2 y y2
Out[10]= 1, 0, 3, 0, 4
It is important to notice that the functions in this section will work even on polynomials that are not
explicitly given in expanded form.
Many of the functions also work on expressions that are not strictly polynomials.
Without giving specific integer values
to a, b and c, this expression cannot
strictly be considered a polynomial.
In[13]:= Exponent[%, x]
Out[12]= xa xb yc
Out[13]= Max 0, a, b
801
ExpandNumerator[expr]
ExpandDenominator[expr]
Expand[expr]
ExpandAll[expr]
3 x2
1 x
2
Out[1]= 2 x
2
1x
1 x
In[2]:= ExpandNumerator[t]
In[3]:= Expand[t]
In[4]:= ExpandDenominator[t]
In[5]:= ExpandAll[t]
3 x2
1 2 x x2
Out[2]= 4 4 x x2
2
1x
1 x
1
2x
x2
3 x2
Out[3]= 4 4 x x2
1x
1x
1 x 1 x2
1 x
3 x2
2
Out[4]= 2 x
1x
1 2 x x2
1
2x
x2
3 x2
Out[5]= 4 4 x x2
1x
1x
1 x 1 2 x x2
Controlling expansion.
1 x
1
2
Out[6]= 1
y2
z2
z
802
Together[expr]
Apart[expr]
Cancel[expr]
Factor[expr]
4 3 x x2
4 x x2
Out[7]=
2
x x
1 x2
In[8]:= Together[u]
In[9]:= Factor[%]
In[10]:= Apart[u]
In[11]:= Cancel[u]
In[12]:= Factor[%]
2 4 x2
Out[8]=
1 x 1 x
2 2 x 2 x
Out[9]=
1 x 1 x
3
3
Out[10]= 2
1 x 1 x
4 x 4 x
Out[11]=
1 x 1 x
2 2 x 2 x
Out[12]=
1 x 1 x
In[13]:= v = (x^2+y^2)/(x + x y)
x2 y2
Out[13]=
xxy
In[14]:= Apart[v, x]
In[15]:= Apart[v, y]
803
x
y2
Out[14]=
1 y x 1 y
1 y
1 x2
Out[15]=
x x x 1 y
PolynomialQuotient[poly , poly , x]
find the result of dividing the polynomial poly in x by poly ,
dropping any remainder term
PolynomialRemainder[poly , poly , x]
find the remainder from dividing the polynomial poly in x
by poly
PolynomialGCD[poly , poly ]
PolynomialLCM[poly , poly ]
PolynomialMod[poly, m]
Resultant[poly , poly , x]
Subresultants[poly , poly , x]
804
px
Given two polynomials px and qx, one can always uniquely write qx ax bx
qx , where the
degree of bx is less than the degree of qx. PolynomialQuotient gives the quotient ax, and
PolynomialRemainder gives the remainder bx.
This gives the remainder from dividing
x by x.
Out[2]= 1 x
Out[3]= x2
PolynomialGCD[poly , poly ] finds the highest degree polynomial that divides the polyi exactly. It
gives the analog for polynomials of the integer function GCD.
PolynomialGCD gives the greatest
common divisor of the two
polynomials.
PolynomialMod is essentially the analog for polynomials of the function Mod for integers. When the
modulus m is an integer, PolynomialMod[poly, m] simply reduces each coefficient in poly modulo the
integer m. If m is a polynomial, then PolynomialMod[poly, m] effectively tries to get as low degree a
polynomial as possible by subtracting from poly appropriate multiples q m of m. The multiplier q can
itself be a polynomial, but its degree is always less than the degree of poly. PolynomialMod yields a
final polynomial whose degree and leading coefficient are both as small as possible.
This reduces x modulo x . The
result is simply the remainder from
dividing the polynomials.
In this case, PolynomialMod and
PolynomialRemainder do not give the
same result.
1
Out[7]= x2 ,
a2
The main difference between PolynomialMod and PolynomialRemainder is that while the former
works simply by multiplying and subtracting polynomials, the latter uses division in getting its results.
In addition, PolynomialMod allows reduction by several moduli at the same time. A typical case is
reduction modulo both a polynomial and an integer.
This reduces the polynomial x
modulo both x and .
805
The function Resultant[poly , poly , x] is used in a number of classical algebraic algorithms. The
resultant of two polynomials a and b, both with leading coefficient one, is given by the product of
all the differences ai bj between the roots of the polynomials. It turns out that for any pair of polynomials, the resultant is always a polynomial in their coefficients. By looking at when the resultant
is zero, one can tell for what values of their parameters two polynomials have a common root. Two
polynomials with leading coefficient one have k common roots if exactly the first k elements in the list
Subresultants[poly , poly , x] are zero.
Here is the resultant with respect to y
of two polynomials in x and y. The
original polynomials have a common
root in y only for values of x at which
the resultant vanishes.
Grobner
bases appear in many modern algebraic algorithms and applications. The function
GroebnerBasis[{poly , poly , ... }, {x , x , ... }] takes a set of polynomials, and reduces this set
to a canonical form from which many properties can conveniently be deduced. An important feature
is that the set of polynomials obtained from GroebnerBasis always has exactly the same collection of
common roots as the original set.
The x y is effectively redundant,
and so does not appear in the Grobner
basis.
Out[11]= 1
Out[12]= 1 y2 y3 y4 y5 , x y2 y3 y4
PolynomialReduce[poly, {p , p , ... }, {x , x , ... }] yields a list {{a , a , ... }, b} of polynomials with the property that b is minimal and a p + a p + ... + b is exactly poly.
This writes x y in terms of x y
and y a, leaving a remainder that
depends only on a.
806
Factor[poly]
FactorSquareFree[poly]
FactorTerms[poly, x]
factor a polynomial
write a polynomial as a product of powers of square-free
factors
factor out terms that do not depend on x
In[15]:= FactorTerms[t, x]
In[16]:= FactorSquareFree[t]
In[17]:= Factor[t]
Out[14]= 12 34 x 34 x2 14 x3 2 x4
Out[15]= 2 6 17 x 17 x2 7 x3 x4
Out[16]= 2 1 x 6 5 x x2
Out[17]= 2 1 x 2 x 3 x
Particularly when you write programs that work with polynomials, you will often find it convenient
to pick out pieces of polynomials in a standard form. The function FactorList gives a list of all
the factors of a polynomial, together with their exponents. The first element of the list is always the
overall numerical factor for the polynomial.
The form that FactorList returns is the analog for polynomials of the form produced by
FactorInteger for integers.
Here is a list of the factors of the
polynomial in the previous set of
examples. Each element of the list
gives the factor, together with its
exponent.
In[18]:= FactorList[t]
Out[18]= 2, 1, 1 x, 2, 2 x, 1, 3 x, 1
807
Factor and related functions usually handle only polynomials with ordinary integer or rationalnumber coefficients. If you set the option GaussianIntegers -> True, however, then Factor will
allow polynomials with coefficients that are complex numbers with rational real and imaginary parts.
This often allows more extensive factorization to be performed.
This polynomial is irreducible when
only ordinary integers are allowed.
Cyclotomic[n, x]
Out[19]= 1 x2
Out[20]= x x
Cyclotomic polynomials.
In[21]:= Cyclotomic[6, x]
Out[21]= 1 x x2
In[22]:= Factor[x^6 - 1]
Out[22]= 1 x 1 x 1 x x2 1 x x2
Decompose[poly, x]
Decomposing polynomials.
Factorization is one important way of breaking down polynomials into simpler parts. Another,
quite different, way is decomposition. When one factors a polynomial Px, one writes it as a product
p xp x of polynomials pi x. Decomposing a polynomial Qx consists of writing it as a composition
of polynomials of the form q q x .
808
Out[23]= 1 x x2 , x2
InterpolatingPolynomial[{f , f , ... }, x]
give a polynomial in x which is equal to fi when x is the
integer i
InterpolatingPolynomial[{{x , f }, {x , f }, ... }, x]
give a polynomial in x which is equal to fi when x is xi
Generating interpolating polynomials.
In[28]:= % /. x -> 0
Out[27]= 4 1 x 2 3 x
Out[28]= 2
809
PolynomialMod[poly, p]
basis modulo p
Functions for manipulating polynomials over finite fields.
In[2]:= PolynomialMod[%, 2]
Out[2]= 1 x2 x4 x6
In[3]:= Factor[%]
Out[3]= 1 x2 1 x4
Out[4]= 1 x
810
GaussianIntegers->True is equivalent
to Extension->Sqrt[-1] .
In[6]:= Expand[%]
Out[1]= 1 x4
Out[3]= x2 x2
Out[4]= x2 x2
1
Out[5]= 2 1 x 2 1 x
4
2 1 x 2 1 x
Out[6]= 1 x4
Factor[poly, Extension->Automatic]
factor poly allowing algebraic numbers in poly to appear in
coefficients
Factoring polynomials with algebraic number coefficients.
In[8]:= Factor[t]
Out[8]= 2 2 2 x x2
Other polynomial functions work much like Factor. By default, they treat algebraic number coefficients just like independent symbolic variables. But with the option Extension->Automatic they
perform operations on these coefficients.
By default, Cancel does not reduce
these polynomials.
2 2 2 x x2
Out[10]=
2 x2
811
2 x
Out[11]=
2 x
By default, PolynomialLCM pulls out
no common factors.
TrigFactor[expr]
TrigFactorList[expr]
TrigReduce[expr]
In[2]:= TrigFactor[%]
In[3]:= TrigReduce[%]
1
Out[3]= Sin
2 x 2 y Sin
2 x 2 y
2
Cosh
y Sinh
x
Out[4]=
Cosh
x Cosh
y Sinh
x Sinh
y
Cosh
x Sinh
y
Cosh
x Cosh
y Sinh
x Sinh
y
In[5]:= TrigReduce[%]
In[6]:= Sin[x]^2/Cos[x]
Out[5]= Tanh x y
812
In[7]:= TrigFactorList[%]
Out[7]= 1, 1, Sin
x, 2, Cos
x, 1
TrigToExp[expr]
ExpToTrig[expr]
In[8]:= TrigToExp[Tan[x]]
In[9]:= ExpToTrig[%]
In[11]:= ExpToTrig[(-1)^(1/17)]
x x
Out[8]=
x x
Out[9]= Tan x
Out[10]= 2 Sinh x
ComplexExpand[expr]
ComplexExpand[expr, {x , x , ... }]
Sin
2 x
Sinh
2 y
Out[1]=
Cos
2 x Cosh
2 y Cos
2 x Cosh
2 y
3.3.9 Simplification
813
Out[2]= a Im x 2 Im x Re x Re x
There are several ways to write a complex variable z in terms of real parameters. As above, for
example, z can be written in the Cartesian form Re[z] + I Im[z]. But it can equally well be written
in the polar form Abs[z] Exp[I Arg[z]].
The option TargetFunctions in ComplexExpand allows you to specify how complex variables
should be written. TargetFunctions can be set to a list of functions from the set {Re, Im, Abs, Arg,
Conjugate, Sign}. ComplexExpand will try to give results in terms of whichever of these functions
you request. The default is typically to give results in terms of Re and Im.
This gives an expansion in Cartesian
form.
Out[4]= Im z Re z
z2
Conjugate
z
Out[6]=
2
2
3.3.9 Simplification
Simplify[expr]
FullSimplify[expr]
Simplifying expressions.
1x
Out[1]=
1 x2
814
In[2]:= Simplify[%]
1
Out[2]=
1x
In[4]:= Simplify[Gamma[1+n]/n]
In[5]:= FullSimplify[%]
Out[3]= 1
Gamma
1 n
Out[4]=
n
Out[5]= Gamma n
2
22619537 15994428 2 1 Sin
x
In[7]:= FullSimplify[t]
2
Out[7]= 3363 2378 2 Cos
x
2
22619537 15994428 2 Cos
x
FullSimplify[expr, TimeConstraint->t]
try to simplify expr, working for at most t seconds on each
transformation
FullSimplify[expr, TransformationFunctions -> {f , f , ... }]
use only the functions fi in trying to transform parts of expr
FullSimplify[expr, TransformationFunctions -> {Automatic, f , f , ... }]
use built-in transformations as well as the fi
Simplify[expr, ComplexityFunction->c] and FullSimplify[expr, ComplexityFunction->c]
simplify using c to determine what form is considered
simplest
Further control of simplification.
815
In both Simplify and FullSimplify there is always an issue of what counts as the simplest form of
an expression. You can use the option ComplexityFunction -> c to provide a function to determine
this. The function will be applied to each candidate form of the expression, and the one that gives
the smallest numerical value will be considered simplest.
With its default definition of simplicity,
Simplify leaves this unchanged.
Mathematica normally makes as few assumptions as possible about the objects you ask it to manipulate. This means that the results it gives are as general as possible. But sometimes these results are
considerably more complicated than they would be if more assumptions were made.
Refine[expr, assum]
Simplify[expr, assum]
FullSimplify[expr, assum]
FunctionExpand[expr, assum]
1
1
Out[1]=
x
x
The reason is that its value is quite
different for different choices of x.
2
Out[2]=
, 2 , 2 , 0, 0, 0
Out[3]= 0
Out[4]= Log x y
816
By applying Simplify and FullSimplify with appropriate assumptions to equations and inequalities you can in effect establish a vast range of theorems.
Without making assumptions about x
the truth or falsity of this equation
cannot be determined.
In[6]:= Simplify[Abs[x] == x]
Out[6]= x Abs x
Out[7]= True
Out[8]= True
In[9]:= FullSimplify[0 < Erf[x] < 1, x > 0]
Out[9]= True
Simplify and FullSimplify always try to find the simplest forms of expressions. Sometimes,
however, you may just want Mathematica to follow its ordinary evaluation process, but with certain
assumptions made. You can do this using Refine. The way it works is that Refine[expr, assum]
performs the same transformations as Mathematica would perform automatically if the variables in
expr were replaced by numerical expressions satisfying the assumptions assum.
There is no simpler form that
Simplify can find.
Out[10]= Log x
An important class of assumptions are those which assert that some object is an element of a
particular domain. You can set up such assumptions using x dom, where the character can be
entered as , el , or \[Element] .
x dom or Element[x, dom]
Out[12]= True
Out[13]= True
817
Out[14]= False
Out[15]= Algebraics
Complexes
Reals
Algebraics
Rationals
Integers
Primes
Booleans
Out[16]= x Reals
If n is assumed to be an integer,
sinn is zero.
Out[17]= 0
Out[18]= True
Out[19]= True
By using Simplify , FullSimplify and FunctionExpand with assumptions you can access many
of Mathematicas vast collection of mathematical facts.
This uses the periodicity of the tangent
function.
Out[20]= Tan x
Out[21]= Tan x
Out[22]= True
818
Mathematica knows about discrete mathematics and number theory as well as continuous mathematics.
This uses Wilsons Theorem to simplify
the result.
Out[24]= 1 p
In something like Simplify[expr, assum] or Refine[expr, assum] you explicitly give the assumptions you want to use. But sometimes you may want to specify one set of assumptions to use in a
whole collection of operations. You can do this by using Assuming.
Assuming[assum, expr]
$Assumptions
Out[26]= x
Out[27]= x
Functions like Simplify and Refine take the option Assumptions , which specifies what default
assumptions they should use. By default, the setting for this option is Assumptions :> $Assumptions .
The way Assuming then works is to assign a local value to $Assumptions , much as in Block.
In addition to Simplify and Refine, a number of other functions take Assumptions options,
and thus can have assumptions specified for them by Assuming . Examples are FunctionExpand ,
Integrate , Limit, LaplaceTransform .
The assumption is automatically used
in Integrate .
1
Out[28]= 1
2
1 n
819
In[1]:= x^2 + 3x == 2
Out[1]= 3 x x2 2
In[2]:= Reduce[%, x]
1
1
Out[2]= x 3 17 x 3 17
2
2
The quadratic equation x^2 + 3x == 2 can be thought of as an implicit statement about the value of
x. As shown in the example above, you can use the function Reduce to get a more explicit statement
about the value of x. The expression produced by Reduce has the form x == r || x == r . This
expression is again a logical statement, which asserts that either x is equal to r , or x is equal to
r . The values of x that are consistent with this statement are exactly the same as the ones that are
consistent with the original quadratic equation. For many purposes, however, the form that Reduce
gives is much more useful than the original equation.
You can combine and manipulate equations just like other logical statements. You can use logical
connectives such as || and && to specify alternative or simultaneous conditions. You can use functions
like LogicalExpand , as well as FullSimplify , to simplify collections of equations.
For many purposes, you will find it convenient to manipulate equations simply as logical statements. Sometimes, however, you will actually want to use explicit solutions to equations in other
calculations. In such cases, it is convenient to convert equations that are stated in the form lhs == rhs
into transformation rules of the form lhs -> rhs. Once you have the solutions to an equation in the
form of explicit transformation rules, you can substitute the solutions into expressions by using the
/. operator.
Reduce produces a logical statement
about the values of x corresponding to
the roots of the quadratic equation.
1
1
Out[3]= x 3 17 x 3 17
2
2
820
In[4]:= {ToRules[ % ]}
In[5]:= x^2 + a x /. %
1
1
Out[4]= x 3 17
, x 3 17
2
2
1
2 1
Out[5]= 3 17 3 17 a,
4
2
1
2 1
3 17 3 17 a
2
4
1
1
Out[6]= x 3 17
, x 3 17
2
2
In[1]:= Solve[ a x + b == c , x ]
b c
Out[1]= x
1
1
Out[2]= x a 8 a2
, x a 8 a2
2
2
13
2
%
"
'
$
Out[3]= x 34 $
'
# 3 9 471729 &
13
12 9 471729
323
For cubic and quartic equations the results are often complicated, but for all equations with degrees
up to four Mathematica is always able to give explicit formulas for the solutions.
An important feature of these formulas is that they involve only radicals: arithmetic combinations
of square roots, cube roots and higher roots.
It is a fundamental mathematical fact, however, that for equations of degree five or higher, it is no
longer possible in general to give explicit formulas for solutions in terms of radicals.
There are some specific equations for which this is still possible, but in the vast majority of cases it
is not.
This constructs a degree six
polynomial.
821
In[5]:= Solve[% == 0, x]
In[7]:= Solve[% == 0, x]
Out[5]=
x 2, x 2, x 2 !,
x 2 !, x 6 !, x 6 !!
5 3 2
, x
Out[7]= x
5 3 2
,
x
5 3 2
, x
5 3 2
,
x
5 3 2
, x
5 3 2
,
x
5 3 2
, x
5 3 2
Root[f, k]
In[8]:= Solve[x^5 - x + 11 == 0, x]
In[9]:= N[%]
In[10]:= NSolve[x^5 - x + 11 == 0, x]
Out[8]=
x Root11 #1 #15
x Root11 #1 #15
x Root11 #1 #15
x Root11 #1 #15
x Root11 #1 #15
&,
&,
&,
&,
&,
1!,
2!,
3!,
4!,
5!!
Root objects provide an exact, though implicit, representation for the roots of a polynomial. You
can work with them much as you would work with Sqrt[2] or any other expression that represents
an exact numerical quantity.
822
In[12]:= N[r]
In[13]:= Round[r]
In[15]:= FullSimplify[
Product[Root[11 - # + #^5 &, k], {k, 5}] ]
Out[12]= 1.66149
Out[13]= 2
Out[14]= 0
Out[15]= 11
If the only symbolic parameter that exists in an equation is the variable that you are solving for,
then all the solutions to the equation will just be numbers. But if there are other symbolic parameters
in the equation, then the solutions will typically be functions of these parameters.
The solution to this equation can again
be represented by Root objects, but
now each Root object involves the
parameter a.
In[17]:= Solve[x^5 + x + a == 0, x]
Out[17]=
x Roota #1 #15
x Roota #1 #15
x Roota #1 #15
x Roota #1 #15
x Roota #1 #15
&,
&,
&,
&,
&,
1!,
2!,
3!,
4!,
5!!
1
Out[18]= x Root1 #12 #13 &, 1!, x 3
,
2
1
x 3
, x Root1 #12 #13 &, 2!,
2
x Root1 #12 #13 &, 3!
823
0.5
-2
-1
-0.5
-1
1
Out[20]=
4
1 5 Roota #1 #15 &, 1
If you give Solve any nth -degree polynomial equation, then it will always return exactly n solutions,
although some of these may be represented by Root objects. If there are degenerate solutions, then
the number of times that each particular solution appears will be equal to its multiplicity.
Solve gives two identical solutions to
this equation.
Out[22]=
x Root11 #1 #15
x Root11 #1 #15
x Root11 #1 #15
x Root11 #1 #15
&,
&,
&,
&,
1!,
1!,
2!,
2!!
Mathematica also knows how to solve equations which are not explicitly in the form of polynomials.
Here is an equation involving square
roots.
1 2 a2 a4
Out[23]= x
4 a2
1
1
Out[24]= x 1 1 4 a
, x 1 1 4 a
2
2
So long as it can reduce an equation to some kind of polynomial form, Mathematica will always be
able to represent its solution in terms of Root objects. However, with more general equations, involving say transcendental functions, there is no systematic way to use Root objects, or even necessarily
to find numerical approximations.
Here is a simple transcendental
equation for x.
In[25]:= Solve[ArcSin[x] == a, x]
Out[25]= x Sin
a
824
In[26]:= Solve[Cos[x] == x, x]
Solve::tdep:
The equations appear to involve the variables to be
solved for in an essentially non-algebraic way.
Polynomial equations in one variable only ever have a finite number of solutions. But transcendental
equations often have an infinite number. Typically the reason for this is that functions like Sin in effect have infinitely many possible inverses. With the default option setting InverseFunctions->True ,
Solve will nevertheless assume that there is a definite inverse for any such function. Solve may then
be able to return particular solutions in terms of this inverse function.
Mathematica returns a particular
solution in terms of ArcSin, but prints
a warning indicating that other
solutions are lost.
In[28]:= Solve[Sin[x] == a, x]
Solve::ifun:
Inverse functions are being used by Solve, so some
solutions may not be found; use Reduce for complete
solution information.
In[29]:= Solve[Exp[x] + x + 1 == 0, x]
InverseFunction::ifun:
Inverse functions are being used. Values may be lost
for multivalued inverses.
Solve::ifun:
Inverse functions are being used by Solve, so some
solutions may not be found; use Reduce for complete
solution information.
1
Out[29]= x 1 ProductLog
If you ask Solve to solve an equation involving an arbitrary function like f, it will by default try
to construct a formal solution in terms of inverse functions.
Solve by default uses a formal inverse
for the function f.
In[30]:= Solve[f[x] == a, x]
InverseFunction::ifun:
Inverse functions are being used. Values may be lost
for multivalued inverses.
In[31]:= InputForm[%]
Out[31]//InputForm= {{x -> InverseFunction[f, 1, 1][a]}}
InverseFunction[f]
InverseFunction[f, k, n]
825
Inverse functions.
In[32]:= InverseFunction[Tan]
In[33]:= D[InverseFunction[f][x^2], x]
Out[32]= ArcTan
2x
Out[33]=
f<
f1
x2
While Solve can only give specific solutions to an equation, Reduce can give a representation of a
whole solution set. For transcendental equations, it often ends up introducing new parameters, say
with values ranging over all possible integers.
This is a complete representation of the
solution set.
In[34]:= Reduce[Sin[x] == a, x]
In[35]:= Reduce[Exp[x] + x + 1 == 0, x]
1
Out[35]= C
1 Integers && x 1 ProductLogC
1,
As discussed at more length in Section 3.4.9, Reduce allows you to restrict the domains of variables.
Sometimes this will let you generate definite solutions to transcendental equationsor show that they
do not exist.
With the domain of x restricted, this
yields definite solutions.
5
Out[36]= x x x
6
6
6
1
Out[37]= x 1 ProductLog
Out[38]= False
826
In[2]:= First[%][x]
Out[2]= 12 x 2 x5
Root objects are the way that Mathematica represents algebraic numbers. Algebraic numbers have the
property that when you perform algebraic operations on them, you always get a single algebraic
number as the result.
Here is the square root of an algebraic
number.
In[4]:= RootReduce[%]
Out[3]=
Root2 #1 #15 &, 1
Out[5]=
2
2 Root2 #1 #15 &, 1
In[6]:= RootReduce[%]
Out[6]= Root14 72 #1 25 #12 144 #13
RootReduce[expr]
ToRadicals[expr]
1
Out[7]= 1 5
2
In[8]:= Root[#^3 - 2 &, 1]
Out[8]= Root2 #13 &, 1
827
In[9]:= ToRadicals[%]
Out[9]= 213
If Solve and ToRadicals do not succeed in expressing the solution to a particular polynomial equation in terms of radicals, then it is a good guess that this fundamentally cannot be done. However,
you should realize that there are some special cases in which a reduction to radicals is in principle
possible, but Mathematica cannot find it. The simplest example is the equation x x
, but
here the solution in terms of radicals is very complicated. The equation x x
x
x
x
In[11]:= ToRadicals[%]
Beyond degree four, most polynomials do not have roots that can be expressed at all in terms of
radicals. However, for degree five it turns out that the roots can always be expressed in terms of
elliptic or hypergeometric functions. The results, however, are typically much too complicated to be
useful in practice.
RootSum[f, form]
Normal[expr]
Sums of roots.
Out[12]= 2
828
In[14]:= Normal[%]
Out[14]= Log1 Root1 2 #1 #15 &, 1
Root1 2 #1 #15 &, 1
Log1 Root1 2 #1 #15 &, 2
Root1 2 #1 #15 &, 2
Log1 Root1 2 #1 #15 &, 3
Root1 2 #1 #15 &, 3
Log1 Root1 2 #1 #15 &, 4
Root1 2 #1 #15 &, 4
Log1 Root1 2 #1 #15 &, 5
Root1 2 #1 #15 &, 5
1 2 b
1 2 a
Out[1]= x , y
ab
ab
1
1
Out[2]= x a 2 a2 , y a 2 a2
,
2
2
a
2 a2
1
x , y a 2 a2
2
2
2
Out[4]= x
2
1
1 Root1 3 #1 #12 2 #13 2 #14 #15 &, 1
2
3
In[5]:= N[ % ]
Out[5]= x 3.4875, y 1.80402
829
The variables that you use in Solve do not need to be single symbols. Often when you set up
large collections of simultaneous equations, you will want to use expressions like a[i] as variables.
Here is a list of three equations for the
a[i].
Out[6]= a
0 2 a
1 a
2,
a
1 2 a
2 a
3, a
2 2 a
3 a
4
1
Out[7]= a
1 5 a
0 a
4,
12
1
a
2 a
0 a
4,
6
1
a
3 a
0 5 a
4
12
In[8]:= Solve[ { x + y == 1, x - 3 y == 2 } ]
5
1
Out[8]= x , y
4
4
In[9]:= {{3,1},{2,-5}}.{x,y}=={7,8}
In[11]:= LogicalExpand[%%]
Out[9]= 3 x y, 2 x 5 y 7, 8
43
10
Out[10]= x , y
17
17
Out[11]= 2 x 5 y 8 && 3 x y 7
In some kinds of computations, it is convenient to work with arrays of coefficients instead of explicit
equations. You can construct such arrays from equations by using CoefficientArrays .
830
In[1]:= Solve[ a x == 0 , x ]
Out[1]= x 0
In[2]:= Reduce[ a x == 0 , x ]
Out[2]= a 0 x 0
A basic difference between Reduce and Solve is that Reduce gives all the possible solutions to a
set of equations, while Solve gives only the generic ones. Solutions are considered generic if they
involve conditions only on the variables that you explicitly solve for, and not on other parameters in
the equations. Reduce and Solve also differ in that Reduce always returns combinations of equations,
while Solve gives results in the form of transformation rules.
Solve[eqns, vars]
Reduce[eqns, vars]
Solving equations.
In[3]:= Solve[a x + b == 0, x]
b
Out[3]= x
a
In[4]:= Reduce[a x + b == 0, x]
b
Out[4]= b 0 && a 0 a 0 && x
a
In[5]:= Reduce[a x^2 + b x + c == 0, x]
Out[5]= a 0 &&
b b2 4 a c %
b b2 4 a c
"
$
$x x '
'
2a
2a
#
&
c
a 0 && b 0 && x c 0 && b 0 && a 0
b
When you have several simultaneous equations, Reduce can show you under what conditions the
equations have solutions. Solve shows you whether there are any generic solutions.
In[10]:= Reduce[ x == x , x ]
In[11]:= Solve[ x == x , x ]
831
Out[6]= False
Out[7]= a 1 && x 1
Out[8]=
Out[10]= True
Out[11]=
When you work with systems of linear equations, you can use Solve to get generic solutions, and
Reduce to find out for what values of parameters solutions exist.
Here is a matrix whose i jth element is
i j.
In[13]:= Det[ m ]
Out[13]= 0
Out[14]= 2 x 3 y 4 z, 3 x 4 y 5 z, 4 x 5 y 6 z a, b, c
Out[15]=
For nonlinear equations, the conditions for the existence of solutions can be much more complicated.
Here is a very simple pair of nonlinear
equations.
Out[17]= x y a, x2 y2 b
Out[18]=
832
Eliminating variables.
In[4]:= Solve[eqn, x, y]
In[5]:= Solve[eqn, x, a]
Out[1]= x y 6 a 3 b, y 9 a 2 x
1
1
Out[3]= x 9 b y, a 2 b y
7
7
1
Out[5]= x 9 b y
In some cases, you may want to construct explicitly equations in which variables have been
eliminated. You can do this using Eliminate .
This combines the two equations in the
list eqn, by eliminating the variable a.
In[6]:= Eliminate[eqn, a]
In[7]:= Eliminate[eqn, y]
Out[6]= 9 b y 7 x
Out[7]= b x a
833
In dealing with sets of equations, it is common to consider some of the objects that appear as true
variables, and others as parameters. In some cases, you may need to know for what values of
parameters a particular relation between the variables is always satisfied.
SolveAlways[eqns, vars]
solve for the values of parameters for which the eqns are
satisfied for all values of the vars
9 a
x2
4
4
Out[10]= 1 a b 2 b x2 O
x 1 O
x
2 2
2
This finds values of the undetermined
coefficients.
In[11]:= SolveAlways[%, x]
10
10
Out[11]= a , b
3
3
3
1
Out[1]= x , y
2
2
In[3]:= Solve[ x + y == 1 || x - y == 2, x ]
3
1
Out[2]= x , y
2
2
834
In[4]:= Solve[x^3 == x, x]
When you use Solve, the final results you get are in the form of transformation rules. If you use
Reduce or Eliminate , on the other hand, then your results are logical statements, which you can
manipulate further.
This gives a logical statement
representing the solutions of the
equation x^2 == x.
In[7]:= Reduce[x^2 == x, x]
Out[7]= x 0 x 1
Out[8]= x 1 x x
The logical statements produced by Reduce can be thought of as representations of the solution set
for your equations. The logical connectives &&, || and so on then correspond to operations on these
sets.
eqns || eqns
!eqns
Implies[eqns , eqns ]
You may often find it convenient to use special notations for logical connectives, as discussed on
page 1001.
The input uses special notations for
Implies and Or.
3.4.8 Inequalities
835
3.4.8 Inequalities
Just as the equation x^2 + 3x == 2 asserts that x^2 + 3x is equal to 2, so also the inequality x^2 + 3x > 2
asserts that x^2 + 3x is greater than 2. In Mathematica, Reduce works not only on equations, but also
on inequalities.
Out[1]= 1 ? x ? 2
Out[2]= False
When applied to an equation, Reduce[eqn, x] tries to get a result consisting of simple equations for
x of the form x == r , ... . When applied to an inequality, Reduce[ineq, x] does the exactly analogous
thing, and tries to get a result consisting of simple inequalities for x of the form l < x < r , ... .
This reduces a quadratic equation to
two simple equations for x.
In[3]:= Reduce[x^2 + 3x == 2, x]
1
1
Out[3]= x 3 17 x 3 17
2
2
1
1
Out[4]= x ? 3 17 x > 3 17
2
2
You can think of the result generated by Reduce[ineq, x] as representing a series of intervals,
described by inequalities. Since the graph of a polynomial of degree n can go up and down as many
as n times, a polynomial inequality of degree n can give rise to as many as n distinct intervals.
This inequality yields three distinct
intervals.
Out[5]= x ? 1 2 ? x ? 3 x > 4
1
1
Out[7]= ProductLog
? x ? ProductLog1,
2
2
Transcendental functions like sinx have graphs that go up and down infinitely many times, so
that infinitely many intervals can be generated.
The second inequality allows only
finitely many intervals.
836
0 ? x ? ? x ?
2
2
1
2 2 ArcTan 4 7 ? x ? 3 2
3
If you have inequalities that involve <= as well as <, there may be isolated points where the
inequalities can be satisfied. Reduce represents such points by giving equations.
This inequality can be satisfied at just
two isolated points.
1
1
Out[11]= x 3 5 x 3 5
2
2
5
Out[12]= x x
2
6
3
11
5
17
x x x 3
2
6
2
6
Multivariate inequalities.
For inequalities involving several variables, Reduce in effect yields nested collections of interval
specifications, in which later variables have bounds that depend on earlier variables.
This represents the unit disk as nested
inequalities for x and y.
In geometrical terms, any linear inequality divides space into two halves. Lists of linear inequalities
thus define polyhedra, sometimes bounded, sometimes not. Reduce represents such polyhedra in
terms of nested inequalities. The corners of the polyhedra always appear among the endpoints of
these inequalities.
This defines a triangular region in the
plane.
3.4.8 Inequalities
837
Lists of inequalities in general represent regions of overlap between geometrical objects. Often the
description of these can be quite complicated.
This represents the part of the unit
disk on one side of a line.
In[17]:= Reduce[{(x - 1)^2 + y^2 < 2, x^2 + y^2 < 2}, {x, y}]
1
1
2x
Out[16]= 2 3 6 ? x ? 2 3 6 && ? y ? 1 x2
10
10
3
1
2 ? x && 1 2 x x2 ? y ? 1 2 x x2
2
1
? x ? 2 && 2 x2 ? y ? 2 x2
2
Out[17]= 1
In[18]:= Reduce[{(x - 4)^2 + y^2 < 2, x^2 + y^2 < 2}, {x, y}]
In[19]:= Reduce[{Sin[x y] > 1/2, x^2 + y^2 < 3/2}, {x, y}]
Out[18]= False
3
1
Out[19]=
81 4 2 ? x ?
4 12
3 2 x2
1
1
? y ?
9 81 4 2 &&
6x
2
3
2
3
1
1
1
81 4 2 &&
9 81 4 2 ? x ?
4 12
2
3
3 2 x2
? y ?
6x
2
If you have inequalities that involve parameters, Reduce automatically handles the different cases
that can occur, just as it does for equations.
The form of the intervals depends on
the value of a.
838
"
"
"
1 x2 %
1 x2
'
$
$
$
$
$
$
y >
'
$
'
'
$
$
$
$a ? 0 && $
$x 1 && $
$y ?
a
a '
&
#
#
#
1 ? x ? 1
"
%'
%
1 x2
1 x2 '
$
y >
$
'
'
x 1 && $
'
$
''
'
$y ?
a
a ''
#
&&
a 0 && 1 ? x ? 1 a > 0 && 1 ? x ? 1 &&
1 x2
1 x2 %
'
'
? y ?
'
'
a
a '
&
Reduce tries to give you a complete description of the region defined by a set of inequalities.
Sometimes, however, you may just want to find individual instances of values of variables that satisfy
the inequalities. You can do this using FindInstance .
FindInstance[ineqs, vars, n]
In[22]:= FindInstance[{Sin[x y] > 1/2, x^2 + y^2 < 3/2}, {x, y}]
In[23]:= FindInstance[{Sin[x y] > 1/2, x^2 + y^2 < 1/4}, {x, y}]
118
149
Out[22]= x , y
151
185
Out[23]=
FindInstance is in some ways an analog for inequalities of Solve for equations. For like Solve,
it returns a list of rules giving specific values for variables. But while for equations these values can
generically give an accurate representation of all solutions, for inequalities they can only correspond
to isolated sample points within the regions described by the inequalities.
Every time you call FindInstance with specific input, it will give the same output. And when
there are instances that correspond to special, limiting, points of some kind, it will preferentially
return these. But in general, the distribution of instances returned by FindInstance will typically
seem somewhat random. Each instance is, however, in effect a constructive proof that the inequalities
you have given can in fact be satisfied.
If you ask for one point in the unit
disk, FindInstance gives the origin.
839
0.5
-1
-0.5
0.5
-0.5
-1
Mathematica normally assumes that variables which appear in equations can stand for arbitrary complex numbers. But when you use Reduce, you can explicitly tell Mathematica that the variables stand
for objects in more restricted domains.
A single polynomial equation in one variable will always have a finite set of discrete solutions. And
in such a case one can think of Reduce[eqns, vars, dom] as just filtering the solutions by selecting the
ones that happen to lie in the domain dom.
840
But as soon as there are more variables, things can become more complicated, with solutions to
equations corresponding to parametric curves or surfaces in which the values of some variables can
depend on the values of others. Often this dependence can be described by some collection of equations or inequalities, but the form of these can change significantly when one goes from one domain
to another.
This gives solutions over the complex
numbers as simple formulas.
If your input involves only equations, then Reduce will by default assume that all variables are
complex. But if your input involves inequalities, then Reduce will assume that any algebraic variables
appearing in them are real, since inequalities can only compare real quantities.
Since the variables appear in an
inequality, they are assumed to be real.
Complexes
Reals
Integers
1
1 x 1
Out[7]= ? x ? 1 && 1 2 x 3 x2 ?
3
2
2
1 x 1
y ? 1 2 x 3 x2 && z 1 x y
2
2
polynomial != 0, xi == Root[... ]
For systems of polynomials over real and complex domains, the solutions always consist of a
finite number of components, within which the values of variables are given by algebraic numbers or
functions.
Here the components are distinguished
by equations and inequations on x.
841
4
Out[9]= x ? && y Root1 #1 x #13 &, 1
27
4
3
x && y 3 y
27
2
4
? x ? 0 && y Root1 #1 x #13 &, 1
27
y Root1 #1 x #13 &, 2
y Root1 #1 x #13 &, 3
x 0 && y Root1 #1 x #13 &, 1
While in principle Reduce can always find the complete solution to any collection of polynomial
equations and inequalities with real or complex variables, the results are often very complicated, with
the number of components typically growing exponentially as the number of variables increases.
With 3 variables, the solution here
already involves 8 components.
As soon as one introduces functions like Sin or Exp, even equations in single real or complex
variables can have solutions with an infinite number of components. Reduce labels these components by introducing additional parameters. By default, the nth parameter in a given solution will be
named C[n]. In general you can specify that it should be named f[n] by giving the option setting
GeneratedParameters -> f.
The components here are labeled by
the integer parameter c1.
In[11]:= Reduce[Exp[x] == 2, x,
GeneratedParameters -> (Subscript[c, #]&)]
Out[11]= c1 Integers && x Log
2 2 c1
Reduce can handle equations not only over real and complex variables, but also over integers.
Solving such Diophantine equations can often be a very difficult problem.
Describing the solution to this equation
over the reals is straightforward.
8
Out[12]= x ? 0 x > 0 && y
x
842
Reduce can solve any system of linear equations or inequalities over the integers. With m linear
equations in n variables, n m parameters typically need to be introduced. But with inequalities, a
much larger number of parameters may be needed.
Three parameters are needed here, even
though there are only two variables.
With two variables, Reduce can solve any quadratic equation over the integers. The result can be
a Fibonacci-like sequence, represented in terms of powers of quadratic irrationals.
Here is the solution to a Pell equation.
Reduce can handle many specific classes of equations over the integers.
Here Reduce finds the solution to a
Thue equation.
Out[19]= False
Equations over the integers sometimes have seemingly quite random collections of solutions. And
even small changes in equations can often lead them to have no solutions at all.
For polynomial equations over real and complex numbers, there is a definite decision procedure
for determining whether or not any solution exists. But for polynomial equations over the integers,
the unsolvability of Hilberts Tenth Problem demonstrates that there can never be any such general
procedure.
For specific classes of equations, however, procedures can be found, and indeed many are implemented in Reduce. But handling different classes of equations can often seem to require whole
different branches of number theory, and quite different kinds of computations. And in fact it is
known that there are universal integer polynomial equations, for which filling in some variables can
make solutions for other variables correspond to the output of absolutely any possible program. This
843
then means that for such equations there can never in general be any closed-form solution built from
fixed elements like algebraic functions.
If one includes functions like Sin, then even for equations involving real and complex numbers the
same issues can arise.
Reduce here effectively has to solve an
equation over the integers.
Since there are only ever a finite number of possible solutions for integer equations modulo n,
Reduce can systematically find them.
This finds all solutions modulo 4.
,
,
1
1
$y y %
'
x 0 && "
x 1 && y 0
2 &
2
#
Reduce normally treats complex variables as single objects. But in dealing with functions that are
not analytic or have branch cuts, it sometimes has to break them into pairs of real variables Re[z]
and Im[z].
The result involves separate real and
imaginary parts.
In[23]:= Reduce[Abs[z] == 1, z]
Out[23]= 1 Re
z 1 &&
2
2
Im
z 1 Re
z Im
z 1 Re
z
844
Reduce by default assumes that variables that appear algebraically in inequalities are real. But you
can override this by explicitly specifying Complexes as the default domain. It is often useful in such
cases to be able to specify that certain variables are still real.
Reduce by default assumes that x is a
real.
Out[25]= 1 ? x ? 1
Out[26]= 1 ? Re
x ? 0 && Im
x 0
Re
x 0 0 ? Re
x ? 1 && Im
x 0
Out[27]= 1 ? Re x ? 1 &&
2
2
1 Re
x ? Im
x ? 1 Re
x
Integers
Booleans
Reduce always returns a complete representation of the solution to a system of equations or inequalities. Sometimes, however, you may just want to find particular sample solutions. You can do
this using FindInstance .
845
If FindInstance[expr, vars, dom] returns {} then this means that Mathematica has effectively
proved that expr cannot be satisfied for any values of variables in the specified domain. When expr
can be satisfied, FindInstance will normally pick quite arbitrarily among values that do this, as
discussed for inequalities on page 838.
Particularly for integer equations, FindInstance can often find particular solutions to equations
even when Reduce cannot find a complete solution. In such cases it usually returns one of the smallest
solutions to the equations.
This finds the smallest integer point on
an elliptic curve.
One feature of FindInstance is that it also works with Boolean expressions whose variables can
have values True or False. You can use FindInstance to determine whether a particular expression
is satisfiable, so that there is some choice of truth values for its variables that makes the expression
True.
This expression cannot be satisfied for
any choice of p and q.
Out[30]=
Out[2]= True
846
3
3
Out[4]= ? y ?
2
2
Reduce[expr, {x , x , ... }] is set up to describe regions by first giving fixed conditions for x ,
then giving conditions for x that depend on x , then conditions for x
that depend on x and x , and
so on. This structure has the feature that it allows one to pick points by successively choosing values
for each of the xi in turnin much the same way as when one uses iterators in functions like Table.
This gives a representation for the
region in which one first picks a value
for y, then x.
In some simple cases the region defined by a system of equations or inequalities will end up having
only one component. In such cases, the output from Reduce will be of the form e && e && ... where
each of the ei is an equation or inequality involving variables up to xi .
In most cases, however, there will be several components, represented by output containing forms
such as u || u || ... . Reduce typically tries to minimize the number of components used in describing a region. But in some cases multiple parametrizations may be needed to cover a single
connected component, and each one of these will appear as a separate component in the output from
Reduce.
In representing solution sets, it is common to find that several components can be described together by using forms such as ... && (u || u ) && ... . Reduce by default does this so as to return
its results as compactly as possible. You can use LogicalExpand to generate an expanded form in
which each component appears separately.
In generating the most compact results, Reduce sometimes ends up making conditions on later
variables xi depend on more of the earlier xi than is strictly necessary. You can force Reduce to
generate results in which a particular xi only has minimal dependence on earlier xi by giving the
option Backsubstitution->True . Usually this will lead to much larger output, although sometimes
it may be easier to interpret.
By default, Reduce expresses the
condition on y in terms of x.
847
For polynomial equations or inequalities over the reals, the structure of the result returned by
Reduce is typically a cylindrical algebraic decomposition or CAD. Sometimes Reduce can yield a simpler
form. But in all cases you can get the complete CAD by using CylindricalDecomposition .
In a statement like x^4 + x^2 > 0, Mathematica treats the variable x as having a definite, though
unspecified, value. Sometimes, however, it is useful to be able to make statements about whole
collections of possible values for x. You can do this using quantifiers.
ForAll[x, expr]
Exists[x, expr]
You can work with quantifiers in Mathematica much as you work with equations, inequalities or
logical connectives. In most cases, the quantifiers will not immediately be changed by evaluation. But
they can be simplified or reduced by functions like FullSimplify and Reduce.
This asserts that an x exists that makes
the inequality true. The output here is
just a formatted version of the input.
In[2]:= FullSimplify[%]
Out[1]= ]x x2 x4 > 0
Out[2]= True
Out[3]= False
848
Mathematica supports a version of the standard notation for quantifiers used in predicate logic and
pure mathematics. You can input \ as \[ForAll] or , fa ,, and you can input ] as \[Exists] or , ex ,.
To make the notation precise, however, Mathematica makes the quantified variable a subscript. The
conditions on the variable can also be given in the subscript, separated by a comma.
\x expr
]x expr
ForAll[x, expr]
ForAll[{x , x , ... }, expr]
ForAll[x, cond, expr]
Exists[x, expr]
Exists[{x , x , ... }, expr]
Exists[x, cond, expr]
Given a statement that involves quantifiers, there are certain important cases where it is possible to
resolve it into an equivalent statement in which the quantifiers have been eliminated. Somewhat like
solving an equation, such quantifier elimination turns an implicit statement about what is true for all
x or for some x into an explicit statement about the conditions under which this holds.
Resolve[expr]
Resolve[expr, dom]
Quantifier elimination.
Out[4]= True
Out[5]= 1 2 c c2 c3 0
Resolve can always eliminate quantifiers from any collection of polynomial equations and inequations over complex numbers, and from any collection of polynomial equations and inequalities over
real numbers. It can also eliminate quantifiers from Boolean expressions.
849
b2
b2
"
$b ? 0 && a > b 0 && a 0 b > 0 && a > %
'
4
c
4
c&
#
In[7]:= Resolve[Exists[{p, q}, p || q && ! q], Booleans]
Out[7]= True
You can also use quantifiers with Reduce. If you give Reduce a collection of equations or inequalities, then it will try to produce a detailed representation of the complete solution set. But sometimes
you may want to address a more global question, such as whether the solution set covers all values
of x, or whether it covers none of these values. Quantifiers provide a convenient way to specify such
questions.
This gives the complete structure of the
solution set.
1
Out[8]= c ? &&
4
1 1
1 1
x 1 4 c x 1 4 c
2 2
2 2
1
1
c && x
4
2
1
Out[9]= c
4
In[10]:= Reduce[ForAll[{x, y}, x^2 + y^2 < 1, a x^2 + b y^2 < c],
{a, b, c}, Reals]
Out[10]= a 0 && b 0 && c > 0 b > 0 && c b
a > 0 && b ? a && c a b a && c b
In[11]:= Reduce[Exists[{x, y}, x^2 + y^2 < 1, r x + s y == 1],
{r, s}, Reals]
Out[11]= r ? 1
1 r 1 && s ? 1 r2 s > 1 r2 r > 1
3 b2
b3
b4
Out[13]= c && d && e
8
16
256
b 0 && c 0 && d 0 && e 0
850
Although quantifier elimination over the integers is in general a computationally impossible problem, Mathematica can do it in specific cases.
This shows that cannot be a
rational number.
is, though.
,
,
,
,
minimize expr
maximize expr
Minimize and Maximize yield lists giving the value attained at the minimum or maximum, together
with rules specifying where the minimum or maximum occurs.
This finds the minimum of a quadratic
function.
In[1]:= Minimize[x^2 - 3x + 6, x]
3
15
Out[1]= , x
2
4
15
Out[2]=
4
In[3]:= Maximize[5 x y - x^4 - y^4, {x, y}]
25
5
5
Out[3]= , x , y
8
2
2
Minimize[expr, x] minimizes expr allowing x to range over all possible values from to .
Minimize[{expr, cons}, x] minimizes expr subject to the constraints cons being satisfied. The constraints can consist of any combination of equations and inequalities.
This finds the minimum subject to the
constraint x !
.
851
In[5]:= Maximize[{5 x y - x^4 - y^4, x^2 + y^2 <= 1}, {x, y}]
In[6]:= Maximize[{5 x y - x^4 - y^4, x^2 + 2y^2 <= 1}, {x, y}]
1
1
Out[5]= 2, x
, y
2
2
Out[6]=
Root811219 320160 #1
274624 #12 170240 #13 25600 #14 &, 1,
x Root25 102 #12 122 #14 70 #16 50 #18 &, 2,
y Root
25 264 #12 848 #14 1040 #16 800 #18 &, 1!!
9
1
1
Out[7]= , x , y
8
2
2
Minimize and Maximize can solve any linear programming problem in which both the objective
function expr and the constraints cons involve the variables xi only linearly.
Here is a typical linear programming
problem.
53
44
3
Out[8]= , x , y
5
5
5
They can also in principle solve any polynomial programming problem in which the objective function
and the constraints involve arbitrary polynomial functions of the variables. There are many important
geometrical and other problems that can be formulated in this way.
This solves the simple geometrical
problem of maximizing the area of a
rectangle with fixed perimeter.
1
1
1
Out[9]= , x , y
4
2
2
8
1
1
1
Out[10]=
, x
, y
, z
3 3
3
3
3
An important feature of Minimize and Maximize is that they always find global minima and
maxima. Often functions will have various local minima and maxima at which derivatives vanish.
But Minimize and Maximize use global methods to find absolute minima or maxima, not just local
extrema.
852
10
-10
-5
10
-5
-10
8
8
Out[12]= 3 , x
3
3
If you give functions that are unbounded, Minimize and Maximize will return - and + as the
minima and maxima. And if you give constraints that can never be satisfied, they will return + and
- as the minima and maxima, and Indeterminate as the values of variables.
One subtle issue is that Minimize and Maximize allow both non-strict inequalities of the form x <= v,
and strict ones of the form x < v. With non-strict inequalities there is no problem with a minimum or
maximum lying exactly on the boundary x -> v. But with strict inequalities, a minimum or maximum
must in principle be at least infinitesimally inside the boundary.
With a strict inequality, Mathematica
prints a warning, then returns the
point on the boundary.
Minimize and Maximize normally assume that all variables you give are real. But by giving a
constraint such as x Integers you can specify that a variable must in fact be an integer.
This does maximization only over
integer values of x and y.
3.5.1 Differentiation
853
3.5 Calculus
3.5.1 Differentiation
D[f, x]
D[f, x , x , ... ]
D[f, {x, n}]
partial derivative
"
"x
multiple derivative
nth derivative
"n
"xn
f
" "
"x "x
In[1]:= D[x^n, x]
Out[1]= n x1n
Out[3]= 2 x 1
Out[4]= 2 x
Out[5]= 2 x 2 y x y< x
854
SetAttributes[c, Constant]
total differential df
total derivative
df
dx
d d
dx dx
dy
dx
When you find the derivative of some expression f with respect to x, you are effectively finding out
how fast f changes as you vary x. Often f will depend not only on x, but also on other variables, say
y and z. The results that you get then depend on how you assume that y and z vary as you change x.
There are two common cases. Either y and z are assumed to stay fixed when x changes, or they
"f
are allowed to vary with x. In a standard partial derivative "x , all variables other than x are assumed
fixed. On the other hand, in the total derivative
df
dx ,
In Mathematica, D[f, x] gives a partial derivative, with all other variables assumed independent of
x. Dt[f, x] gives a total derivative, in which all variables are assumed to depend on x. In both cases,
you can add an argument to give more information on dependencies.
This gives the partial derivative
"
"x x y . y is assumed to be
independent of x.
d
This gives the total derivative dx
x y .
Now y is assumed to depend on x.
dy
Out[4]= 0
In[6]:= Clear[y]
Out[5]= 2 x 2 z Dt z, x
855
Out[9]= 2 c x 2 a Dt a, x
Out[10]= 2 x c x 2 a Dt a, x
Out[11]= 2 x Dt x 2 c y Dt y
Out[12]= 2 c dy y 2 x Dt x
In[1]:= D[Log[x]^2, x]
In[2]:= D[f[x]^2, x]
In[4]:= D[%, x]
2 Log
x
Out[1]=
x
Out[2]= 2 f
x f<
x
Out[3]= f x2 2 x2 f< x2
Out[5]= 2 x g1,0 x2 , y2
856
f'[x]
f (n) [x]
f (n ,n , ) [x]
In[7]:= % /. x->0
Out[7]= g2,1
0, y
857
In[5]:= % // FullForm
Out[4]= g0,1 x, y
Out[5]//FullForm= Derivative 0, 1 g x, y
Out[6]//FullForm= Derivative 0, 2 g x, y
Out[7]//FullForm= Derivative 1, 2 g x, y
In[10]:= % // FullForm
Out[8]//FullForm= Derivative 1, 2 g x, y
The object f' behaves essentially like any other function in Mathematica. You can evaluate the
function with any argument, and you can use standard Mathematica /. operations to change the
argument. (This would not be possible if explicit dummy variables had been introduced in the course
of the differentiation.)
This is the Mathematica representation
of the derivative of a function f,
evaluated at the origin.
In[12]:= D[f[x^2], x]
In[13]:= % /. x->2
Out[11]//FullForm= Derivative 1 f 0
Out[12]= 2 x f< x2
Out[13]= 4 f< 4
There is some slight subtlety when you need to deduce the value of f' based on definitions for
objects like f[x_].
858
In[15]:= D[h[x], x]
In[16]:= h'[x]
In[17]:= h'
Out[15]= 4 x3
Out[16]= 4 x3
The function f' is completely determined by the form of the function f. Definitions for objects
like f[x_] do not immediately apply however to expressions like f'[x]. The problem is that f'[x]
has the full form Derivative[1][f][x] , which nowhere contains anything that explicitly matches
the pattern f[x_]. In addition, for many purposes it is convenient to have a representation of the
function f' itself, without necessarily applying it to any arguments.
What Mathematica does is to try and find the explicit form of a pure function which represents the
object f'. When Mathematica gets an expression like Derivative[1][f] , it effectively converts it to the
explicit form D[f[#], #]& and then tries to evaluate the derivative. In the explicit form, Mathematica
can immediately use values that have been defined for objects like f[x_]. If Mathematica succeeds in
doing the derivative, it returns the explicit pure-function result. If it does not succeed, it leaves the
derivative in the original f' form.
This gives the derivative of Tan in
pure-function form.
In[18]:= Tan'
In[19]:= %[y]
Out[19]= Sec y
In[2]:= D[f[x^2], x]
In[3]:= D[%, x]
Out[2]= 2 x fp x2
Out[3]= 2 fp x2 4 x2 fp< x2
859
In[4]:= g'[0] = g0
Out[4]= g0
Out[5]= 2 g0 g 0
Out[6]= gpp x
To define derivatives of functions with several arguments, you have to use the general representation
of derivatives in Mathematica.
f'[x_] := rhs
Derivative[n][f][x_] := rhs
860
In[1]:= Integrate[x^2, x]
x3
Out[1]=
3
In[2]:= D[ % + c, x]
Out[2]= x2
In[4]:= D[%, x]
In[5]:= Simplify[%]
x
1
1
Out[3]= Log
1 x Log
1 x
2
2
1
1
Out[4]=
2 1 x 2 1 x
1
Out[5]=
1 x2
The Integrate function assumes that any object that does not explicitly contain the integration
variable is independent of it, and can be treated as a constant. As a result, Integrate is like an
inverse of the partial differentiation function D.
The variable a is assumed to be
independent of x.
a x3
Out[6]=
3
1
3
Out[7]= x b
x
3
Another assumption that Integrate implicitly makes is that all the symbolic quantities in your
n
integrand have generic values. Thus, for example, Mathematica will tell you that xn dx is xn even
though this is not true in the special case n .
Mathematica gives the standard result
for this integral, implicitly assuming
that n is not equal to -1.
In[8]:= Integrate[x^n, x]
In[9]:= Integrate[x^-1, x]
x1n
Out[8]=
1n
Out[9]= Log x
You should realize that the result for any particular integral can often be written in many different
forms. Mathematica tries to give you the most convenient form, following principles such as avoiding
explicit complex numbers unless your input already contains them.
861
In[12]:= % /. b -> -a
In[13]:= D[%, x]
ArcTan a x
Out[10]=
a
ArcTanh b x
Out[11]=
b
ArcTanh a x
Out[12]=
a
1
Out[13]=
1 a x2
Even though they look quite different,
both ArcTan[x] and -ArcTan[1/x] are
indefinite integrals of x .
1
1
Out[14]=
,
1 x2 1 x2
Out[15]= ArcTan x
In[1]:= Integrate[Log[x]^2, x]
In[2]:= Integrate[Log[Log[x]], x]
In[3]:= Integrate[Sin[x^2], x]
2
Out[3]=
FresnelS
x
2
862
In[5]:= Integrate[Exp[-x^a], x]
3 3
1 1
Out[4]= x HypergeometricPFQ ,
, ,
, x2
2 2
2 2
1
Erf
x Log
x
2
1a
x xa
Gamma 1a , xa
Out[5]=
a
Mathematica includes a very wide range of mathematical functions, and by using these functions a
great many integrals can be done. But it is still possible to find even fairly simple-looking integrals
that just cannot be done in terms of any standard mathematical functions.
Here is a fairly simple-looking integral
that cannot be done in terms of any
standard mathematical functions.
In[6]:= Integrate[Sin[x]/Log[x], x]
Sin
x
Out[6]= 7x
Log
x
The main point of being able to do an integral in terms of standard mathematical functions is that
it lets one use the known properties of these functions to evaluate or manipulate the result one gets.
In the most convenient cases, integrals can be done purely in terms of elementary functions such
as exponentials, logarithms and trigonometric functions. In fact, if you give an integrand that involves only such elementary functions, then one of the important capabilities of Integrate is that if
the corresponding integral can be expressed in terms of elementary functions, then Integrate will
essentially always succeed in finding it.
Integrals of rational functions are
straightforward to evaluate, and always
come out in terms of rational functions,
logarithms and inverse trigonometric
functions.
In[9]:= N[%]
1
2
Out[7]= Log
1 x Log
2 x
3
3
Log
x #1
Out[8]= RootSum1 2 #1 #13 &,
&
2 3 #12
Out[9]= 0.19108 0.088541
Log
0.226699 1.46771 x
0.19108 0.088541
Log
0.226699 1.46771 x
0.38216 Log
0.453398 x
1
3
Out[10]= Cos
x 7 3 Cos
2 x
30
863
1
Out[11]= x 1 x 1 2 x ArcSinh x
4
Out[12]=
x x 1 x x14 3 2 x 8 x
3 ArcSinh
x14 > 12
In[13]:= Integrate[Cos[Log[x]], x]
In[14]:= Integrate[Log[Cos[x]], x]
In[15]:= Integrate[Sqrt[Cos[x]], x]
x
Out[15]= 2 EllipticE , 2
2
In[16]:= Integrate[Sqrt[Tan[x]], x]
1 x x14
1
Out[13]= x Cos
Log
x Sin
Log
x
2
x2
Out[14]= x Log
1 2 x
2
1
x Log
Cos
x PolyLog
2, 2 x
2
1
Out[16]=
2 ArcTan1 2 Tan
x
2 2
2 ArcTan1 2 Tan
x
Log1 2 Tan
x Tan
x
Log1 2 Tan
x Tan
x
Beyond working with elementary functions, Integrate includes a large number of algorithms for
dealing with special functions. Sometimes it uses a direct generalization of the procedure for elementary functions. But more often its strategy is first to try to write the integrand in a form that can be
integrated in terms of certain sophisticated special functions, and then having done this to try to find
reductions of these sophisticated functions to more familiar functions.
To integrate this Bessel function
requires a generalized hypergeometric
function.
In[18]:= Integrate[EllipticK[x], x]
1
3
x2
Out[17]= x HypergeometricPFQ
, 1,
,
2
2
4
1
1 1
Out[18]= x HypergeometricPFQ ,
, 2, x
2
2 2
864
A large book of integral tables will list perhaps a few thousand indefinite integrals. Mathematica
can do essentially all of these integrals. And because it contains general algorithms rather than just
specific cases, Mathematica can actually do a vastly wider range of integrals.
You could expect to find this integral
in any large book of integral tables.
Out[20]= PolyLog 2, x
2x
Out[21]= Log
x Log1
3 5
2x
2
Log
x Log1
Log
x Log
1 3 x x
3 5
2x
2x
PolyLog2,
PolyLog2,
3 5
3 5
Particularly if you introduce new mathematical functions of your own, you may want to teach
Mathematica new kinds of integrals. You can do this by making appropriate definitions for Integrate .
In the case of differentiation, the chain rule allows one to reduce all derivatives to a standard
form, represented in Mathematica using Derivative . But for integration, no such similar standard
form exists, and as a result you often have to make definitions for several different versions of the
same integral. Changes of variables and other transformations can rarely be done automatically by
Integrate .
This integral cannot be done in terms
of any of the standard mathematical
functions built into Mathematica.
In[22]:= Integrate[Sin[Sin[x]], x]
In[23]:= Unprotect[Integrate]
In[25]:= Integrate[Sin[Sin[3x]], x]
Out[23]= Integrate
1
Out[25]= Jones
0, x
3
As it turns out, the integral sinsinx dx can in principle be represented as an infinite sum of F
hypergeometric functions, or as a suitably generalized Kampe de Feriet hypergeometric function of
two variables.
865
1
Out[1]= a3 b3
3
This gives the multiple integral
a
b
dx dy x
y .
1
Out[2]= a b a2 b2
3
In[3]:= Integrate[x^2 + y^2, {x, 0, a}, {y, 0, x}]
a4
Out[3]=
3
In simple cases, definite integrals can be done by finding indefinite forms and then computing appropriate limits. But there is a vast range of integrals for which the indefinite form cannot be expressed
in terms of standard mathematical functions, but the definite form still can be.
This indefinite integral cannot be done
in terms of standard mathematical
functions.
In[4]:= Integrate[Cos[Sin[x]], x]
Out[5]= 2 BesselJ 0, 1
1
Out[6]= EulerGamma Log
4
4
2
Out[7]=
4
Gamma 14
Out[8]=
4 2
866
1
3 5
1
,
,
Out[9]=
2 HypergeometricPFQ1,
4 4
64
2 2
1
1
Cos Sin
4
4
Even when you can find the indefinite form of an integral, you will often not get the correct answer
for the definite integral if you just subtract the values of the limits at each end point. The problem
is that within the domain of integration there may be singularities whose effects are ignored if you
follow this procedure.
Here is the indefinite integral of x .
In[10]:= Integrate[1/x^2, x]
1
Out[10]=
x
This subtracts the limits at each end
point.
Out[11]= 1
Out[12]=
aTan
2
2 ArcTan
1a2
Out[13]=
1 a2
x
Out[14]= 0
4
Out[15]=
4 4 a2
In[16]:= Integrate[1/x, x]
Out[16]= Log
x
867
Out[18]=
1
1
7x
x
When parameters appear in an indefinite integral, it is essentially always possible to get results that
are correct for almost all values of these parameters. But for definite integrals this is no longer the
case. The most common problem is that a definite integral may converge only when the parameters
that appear in it satisfy certain specific conditions.
This indefinite integral is correct for all
n ^ .
In[20]:= Integrate[x^n, x]
x1n
Out[20]=
1n
1
Out[21]= IfRe
n > 1, ,
1n
Integrate
xn , x, 0, 1, Assumptions Re
n 1
In[22]:= % /. n -> 2
1
Out[22]=
3
option name
default value
GenerateConditions
Automatic
Assumptions
{}
1
Out[23]=
1n
Even when a definite integral is convergent, the presence of singularities on the integration path
can lead to discontinuous changes when the parameters vary. Sometimes a single formula containing
functions like Sign can be used to summarize the result. In other cases, however, an explicit If is
more convenient.
868
1
Out[24]= IfIm
a 0, Sign
a, Integrate
2
Sin
a x
, x, 0, , Assumptions Im
a 0
x
1
Out[25]= Sign
a
2
The result is discontinuous as a
function of a. The discontinuity can be
traced to the essential singularity of
sinx at x .
1.5
1
0.5
-4
-2
-0.5
-1
-1.5
a ArcSin 1a
Out[27]= Ifa2 > 1,
,
Abs
a
2
1.5
1.25
1
0.75
0.5
0.25
-4
-2
869
In[2]:= D[%, x]
Out[1]= x2 f x7x
Out[2]= x2 f x
b x
Out[3]=
f x7 x
a x
In[4]:= D[%, x]
Out[5]= f
x7x
a
In[6]:= D[defint, u]
In[7]:= Dt[defint, u]
Out[6]= 0
Out[7]= Dt a, u f a Dt b, u f b
870
DSolve[eqn, y[x], x]
DSolve[eqn, y, x]
Out[5]= True
1
1
x 1 2 x C
1 x 1 2 x C
2,
2
2
1 x
y Functionx, 1 2 x C
1
2
1 x
2x
1 C
2
871
You can add constraints and boundary conditions for differential equations by explicitly giving
additional equations such as y[0] == 0.
This asks for a solution which satisfies
the condition y[0] == 1.
If you ask Mathematica to solve a set of differential equations and you do not give any constraints
or boundary conditions, then Mathematica will try to find a general solution to your equations. This
general solution will involve various undetermined constants. One new constant is introduced for
each order of derivative in each equation you give.
The default is that these constants are named C[n], where the index n starts at 1 for each
invocation of DSolve. You can override this choice, by explicitly giving a setting for the option
GeneratedParameters . Any function you give is applied to each successive index value n to get the
constants to use for each invocation of DSolve.
The general solution to this
fourth-order equation involves four
undetermined constants.
Out[10]= y
x
x C
3 2 x C
3 2 x C
4 2 x C
3 Cos
x
x C
4 Cos
x x C
4 Sin
x
You should realize that finding exact formulas for the solutions to differential equations is a difficult
matter. In fact, there are only fairly few kinds of equations for which such formulas can be found, at
least in terms of standard mathematical functions.
The most widely investigated differential equations are linear ones, in which the functions you are
solving for, as well as their derivatives, appear only linearly.
This is a homogeneous first-order
linear differential equation, and its
solution is quite simple.
x2
Out[11]= y x 2 C 1
x2
x2
x
Out[12]= y
x 2 C
1 2
Erf
2
2
If you have only a single linear differential equation, and it involves only a first derivative of the
function you are solving for, then it turns out that the solution can always be found just by doing
integrals.
872
But as soon as you have more than one differential equation, or more than a first-order derivative,
this is no longer true. However, some simple second-order linear differential equations can nevertheless be solved using various special functions from Section 3.2.10. Indeed, historically many of
these special functions were first introduced specifically in order to represent the solutions to such
equations.
This is Airys equation, which is solved
in terms of Airy functions.
x
Out[15]= y Functionx, C
1 MathieuC0, 2,
2
x
C
2 MathieuS0, 2,
2
Occasionally second-order linear
equations can be solved using only
elementary functions.
1
x C
1 Cos 3 Log
x
2
1
x C
2 Sin 3 Log
x
Out[16]= y x
Beyond second order, the kinds of functions needed to solve even fairly simple linear differential
equations become extremely complicated. At third order, the generalized Meijer G function MeijerG
can sometimes be used, but at fourth order and beyond absolutely no standard mathematical functions
are typically adequate, except in very special cases.
Here is a third-order linear differential
equation which can be solved in terms
of generalized hypergeometric
functions.
1 3
x4
Out[17]= y
x C
1 HypergeometricPFQ, ,
,
2 4
64
4
x
x C
2 HypergeometricPFQ, 34 , 54 !,
1
64
8
2 2
5 3
x4
x2 C
3 HypergeometricPFQ, ,
,
4 2
64
This requires more general Meijer G
functions.
For nonlinear differential equations, only rather special cases can usually ever be solved in terms
of standard mathematical functions. Nevertheless, DSolve includes fairly general procedures which
allow it to handle almost all nonlinear differential equations whose solutions are found in standard
reference books.
873
1
Out[19]= y
x
x C 1
Out[20]= y x
2 2 x32
2 2 x32
"
$
$BesselJ , BesselJ ,
x "
3
3
3
3
#
#
32
1 2x
%'
%>$
"BesselJ
C
1'
,
3
3
&& #
1 2 x32
'
x
Out[21]= y
x
x x x C 1
Solve::tdep:
The equations appear to involve the variables to be
solved for in an essentially non-algebraic way.
12 x y
x
2 ArcTanh
1 "
$
5
$
Out[22]= Solve $
$
$
2
5
#
1 x y
x 1 x y
x %
'
'
Log
'
'
'
2
x2 y
x
&
C
1 Log
x, y
x
Beyond ordinary differential equations, one can consider differential-algebraic equations that involve a
mixture of differential and algebraic equations.
This solves a differential-algebraic
equation.
3
1
Out[23]= y
x
2 18
2 x C
1 9 2 x 3 2 x ExpIntegralEi
2 x,
1
1
z
x 2 x C
1
2 18
9 2 x 3 2 x ExpIntegralEi
2 x
874
DSolve is set up to handle not only ordinary differential equations in which just a single independent
variable appears, but also partial differential equations in which two or more independent variables
appear.
This finds the general solution to a
simple partial differential equation with
two independent variables.
1
Out[24]= y
x1, x2 Log
x1 Log
x2
x1 x2
x1 C
1
x1 x2 x2 C
1
x1 x2
1
Out[25]= y Functionx1, x2, Log
x1 Log
x2
x1 x2
x1 C
1
x1 x2 x2 C
1
x1 x2
The basic mathematics of partial differential equations is considerably more complicated than that
of ordinary differential equations. One feature is that whereas the general solution to an ordinary
differential equation involves only arbitrary constants, the general solution to a partial differential
equation, if it can be found at all, must involve arbitrary functions. Indeed, with m independent
variables, arbitrary functions of m arguments appear. DSolve by default names these functions
C[n].
Here is a simple PDE involving three
independent variables.
In[26]:= (D[#, x1] + D[#, x2] + D[#, x3])& [y[x1, x2, x3]] == 0
c2 x
c2 x
Out[29]= y
x, t C
1t
C
2t
c2
c2
875
For an ordinary differential equation, it is guaranteed that a general solution must exist, with the
property that adding initial or boundary conditions simply corresponds to forcing specific choices for
arbitrary constants in the solution. But for partial differential equations this is no longer true. Indeed,
it is only for linear partial differential and a few other special types that such general solutions exist.
Other partial differential equations can be solved only when specific initial or boundary values
are given, and in the vast majority of cases no solutions can be found as exact formulas in terms of
standard mathematical functions.
Since y and its derivatives appear only
linearly here, a general solution exists.
1
x2
ExpIntegralEi
x1 x2 2 C
1
2
x1
This weakly nonlinear PDE turns out
to have a general solution.
LaplaceTransform[expr, t, s]
InverseLaplaceTransform[expr, s, t]
The Laplace transform of a function ft is given by ftest dt. The inverse Laplace transform of
i
i i
24 1 5 s2 2 s2
Out[1]=
5
1 s2
876
In[2]:= InverseLaplaceTransform[%, s, t]
Out[2]= t4 Sin
t
s
MeijerG 23 !, !, 0, 13 , 23 , 23 !, !,
27
Out[4]=
2 3
n
s 1 s2
Out[5]=
1 s2
Laplace transforms have the property that they turn integration and differentiation into essentially
algebraic operations. They are therefore commonly used in studying systems governed by differential
equations.
Integration becomes multiplication by
s when one does a Laplace
transform.
LaplaceTransform
f
t, t, s
Out[6]=
s
Fourier Transforms
FourierTransform[expr, t, ]
InverseFourierTransform[expr, , t]
One-dimensional Fourier transforms.
877
1
1
Out[1]= 2
2 2 UnitStep
4 4
1
2
UnitStep
In[2]:= InverseFourierTransform[%, , t]
1
Out[2]=
1 t4
F eit d.
In different scientific and technical fields different conventions are often used for defining Fourier
transforms. The option FourierParameters in Mathematica allows you to choose any of these conventions you want.
common convention
setting
Fourier transform
Mathematica default
{0, 1}
pure mathematics
{1, -1}
ft e
classical physics
{-1, 1}
modern physics
{0, 1}
systems engineering
{1, -1}
ft e
signal processing
{0, -2 Pi}
general case
{a, b}
ft e
"
/b/
ft e
it
dt
ft e
a
it
it
dt
d
it
F eit d
dt
ft e
it
F e
it
F eit d
F e
dt
it
F e
dt
ft eit dt
it
ibt
dt
it
d
F e
"
/b/
F eibt d
a
In[3]:= FourierTransform[Exp[-t^2], t, ]
2
4
Out[3]=
2
In[4]:= FourierTransform[Exp[-t^2], t, ,
FourierParameters->{0, -2 Pi}]
2 2
Out[4]=
878
FourierSinTransform[expr, t, ]
FourierCosTransform[expr, t, ]
InverseFourierSinTransform[expr, , t]
inverse Fourier sine transform
InverseFourierCosTransform[expr, , t]
inverse Fourier cosine transform
Fourier sine and cosine transforms.
In[5]:= {FourierSinTransform[Exp[-t], t, ],
FourierCosTransform[Exp[-t], t, ]}
2
2
Out[5]=
,
1 2
1 2
879
v2
u2 v2
Z Transforms
ZTransform[expr, n, z]
InverseZTransform[expr, z, n]
Z transform of expr
inverse Z transform of expr
Z transforms.
n
The Z transform of a function fn is given by
n fnz . The inverse Z transform of Fz is given
n
by the contour integral i ) Fzz dz. Z transforms are effectively discrete analogs of Laplace transforms. They are widely used for solving difference equations, especially in digital signal processing
and control theory. They can be thought of as producing generating functions, of the kind commonly
used in combinatorics and number theory.
In[1]:= ZTransform[2^-n, n, z]
2z
Out[1]=
1 2 z
Here is the inverse Z transform.
In[2]:= InverseZTransform[%, z, n]
Out[2]= 2n
In[3]:= ZTransform[1/n!, n, z]
Out[3]= z
1
DiracDelta[x]
UnitStep[x]
Dirac delta and unit step functions.
880
-2
-1
5
4
3
2
1
-2
-1
Out[4]= 1
Inserting a delta function in an integral effectively causes the integrand to be sampled at discrete
points where the argument of the delta function vanishes.
This samples the function f with
argument 2.
Out[6]= f 2
1
Out[7]=
5
881
The unit step function UnitStep[x] is effectively the indefinite integral of the delta function. It
is sometimes known as the Heaviside function, and is variously denoted Hx, x, x, and Ux.
It does not need to be considered as a generalized function, though it has a discontinuity at x .
The unit step function is often used in setting up piecewise continuous functions, and in representing
signals and other quantities that become non-zero only beyond some point.
The indefinite integral of the delta
function is the unit step function.
In[9]:= Integrate[DiracDelta[x], x]
Out[9]= UnitStep x
1
0.8
0.6
0.4
0.2
10
15
20
25
30
In[13]:= FourierTransform[1, t, ]
Out[13]=
2 DiracDelta
In[14]:= FourierTransform[Cos[t], t, ]
Out[14]=
DiracDelta
1
DiracDelta
1
2
2
Dirac delta functions can be used in DSolve to find the impulse response or Greens function of
systems represented by linear and certain other differential equations.
This finds the behavior of a harmonic
oscillator subjected to an impulse at
t .
Sin r t UnitStep
t
Out[15]= x
t
r
882
DiracDelta[x , x , ... ]
UnitStep[x , x , ... ]
Related to the multidimensional Dirac delta function are two integer functions: discrete delta and
Kronecker delta. Discrete delta n n is 1 if all the ni , and is zero otherwise. Kronecker delta
n n is 1 if all the ni are equal, and is zero otherwise.
DiscreteDelta[n , n , ... ]
KroneckerDelta[n , n , ... ]
Integer delta functions.
883
x2
x3
x4
5
Out[1]= 1 x O
x
2
6
24
1
2
Out[2]= x 1 x 1
2
1
1
3
4
5
x 1 x 1 O
x 1
24
6
1
1
4
Out[3]= f
0 f<
0 x f<<
0 x2 f3
0 x3 O
x
2
6
In mathematical terms, Series can be viewed as a way of constructing Taylor series for functions.
The standard formula for the Taylor series expansion about the point x x of a function gx
xx k
k
with kth derivative gk x is gx
k g x kd . Whenever this formula applies, it gives the
same results as Series. (For common functions, Series nevertheless internally uses somewhat more
efficient algorithms.)
Series can also generate some power series that involve fractional and negative powers, not
directly covered by the standard Taylor series formula.
Here is a power series that contains
negative powers of x.
1 1 x x2
x3
x4
1
5
Out[4]=
O
x
2
x
x 2 6 24 120 720
Out[5]= 1
32
x2
52
x x
x O
x
2
6
24
884
There are, of course, mathematical functions for which no standard power series exist. Mathematica
recognizes many such cases.
Series sees that exp x has an
essential singularity at x , and does
not produce a power series.
Out[7]= x
1
1 1 1 2 1 1 3
1 4
Out[8]= 1 O
x 2 x
6 x
x
Especially when negative powers occur, there is some subtlety in exactly how many terms of a
particular power series the function Series will generate.
One way to understand what happens is to think of the analogy between power series taken to a
certain order, and real numbers taken to a certain precision. Power series are approximate formulas
in much the same sense as finite-precision real numbers are approximate numbers.
The procedure that Series follows in constructing a power series is largely analogous to the procedure that N follows in constructing a real-number approximation. Both functions effectively start
by replacing the smallest pieces of your expression by finite-order, or finite-precision, approximations,
and then evaluating the resulting expression. If there are, for example, cancellations, this procedure
may give a final result whose order or precision is less than the order or precision that you originally
asked for. Like N, however, Series has some ability to retry its computations so as to get results
to the order you ask for. In cases where it does not succeed, you can usually still get results to a
particular order by asking for a higher order than you need.
Series compensates for cancellations
in this computation, and succeeds in
giving you a result to order x
.
1 x
x3
4
Out[9]= O
x
x 6 120
When you make a power series expansion in a variable x, Mathematica assumes that all objects
that do not explicitly contain x are in fact independent of x. Series thus does partial derivatives
(effectively using D) to build up Taylor series.
Both a and n are assumed to be
independent of x.
1
1
3
Out[10]= an a1n n x a2n n a2n n2 x2 O
x
2
2
885
Out[11]= a
0 n a
0
1 a<
0 x
1
2n
2
1 a<
0
1 n n a
0
2
1
1n <<
3
a
0 x2 O
x
n a
0
2
n
You can use Series to generate power series in a sequence of different variables. Series works
like Integrate , Sum and so on, and expands first with respect to the last variable you specify.
Series performs a series expansion
successively with respect to each
variable. The result in this case is a
series in x, whose coefficients are series
in y.
Out[12]= 1 y O y x
y2
y
"
$ O
y4 %
$ O
y4 %
' x2 "
' x3 O
x4
# 6
# 2
&
&
In[2]:= InputForm[%]
x2
x4
5
Out[1]= 1 O
x
2
24
By using SeriesData objects, rather than ordinary expressions, to represent power series, Mathematica can keep track of the order and expansion point, and do operations on the power series
appropriately. You should not normally need to know the internal structure of SeriesData objects.
You can recognize a power series that is printed out in standard output form by the presence of an
O[x] term. This term mimics the standard mathematical notation Ox, and represents omitted terms
of order x. For various reasons of consistency, Mathematica uses the notation O[x]^n for omitted terms
of order xn , corresponding to the mathematical notation Oxn , rather than the slightly more familiar,
though equivalent, form Oxn .
Any time that an object like O[x] appears in a sum of terms, Mathematica will in fact convert the
whole sum into a power series.
The presence of O[x] makes
Mathematica convert the whole sum to
a power series.
x2
3
Out[3]= 1 1 a x O
x
2
886
In[2]:= %^2
In[3]:= Log[%]
x2
x3
x4
5
Out[1]= 1 x O
x
2
6
24
4 x3
2 x4
5
Out[2]= 1 2 x 2 x2 O
x
3
3
Out[3]= 2 x O x
Mathematica keeps track of the orders of power series in much the same way as it keeps track of
the precision of approximate real numbers. Just as with numerical calculations, there are operations
on power series which can increase, or decrease, the precision (or order) of your results.
Here is a power series accurate to
order x .
In[5]:= 1 / (1 - %)
x2
x4
x6
x8
x10
11
Out[4]= 1 O
x
2
24 720 40320 3628800
1
x2
x4
x6
2
7
O
x
Out[5]=
2
6 120 3024 86400
x
x3
2 x5
17 x7
62 x9
11
Out[6]= x O
x
3
15
315
2835
Here is its derivative with respect to x.
In[7]:= D[%, x]
2 x4
17 x6
62 x8
10
Out[7]= 1 x2 O
x
3
45
315
Integrating with respect to x gives back
the original power series.
In[8]:= Integrate[%, x]
x3
2 x5
17 x7
62 x9
11
Out[8]= x O
x
3
15
315
2835
When you perform an operation that involves both a normal expression and a power series,
Mathematica absorbs the normal expression into the power series whenever possible.
The 1 is automatically absorbed into
the power series.
x2
x3
x4
5
Out[9]= 2 x O
x
2
6
24
In[10]:= % + x^2
In[11]:= % + Sin[x]
In[12]:= (a + x) %^2
887
3 x2
x3
x4
5
Out[10]= 2 x O
x
2
6
24
3 x2
x4
5
Out[11]= 2 2 x O
x
2
24
Out[12]= 4 a 4 8 a x 8 10 a x2
29 a
5
10 6 a x3 6 x4 O
x
12
Mathematica knows how to apply a wide variety of functions to power series. However, if you
apply an arbitrary function to a power series, it is impossible for Mathematica to give you anything
but a symbolic result.
Mathematica does not know how to
apply the function f to a power series,
so it just leaves the symbolic result.
x2
x3
4
Out[13]= f1 x O
x
2
6
x3
x4
x5
x2
6
Out[1]= 1 x O
x
2
6
24 120
x2
x4
x5
6
Out[2]= 1 x O
x
2
8
15
x2
x4
x5
6
Out[3]= 1 x O
x
2
8
15
888
If you have a power series for a function fy, then it is often possible to get a power series
approximation to the solution for y in the equation fy x. This power series effectively gives the
inverse function f x such that ff x x. The operation of finding the power series for an inverse
function is sometimes known as reversion of power series.
Here is the series for siny.
y3
y5
6
Out[4]= y O
y
6
120
Inverting the series gives the series for
sin x.
In[5]:= InverseSeries[%, x]
x3
3 x5
6
Out[5]= x O
x
6
40
Out[6]= y O y
As discussed above, power series in Mathematica are represented in a special internal form, which
keeps track of such attributes as their expansion order.
For some purposes, you may want to convert power series to normal expressions. From a mathematical point of view, this corresponds to truncating the power series, and assuming that all higher-order
terms are zero.
This generates a power series, with
four terms.
In[2]:= t^2
In[3]:= Normal[%]
In[4]:= Factor[%]
x3
x5
x7
9
Out[1]= x O
x
3
5
7
2 x4
23 x6
44 x8
10
Out[2]= x2 O
x
3
45
105
2 x4
23 x6
44 x8
Out[3]= x2
3
45
105
1
Out[4]= x2 315 210 x2 161 x4 132 x6
315
SeriesCoefficient[series, n]
889
In[5]:= SeriesCoefficient[t, 7]
1
Out[5]=
7
Out[1]= 1 a 1 x a 2 x2 a 3 x3 O x
a 2 4 a 2 6 a 1 a 3 x2 O x x
In[3]:= LogicalExpand[ % ]
2
a
2 4 a
2 6 a
1 a
3 0
This solves the equations for the
coefficients a[i]. You can also feed
equations involving power series
directly to Solve.
In[4]:= Solve[ % ]
1
1
Out[4]= a
3 , a
1 1, a
2
,
12
2
a
3 0, a
1 1, a
2 0
Some equations involving power series can also be solved using the InverseSeries function discussed
on page 888.
890
Evaluating sums.
Out[1]= x
x
1
Out[3]= x4 x Erf
2
2
There are many analogies between sums and integrals. And just as it is possible to have indefinite
integrals, so indefinite sums can be set up by using symbolic variables as upper limits.
This is effectively an indefinite sum.
1
Out[5]= n 1 n
2
This sum comes out in terms of
incomplete gamma functions.
x 1 n Gamma
1 n, x
Out[6]=
Gamma
2 n
1
4
Out[7]= PolyGamma
3, 2 n
90 6
1
Out[8]=
4
1 n
Mathematica can do essentially all sums that are found in books of tables. Just as with indefinite
integrals, indefinite sums of expressions involving simple functions tend to give answers that involve
more complicated functions. Definite sums, like definite integrals, often, however, come out in terms
of simpler functions.
891
3
Out[9]=
5
1n
9
"
$
$
# 4
3
3
Gamma n Hypergeometric2F11, n,
2
2
4 %
' > Gamma
2 n
2 n, '
9 &
The definite form is much simpler.
3
Out[10]=
5
Here is a slightly more complicated
definite sum.
1
Out[11]= EulerGamma 2 6 Zeta
3
6
If you represent the nth term in a sequence as a[n], you can use a recurrence equation to specify how
it is related to other terms in the sequence.
RSolve takes recurrence equations and solves them to get explicit formulas for a[n].
This solves a simple recurrence
equation.
RSolve[eqn, a[n], n]
1 rn
Out[3]= a
n
1 r
1 rn
Out[4]= a
n
1 r
This gives an algebraic solution to the
Fibonacci recurrence equation.
5 1 5
892
RSolve can be thought of as a discrete analog of DSolve. Many of the same functions generated in
solving differential equations also appear in finding symbolic solutions to recurrence equations.
This generates a gamma function,
which generalizes the factorial.
RSolve does not require you to specify explicit values for terms such as a[1]. Like DSolve, it
automatically introduces undetermined constants C[i] to give a general solution.
This gives a general solution with one
undetermined constant.
RSolve can solve equations that do not depend only linearly on a[n]. For nonlinear equations,
however, there are sometimes several distinct solutions that must be given. Just as for differential
equations, it is a difficult matter to find symbolic solutions to recurrence equations, and standard
mathematical functions only cover a limited set of cases.
Here is the general solution to a
nonlinear recurrence equation.
Out[9]=
Out[10]=
15 C
1 Sinn ArcTan 15
a
n C
2 Cosn ArcTan
2
!,
15 C
1 Sinn ArcTan 15
!!
RSolve can solve not only ordinary difference equations in which the arguments of a differ by integers, but also q-difference equations in which the arguments of a are related by multiplicative factors.
This solves the q-difference analog of
the factorial equation.
Log
q
a
n n 2 1
C
1!!
1
Out[11]=
Log n
Log
n
Log
n
Out[12]= a
n C
1 Cos C
2 Sin
3 Log
q
3 Log
q
893
1
n
2n
2n
Out[13]= a
n 4 3 1 1 2 1 n,
4
1
n
2n
2n
b
n 4 3 1 1 2 1 n
Just as one can set up partial differential equations that involve functions of several variables, so one
can also set up partial recurrence equations that involve multidimensional sequences. Just as in the
differential equations case, general solutions to partial recurrence equations can involve undetermined
functions.
This gives the general solution to a
simple partial recurrence equation.
Gamma
i Gamma
j C
1
i j
Out[14]= a
i, j
Gamma 1 i j
Limit[expr, x -> x ]
Finding limits.
894
Out[4]= 0
Out[5]= 2
In[6]:= Sign[0]
Out[6]= 0
Not all functions have definite limits at particular points. For example, the function sinx oscillates infinitely often near x , so it has no definite limit there. Nevertheless, at least so long as x
remains real, the values of the function near x always lie between and 1. Limit represents values with bounded variation using Interval objects. In general, Interval[{xmin, xmax}] represents
an uncertain value which lies somewhere in the interval xmin to xmax.
Limit returns an Interval object,
representing the range of possible
values of sinx near its essential
singularity at x .
In[9]:= (1 + %)^3
1
Out[10]= Interval ,
Some functions may have different limits at particular points, depending on the direction from
which you approach those points. You can use the Direction option for Limit to specify the
direction you want.
3.6.10 Residues
895
75
50
25
-1
-0.5
0.5
-25
-50
-75
-100
Out[12]=
Out[13]=
Limit makes no assumptions about functions like f[x] about which it does not have definite
knowledge. As a result, Limit remains unevaluated in most cases involving symbolic functions.
Limit has no definite knowledge about
f, so it leaves this limit unevaluated.
3.6.10 Residues
Limit[expr, x -> x ] tells you what the value of expr is when x tends to x . When this value is
infinite, it is often useful instead to know the residue of expr when x equals x . The residue is given
by the coefficient of x x in the power series expansion of expr about the point x .
Residue[expr, {x, x }]
Computing residues.
896
IdentityMatrix[n] produces an n n
identity matrix.
In[4]:= IdentityMatrix[3]
This makes a
matrix with two
non-zero values filled in.
In[6]:= MatrixForm[%]
%
"0 0 0 0'
$
$
'
0 0 a 0'
Out[6]//MatrixForm= $
'
$
'
$
'
$
0
b
0
0
&
#
897
a zero matrix
a matrix with random numerical entries
a lower-triangular matrix
a zero matrix
an n n identity matrix
a lower-triangular matrix
f
1, 1
0
0
%
"
'
$
'
'
$
f
2,
1
f
2,
2
0
Out[8]//MatrixForm= $
'
$
'
$
'
$
# f
3, 1 f
3, 2 f
3, 3 &
898
m[[i, j]]
m[[i]]
m[[All, i]]
Tr[m, List]
,
ArrayRules[m]
Matrices in Mathematica are represented as lists of lists. You can use all the standard Mathematica
list-manipulation operations on matrices.
Here is a sample
matrix.
In[2]:= t[[2]]
899
Here is a matrix.
900
VectorQ[expr]
MatrixQ[expr]
Dimensions[expr]
Out[2]= False
This is a matrix.
In[2]:= VectorQ[ x + y ]
Out[3]= 2, 3
Out[4]= 3
Out[5]= False
Out[3]= 1, 2 x, 3 x2
901
In[6]:= 1 + {a, b}
In[7]:= {a, b} + c
In[8]:= k {a, b}
Out[6]= 1 a, 1 b
Out[7]= a c, b c
Out[8]= a k, b k
It is important to realize that Mathematica treats an object as a vector in a particular operation only
if the object is explicitly a list at the time when the operation is done. If the object is not explicitly a
list, Mathematica always treats it as a scalar. This means that you can get different results, depending
on whether you assign a particular object to be a list before or after you do a particular operation.
The object p is treated as a scalar, and
added separately to each element in
the vector.
In[9]:= {a, b} + p
Out[9]= a p, b p
Out[11]= a c, b d
Cross[v, v]
Outer[Times, t, u]
In[1]:= k {a, b, c}
Out[1]= a k, b k, c k
902
Out[2]= a ap b bp c cp
Out[3]= a x b y, c x d y
It is important to realize that you can use dot for both left- and right-multiplication of vectors by
matrices. Mathematica makes no distinction between row and column vectors. Dot carries out
whatever operation is possible. (In formal terms, a.b contracts the last index of the tensor a with the
first index of b.)
Here are definitions for a matrix m and
a vector v.
In[6]:= m . v
In[7]:= v . m
In[8]:= v . m . v
Out[5]= x, y
Out[6]= a x b y, c x d y
Out[7]= a x c y, b x d y
Out[8]= x a x c y y b x d y
For some purposes, you may need to represent vectors and matrices symbolically, without explicitly
giving their elements. You can use dot to represent multiplication of such symbolic objects.
Dot effectively acts here as a
non-commutative form of
multiplication.
In[9]:= a . b . a
In[10]:= (a . b) . (a . b)
Out[9]= a.b.a
Out[10]= a.b.a.b
In[11]:= (a + b) . c . (d + e)
In[12]:= Distribute[ % ]
Out[11]= a b.c.d e
The dot operator gives inner products of vectors, matrices, and so on. In more advanced
calculations, you may also need to construct outer or Kronecker products of vectors and matrices. You
can use the general function Outer to do this.
903
Matrix inversion.
In[2]:= Inverse[ m ]
In[3]:= % . m
In[4]:= Together[ % ]
d
b
c
a
Out[2]= ,
, ,
b c a d
b c a d
b c a d b c a d
bc
ad
Out[3]= , 0
,
b c a d b c a d
bc
ad
0,
b c a d b c a d
Out[4]= 1, 0, 0, 1
1
Out[5]= ,
2
1
,
4
1
,
3
1
,
5
1
,
4
1
,
6
In[6]:= Inverse[hb]
In[7]:= % . hb
1
1
, ,
5
3
1
1
, ,
7
5
1
,
4
1
,
6
1
,
5
1
,
7
1
,
6
1
904
If you give a matrix with exact symbolic or numerical entries, Mathematica gives the exact inverse. If,
on the other hand, some of the entries in your matrix are approximate real numbers, then Mathematica
finds an approximate numerical result.
Here is a matrix containing
approximate real numbers.
In[10]:= Inverse[ % ]
In[11]:= % . m
In[12]:= Chop[ % ]
Out[11]=
When you try to invert a matrix with exact numerical entries, Mathematica can always tell whether
or not the matrix is singular. When you invert an approximate numerical matrix, Mathematica can
usually not tell for certain whether or not the matrix is singular: all it can tell is for example that the
determinant is small compared to the entries of the matrix. When Mathematica suspects that you are
trying to invert a singular numerical matrix, it prints a warning.
Mathematica prints a warning if you
invert a numerical matrix that it
suspects is singular.
If you work with high-precision approximate numbers, Mathematica will keep track of the precision
of matrix inverses that you generate.
This generates a numerical matrix
with entries of 20-digit precision.
Out[15]=
1.000000000000000000, 0. 1019 ,
0. 1019 , 0. 1020 , 0. 1020 , 0. 1020 !
905
Inverse works only on square matrices. Section 3.7.10 discusses the function PseudoInverse ,
which can also be used with non-square matrices.
Transpose[m]
Inverse[m]
Det[m]
Minors[m]
Minors[m, k]
Tr[m]
,
CharacteristicPolynomial[m, x]
transpose
matrix inverse
determinant
matrix of minors
kth minors
trace
characteristic polynomial
Transposing a matrix interchanges the rows and columns in the matrix. If you transpose an m n
matrix, you get an n m matrix as the result.
Transposing a
matrix gives a
result.
Det[m] gives the determinant of a square matrix m. Minors[m] is the matrix whose i jth element
gives the determinant of the submatrix obtained by deleting the n i th row and the n j th
column of m. The i jth cofactor of m is ij times the n i n j th element of the matrix of
minors.
Minors[m, k] gives the determinants of the k k submatrices obtained by picking each possible set
of k rows and k columns from m. Note that you can apply Minors to rectangular, as well as square,
matrices.
Here is the determinant of a simple
matrix.
906
In[4]:= Det[ m ]
Out[4]= a
1, 3 a
2, 2 a
3, 1 a
1, 2 a
2, 3 a
3, 1
a
1, 3 a
2, 1 a
3, 2 a
1, 1 a
2, 3 a
3, 2
a
1, 2 a
2, 1 a
3, 3 a
1, 1 a
2, 2 a
3, 3
The trace or spur of a matrix Tr[m] is the sum of the terms on the leading diagonal.
This finds the trace of a simple
matrix.
MatrixPower[m, n]
MatrixExp[m]
Here is a matrix.
In[7]:= MatrixPower[m, 3]
Out[7]= 0.465625, 0.534375, 0.467578, 0.532422
In[8]:= m . m . m
In[10]:= MatrixExp[m]
Out[10]= 1.7392, 0.979085, 0.8567, 1.86158
907
Many calculations involve solving systems of linear equations. In many cases, you will find it convenient to write down the equations explicitly, and then solve them using Solve.
In some cases, however, you may prefer to convert the system of linear equations into a matrix
equation, and then apply matrix manipulation operations to solve it. This approach is often useful
when the system of equations arises as part of a general algorithm, and you do not know in advance
how many variables will be involved.
A system of linear equations can be stated in matrix form as m x b, where x is the vector of
variables.
Note that if your system of equations is sparse, so that most of the entries in the matrix m are zero,
then it is best to represent the matrix as a SparseArray object. As discussed on page 922, you can
convert from symbolic equations to SparseArray objects using CoefficientArrays . All the functions
described in this section work on SparseArray objects as well as ordinary matrices.
LinearSolve[m, b]
NullSpace[m]
,
MatrixRank[m]
RowReduce[m]
Here is a matrix.
1
1
Out[3]= x a 5 b, y 2 a b
9
9
1
1
Out[4]= a 5 b, 2 a b
9
9
908
a 5b 2a b
Out[5]= ,
9
9
9
9
1
1
Out[6]= 1, 0, a 5 b
, 0, 1, 2 a b
9
9
If you have a square matrix m with a non-zero determinant, then you can always find a unique
solution to the matrix equation m x b for any b. If, however, the matrix m has determinant zero,
then there may be either no vector, or an infinite number of vectors x which satisfy m x b for a
particular b. This occurs when the linear equations embodied in m are not independent.
When m has determinant zero, it is nevertheless always possible to find non-zero vectors x that
satisfy m x 0. The set of vectors x satisfying this equation form the null space or kernel of the matrix
m. Any of these vectors can be expressed as a linear combination of a particular set of basis vectors,
which can be obtained using NullSpace[m] .
Here is a simple matrix, corresponding
to two identical linear equations.
In[8]:= Det[ m ]
Out[8]= 0
In[10]:= NullSpace[ m ]
In[11]:= m . %[[1]]
In[12]:= MatrixRank[ m ]
Out[11]= 0, 0
Out[12]= 1
NullSpace and MatrixRank have to determine whether particular combinations of matrix elements
are zero. For approximate numerical matrices, the Tolerance option can be used to specify how
close to zero is considered good enough. For exact symbolic matrices, you may sometimes need to
specify something like ZeroTest->(FullSimplify[#]==0&) to force more to be done to test whether
symbolic expressions are zero.
Here is a simple symbolic matrix with
determinant zero.
909
In[14]:= NullSpace[m]
c
b
Out[14]= , 0, 1
, , 1, 0
a
a
Out[15]= 0, 0, 0
An important feature of functions like LinearSolve and NullSpace is that they work with rectangular, as well as square, matrices.
When you represent a system of linear equations by a matrix equation of the form m x b, the
number of columns in m gives the number of variables, and the number of rows gives the number of
equations. There are a number of cases.
Underdetermined
Overdetermined
Nonsingular
Consistent
Inconsistent
In[19]:= NullSpace[m]
2 1
Out[18]= , , 0
5 5
910
In[20]:= m . (v + 4 %[[1]])
Out[20]= 1, 1
The number of independent equations is the rank of the matrix MatrixRank[m] . The number of
redundant equations is Length[NullSpace[m]] . Note that the sum of these quantities is always equal
to the number of columns in m.
LinearSolve[m]
In some applications, you will want to solve equations of the form m x b many times with the
same m, but different b. You can do this efficiently in Mathematica by using LinearSolve[m] to create
a single LinearSolveFunction that you can apply to as many vectors as you want.
This creates a LinearSolveFunction .
13 3
Out[22]= ,
5
5
You get the same result by giving the
vector as an explicit argument to
LinearSolve .
13 3
Out[23]= ,
5
5
51
19
Out[24]= ,
5
5
Eigenvalues[m]
Eigenvectors[m]
Eigensystem[m]
Eigenvalues[ N[m] ], etc.
Eigenvalues[ N[m, p] ], etc.
,
CharacteristicPolynomial[m, x]
911
The eigenvalues of a matrix m are the values i for which one can find non-zero vectors vi such that
m vi i vi . The eigenvectors are the vectors vi .
The characteristic polynomial CharacteristicPolynomial[m, x] for an n n matrix is given by
Det[m - x IdentityMatrix[n]] . The eigenvalues are the roots of this polynomial.
Finding the eigenvalues of an n n matrix in general involves solving an nth -degree polynomial
equation. For n ! , therefore, the results cannot in general be expressed purely in terms of explicit
radicals. Root objects can nevertheless always be used, although except for fairly sparse or otherwise
simple matrices the expressions obtained are often unmanageably complex.
Even for a matrix as simple as this, the
explicit form of the eigenvalues is quite
complicated.
1
1
Out[1]= 3 a a2 4 b2 , 3 a a2 4 b2
2
2
If you give a matrix of approximate real numbers, Mathematica will find the approximate numerical
eigenvalues and eigenvectors.
Here is a numerical matrix.
In[3]:= Eigenvalues[ m ]
In[4]:= Eigenvectors[ m ]
matrix. For non-symmetric
matrices, the eigenvalues can have
imaginary parts.
Out[6]= True
The function Eigenvalues always gives you a list of n eigenvalues for an n n matrix. The eigenvalues correspond to the roots of the characteristic polynomial for the matrix, and may not necessarily
be distinct. Eigenvectors , on the other hand, gives a list of eigenvectors which are guaranteed to
be independent. If the number of such eigenvectors is less than n, then Eigenvectors appends zero
vectors to the list it returns, so that the total length of the list is always n.
Here is a
matrix.
912
In[9]:= Eigenvalues[mz]
In[10]:= Eigenvectors[mz]
Out[9]= 0, 0, 0
Eigenvalues[m, k]
Eigenvectors[m, k]
Eigenvalues[m, -k]
Eigenvectors[m, -k]
Eigenvalues sorts numeric eigenvalues so that the ones with large absolute value come first. In
many situations, you may be interested only in the largest or smallest eigenvalues of a matrix. You
can get these efficiently using Eigenvalues[m, k] and Eigenvalues[m, -k].
This computes the exact eigenvalues of
an integer matrix.
In[12]:= N[%]
Eigenvalues[{m, a}]
Eigenvectors[{m, a}]
1
1
Out[11]= 5 33 , 5 33
2
2
CharacteristicPolynomial[{m, a}, x]
the generalized characteristic polynomial of m
The generalized eigenvalues for a matrix m with respect to a matrix a are defined to be those i for
which m vi i a vi .
913
SingularValueList[m]
SingularValueList[m, k]
SingularValueList[{m, a}]
Norm[m, p]
The singular values of a matrix m are the square roots of the eigenvalues of m m , where denotes
Hermitian transpose. The number of such singular values is the smaller dimension of the matrix.
SingularValueList sorts the singular values from largest to smallest. Very small singular values are
usually numerically meaningless. With the option setting Tolerance -> t, SingularValueList drops
singular values that are less than a fraction t of the largest singular value. For approximate numerical
matrices, the tolerance is by default slightly greater than zero.
If you multiply the vector for each point in a unit sphere in n-dimensional space by an m n matrix
m, then you get an m-dimensional ellipsoid, whose principal axes have lengths given by the singular
values of m.
The 2-norm of a matrix Norm[m, 2] is the largest principal axis of the ellipsoid, equal to the largest
singular value of the matrix. This is also the maximum 2-norm length of m v for any possible unit
vector v.
The p-norm of a matrix Norm[m, p] is in general the maximum p-norm length of m v that can be
attained. The cases most often considered are p , p and p . Also sometimes considered is
the Frobenius norm, whose square is the trace of m m .
914
LUDecomposition[m]
,
CholeskyDecomposition[m]
the LU decomposition
the Cholesky decomposition
When you create a LinearSolveFunction using LinearSolve[m] , this often works by decomposing the matrix m into triangular forms, and sometimes it is useful to be able to get such forms
explicitly.
LU decomposition effectively factors any square matrix into a product of lower- and upper-triangular
matrices. Cholesky decomposition effectively factors any Hermitian positive-definite matrix into a product of a lower-triangular matrix and its Hermitian conjugate, which can be viewed as the analog of
finding a square root of a matrix.
PseudoInverse[m]
QRDecomposition[m]
,
SingularValueDecomposition[m]
SingularValueDecomposition[{m, a}]
the pseudoinverse
the QR decomposition
the singular value decomposition
the generalized singular value decomposition
The standard definition for the inverse of a matrix fails if the matrix is not square or is singular.
The pseudoinverse m of a matrix m can however still be defined. It is set up to minimize the
sum of the squares of all entries in m m I, where I is the identity matrix. The pseudoinverse is
sometimes known as the generalized inverse, or the Moore-Penrose inverse. It is particularly used in
doing problems related to least-squares fitting.
QR decomposition writes any matrix m as a product q r, where q is an orthonormal matrix, denotes
Hermitian transpose, and r is a triangular matrix, in which all entries below the leading diagonal are
zero.
Singular value decomposition, or SVD, is an underlying element in many numerical matrix algorithms.
The basic idea is to write any matrix m in the form usv , where s is a matrix with the singular values
of m on its diagonal, u and v are orthonormal matrices, and v is the Hermitian transpose of v.
915
JordanDecomposition[m]
SchurDecomposition[m]
SchurDecomposition[{m, a}]
Most matrices can be reduced to a diagonal matrix of eigenvalues by applying a matrix of their
eigenvectors as a similarity transformation. But even when there are not enough eigenvectors to do
this, one can still reduce a matrix to a Jordan form in which there are both eigenvalues and Jordan
blocks on the diagonal. Jordan decomposition in general writes any matrix in the form as sjs .
Numerically more stable is the Schur decomposition, which writes any matrix m in the form qtq ,
where q is an orthonormal matrix, and t is block upper triangular.
rank 0
scalar
rank 1
vector
rank 2
matrix
rank k
rank k tensor
A tensor of rank k is essentially a k-dimensional table of values. To be a true rank k tensor, it must
be possible to arrange the elements in the table in a k-dimensional cuboidal array. There can be no
holes or protrusions in the cuboid.
The indices that specify a particular element in the tensor correspond to the coordinates in the
cuboid. The dimensions of the tensor correspond to the side lengths of the cuboid.
One simple way that a rank k tensor can arise is in giving a table of values for a function of
k variables. In physics, the tensors that occur typically have indices which run over the possible
directions in space or spacetime. Notice, however, that there is no built-in notion of covariant and
contravariant tensor indices in Mathematica: you have to set these up explicitly using metric tensors.
916
ArrayQ[t, n]
Dimensions[t]
ArrayDepth[t]
MatrixForm[t]
Here is a tensor.
In[3]:= MatrixForm[ t ]
In[4]:= Dimensions[ t ]
Out[2]= 2, 3, 3, 5, 4, 7, 3, 4, 4, 6, 5, 8
2
3
4
"
$
'
%
$
$
'
5
3
7 '
$
'
$
'
'
Out[3]//MatrixForm= $
$
'
$
'
$
'
5
3
4
$
$
'
$ '
'
6
8
4
#
&
Out[4]= 2, 3, 2
Out[5]= 2
In[6]:= ArrayDepth[ t ]
Out[6]= 3
The rank of a tensor is equal to the number of indices needed to specify each element. You can
pick out subtensors by using a smaller number of indices.
Transpose[t]
Transpose[t, {p , p , ... }]
Tr[t, f]
Outer[f, t , t ]
t . t
Inner[f, t , t , g]
917
You can think of a rank k tensor as having k slots into which you insert indices. Applying
Transpose is effectively a way of reordering these slots. If you think of the elements of a tensor
as forming a k-dimensional cuboid, you can view Transpose as effectively rotating (and possibly
reflecting) the cuboid.
In the most general case, Transpose allows you to specify an arbitrary reordering to apply to the
indices of a tensor. The function Transpose[T, {p , p , ... , pk }], gives you a new tensor T$ such
that the value of T$ i i ik is given by Tip ip ip .
k
If you originally had an np np npk tensor, then by applying Transpose , you will get an
n n nk tensor.
Here is a matrix that you can also
think of as a
tensor.
In[8]:= mt = Transpose[m]
Out[10]= a
1,
a
1,
a
1,
a
2,
a
2,
a
2,
1,
2,
3,
1,
2,
3,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
a
1,
a
1,
a
1,
a
2,
a
2,
a
2,
1,
2,
3,
1,
2,
3,
1,
1,
1,
1,
1,
1,
2,
2,
2,
2,
2,
2
918
Out[11]= a
1,
a
2,
a
1,
a
2,
a
1,
a
2,
1,
1,
2,
2,
3,
3,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
a
1,
a
2,
a
1,
a
2,
a
1,
a
2,
1,
1,
2,
2,
3,
3,
1,
1,
1,
1,
1,
1,
2,
2,
2,
2,
2,
2
Out[12]= 3, 2, 1, 2
If you have a tensor that contains lists of the same length at different levels, then you can use
Transpose to effectively collapse different levels.
This collapses all three levels, giving a
list of the elements on the main
diagonal.
Out[15]= a 1, 1, 1 a 2, 2, 2 a 3, 3, 3
Outer products, and their generalizations, are a way of building higher-rank tensors from lower-rank
ones. Outer products are also sometimes known as direct, tensor or Kronecker products.
From a structural point of view, the tensor you get from Outer[f, t, u] has a copy of the structure
of u inserted at the position of each element in t. The elements in the resulting structure are obtained
by combining elements of t and u using the function f.
This gives the outer f of two vectors.
The result is a matrix.
919
In[21]:= Dimensions[ % ]
a,
a,
a,
a,
f
m11,
f
m12,
f
m21,
f
m22,
b,
b,
b,
b,
f
m11,
f
m12,
f
m21,
f
m22,
c,
c,
c,
c
Out[21]= 2, 2, 3
In[23]:= Inner[f, {{1, 2}, {3, 4}}, {{a, b}, {c, d}}, g]
Here is a tensor.
Out[24]= 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
Here is a tensor.
In[26]:= a . b
Out[26]= 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4
920
In[27]:= Dimensions[ % ]
Out[27]= 3, 2, 3, 1
You can think of Inner as performing a contraction of the last index of one tensor with the first
index of another. If you want to perform contractions across other pairs of indices, you can do so by
first transposing the appropriate indices into the first or last position, then applying Inner, and then
transposing the result back.
In many applications of tensors, you need to insert signs to implement antisymmetry. The function
Signature[{i , i , ... }], which gives the signature of a permutation, is often useful for this purpose.
Outer[f, t , t , ... ]
Outer[f, t , t , ... , n]
Outer[f, t , t , ... , n , n , ... ]
Inner[f, t , t , g]
Inner[f, t , t , g, n]
,
,
921
SparseArray[list]
Normal[array]
As discussed in Section 2.4.5, you can use patterns to specify collections of elements in sparse
arrays. You can also have sparse arrays that correspond to tensors of any rank.
This makes a sparse numerical
matrix, with 148 non-zero elements.
In[2]:= ListDensityPlot[-m]
50
40
30
20
10
0
0
10
20
In[3]:= Eigenvalues[m, 4]
In[4]:= m . m
30
40
50
You can apply most standard structural operations directly to SparseArray objects, just as you
would to ordinary lists. When the results are sparse, they typically return SparseArray objects.
922
Dimensions[m]
ArrayRules[m]
m[[i, j]]
element i, j
m[[i]]
m[[All, j]]
m[[i, j]] = v
In[9]:= ArrayRules[m[[2]]]
,
,
SparseArray[rules]
923
In[13]:= Normal[%]
Out[14]= c x z, x 2 y z
In[15]:= s = CoefficientArrays[
{c + x^2 - z == 0, x^2 + 2 y + z^2 == 0},
{x, y, z}]
Out[15]= SparseArray
?1>, 2, SparseArray
?2>, 2, 3,
SparseArray
?3>, 2, 3, 3
In[16]:= Normal[%]
Out[17]= c x2 z, x2 2 y z2
For machine-precision numerical sparse matrices, Mathematica supports standard file formats such
as Matrix Market (.mtx) and Harwell-Boeing. You can import and export matrices in these formats
using Import and Export.
924
Mean[list]
Median[list]
Max[list]
Variance[list]
StandardDeviation[list]
Quantile[list, q]
Total[list]
mean (average)
median (central value)
maximum value
variance
standard deviation
qth quantile
total
varx.
If the elements in list are thought of as being selected at random according to some probability
distribution, then the mean gives an estimate of where the center of the distribution is located, while
the standard deviation gives an estimate of how wide the dispersion in the distribution is.
The median Median[list] effectively gives the value at the halfway point in the sorted list Sort[list].
It is often considered a more robust measure of the center of a distribution than the mean, since it
depends less on outlying values.
The qth quantile Quantile[list, q] effectively gives the value that is q of the way through the
sorted list Sort[list].
For a list of length n, Mathematica defines Quantile[list, q] to be Sort[list][[Ceiling[n q]]].
There are, however, about ten other definitions of quantile in use, all potentially giving slightly
different results. Mathematica covers the common cases by introducing four quantile parameters in the
form Quantile[list, q, {{a, b}, {c, d}}]. The parameters a and b in effect define where in the list
should be considered a fraction q of the way through. If this corresponds to an integer position, then
the element at that position is taken to be the qth quantile. If it is not an integer position, then a linear
combination of the elements on either side is used, as specified by c and d.
925
The position in a sorted list s for the qth quantile is taken to be k a n b q. If k is an integer,
then the quantile is sk . Otherwise, it is s$k% s&k' s$k% c dk $k%, with the indices taken to be or
n if they are out of range.
median-based estimate
Whenever d , the value of the qth quantile is always equal to some actual element in list, so that
the result changes discontinuously as q varies. For d , the qth quantile interpolates linearly between
successive elements in list. Median is defined to use such an interpolation.
Note that Quantile[list, q] yields quartiles when q m
and percentiles when q m.
,
,
Mean[{x , x , ... }]
Sometimes each item in your data may involve a list of values. The basic statistics functions in
Mathematica automatically apply to all corresponding elements in these lists.
This separately finds the mean of each
column of data.
1
1
Out[1]= x1 x2 x3, y1 y2 y3
3
3
Note that you can extract the elements in the ith column of a multidimensional list using
list[[All, i]].
926
The standard set of packages distributed with Mathematica includes several for doing more sophisticated statistical analyses, as mentioned on page 109.
In[2]:= gp = ListPlot[ fp ]
70
60
50
40
30
20
10
5
10
15
20
927
60
50
40
30
20
10
10
15
20
10
15
20
60
40
20
70
60
50
40
30
20
10
5
10
15
20
928
70
60
50
40
30
20
10
5
10
15
20
{f , f , ... }
If you give data in the form {f , f , ... } then Fit will assume that the successive fi correspond
to values of a function at successive integer points 1, 2, ... . But you can also give Fit data that
corresponds to the values of a function at arbitrary points, in one or more dimensions.
929
Fit takes a list of functions, and uses a definite and efficient procedure to find what linear combination of these functions gives the best least-squares fit to your data. Sometimes, however, you may
want to find a nonlinear fit that does not just consist of a linear combination of specified functions.
You can do this using FindFit , which takes a function of any form, and then searches for values of
parameters that yield the best fit to your data.
Out[11]=
By default, both Fit and FindFit produce least-squares fits, which are defined to minimize the
quantity i /ri / , where the ri are residuals giving the difference between each original data point
and its fitted value. One can, however, also consider fits based on other norms. If you set the option
NormFunction -> u, then FindFit will attempt to find the fit that minimizes the quantity u[r], where
r is the list of residuals. The default is NormFunction -> Norm, corresponding to a least-squares fit.
This uses the -norm, which
minimizes the maximum distance
between the fit and the data. The
result is slightly different from
least-squares.
FindFit works by searching for values of parameters that yield the best fit. Sometimes you may
have to tell it where to start in doing this search. You can do this by giving parameters in the form
{{a, a }, {b, b }, ... }. FindFit also has various options that you can set to control how it does its
search.
930
option name
default value
NormFunction
Norm
AccuracyGoal
Automatic
PrecisionGoal
Automatic
WorkingPrecision
MachinePrecision
MaxIterations
100
StepMonitor
None
EvaluationMonitor
None
Method
Automatic
method to use
Interpolation[{f , f , ... }]
931
In[3]:= sin[0.25]
In[4]:= sin[0.3]
In[5]:= Sin[0.3]
Out[3]= 0.247404
Out[4]= 0.2955
Out[5]= 0.29552
You can work with approximate functions much as you would with any other Mathematica functions. You can plot approximate functions, or perform numerical operations such as integration or
root finding.
If you give a non-numerical argument,
the approximate function is left in
symbolic form.
In[6]:= sin[x]
Out[7]= 0.78531
Out[8]= 0.785398
932
1
0.8
0.6
0.4
0.2
0.5
1.5
If you differentiate an approximate function, Mathematica will return another approximate function
that represents the derivative.
This finds the derivative of the
approximate sine function, and
evaluates it at .
In[10]:= sin'[Pi/6]
In[11]:= N[Cos[Pi/6]]
Out[10]= 0.865372
Out[11]= 0.866025
InterpolatingFunction objects contain all the information Mathematica needs about approximate
functions. In standard Mathematica output format, however, only the part that gives the domain of
the InterpolatingFunction object is printed explicitly. The lists of actual parameters used in the
InterpolatingFunction object are shown only in iconic form.
In standard output format, the only
part of an InterpolatingFunction
object printed explicitly is its domain.
In[12]:= sin
In[13]:= sin[3]
InterpolatingFunction::dmval:
Input value {3} lies outside the range of data in the
interpolating function. Extrapolation will be used.
Out[13]= 0.0155471
The more information you give about the function you are trying to approximate, the better the
approximation Mathematica constructs can be. You can, for example, specify not only values of the
function at a sequence of points, but also derivatives.
933
Interpolation works by fitting polynomial curves between the points you specify. You can use
the option InterpolationOrder to specify the degree of these polynomial curves. The default setting
is InterpolationOrder -> 3, yielding cubic curves.
This makes a table of values of the
cosine function.
0.5
-0.5
-1
0.5
-0.5
-1
Increasing the setting for InterpolationOrder typically leads to smoother approximate functions.
However, if you increase the setting too much, spurious wiggles may develop.
934
In[18]:= ListInterpolation[
Table[1.5/(x^2 + y^3), {x, 10}, {y, 15}]]
Out[18]= InterpolatingFunction
1., 10., 1., 15., ?>
Out[19]= 0.00360759
ListInterpolation works for arrays of any dimension, and in each case it produces an
InterpolatingFunction object which takes the appropriate number of arguments.
This interpolates a three-dimensional
array.
In[22]:= ListInterpolation[
Array[#1^2 + #2^2 - #3^2 &, {10, 10, 10}]] ;
Mathematica can handle not only purely numerical approximate functions, but also ones which
involve symbolic parameters.
This generates an
InterpolatingFunction that depends
on the parameters a and b.
935
In working with approximate functions, you can quite often end up with complicated combinations of InterpolatingFunction objects. You can always tell Mathematica to produce a single
InterpolatingFunction object valid over a particular domain by using FunctionInterpolation .
This generates a new
InterpolatingFunction object valid in
the domain 0 to 1.
Fourier[{u , u , ... , un }]
InverseFourier[{v , v , ... , vn }]
Fourier transform
inverse Fourier transform
Fourier transforms.
In[2]:= Fourier[%]
Out[2]= 0. 0. ,
0. 0. ,
0. 0. ,
0. 0. ,
0.707107 1.70711 ,
0.707107 0.292893 ,
0.707107 0.292893 ,
0.707107 1.70711
936
In[3]:= InverseFourier[%]
Out[3]= 1., 1., 1., 1., 1., 1., 1., 1.
1.5
1
0.5
50
100
150
200
-0.5
-1
100
150
200
n
n
In different scientific and technical fields different conventions are often used for defining discrete
Fourier transforms. The option FourierParameters in Mathematica allows you to choose any of these
conventions you want.
937
common convention
setting
Mathematica default
{0, 1}
n
data analysis
{-1, 1}
n
n
s vs eirsn
n
n
s vs eirsn
signal processing
{1, -1}
n
general case
{a, b}
na
na
Mathematica can find Fourier transforms for data in any number of dimensions. In n dimensions,
the data is specified by a list nested n levels deep. Two-dimensional Fourier transforms are often used
in image processing.
ListConvolve[kernel, list]
ListCorrelate[kernel, list]
Out[1]= b x a y, c x b y, d x c y, e x d y
Out[2]= a x b y, b x c y, c x d y, d x e y
938
Out[3]= b x a y, c x b y, d x c y, e x d y
Out[4]= a b, b c, c d, d e
In forming sublists to combine with a kernel, there is always an issue of what to do at the ends
of the list of data. By default, ListConvolve and ListCorrelate never form sublists which would
overhang the ends of the list of data. This means that the output you get is normally shorter than
the original list of data.
With an input list of length 6, the
output is in this case of length 4.
In practice one often wants to get output that is as long as the original list of data. To do this
requires including sublists that overhang one or both ends of the list of data. The additional elements
needed to form these sublists must be filled in with some kind of padding. By default, Mathematica
takes copies of the original list to provide the padding, thus effectively treating the list as being cyclic.
ListCorrelate[kernel, list]
ListCorrelate[kernel, list, 1]
ListCorrelate[kernel, list, -1]
Out[7]= a x b y, b x c y, c x d y, d x a y
Out[8]= d x a y, a x b y, b x c y, c x d y, d x a y
In the general case ListCorrelate[kernel, list, {kL , kR }] is set up so that in the first element of
the result, the first element of list appears multiplied by the element at position kL in kernel, and in
the last element of the result, the last element of list appears multiplied by the element at position
939
kR in kernel. The default case in which no overhang is allowed on either side thus corresponds to
ListCorrelate[kernel, list, {1, -1}].
With a kernel of length 3, alignments
{-1, 2} always make the first and last
elements of the result the same.
For many kinds of data, it is convenient to assume not that the data is cyclic, but rather that it is
padded at either end by some fixed element, often 0, or by some sequence of elements.
include no padding
Different choices of kernel allow ListConvolve and ListCorrelate to be used for different kinds
of computations.
This finds a moving average of data.
a d e
Out[13]= ,
3 3 3
b c d
,
3 3 3
a
3
c
3
b
3
d
3
e
,
3
e
,
3
a
3
a
3
b
3
d
3
c
,
3
e a b e
,
3 3 3 3
940
In[16]:= ListPlot[data];
0.6
0.4
0.2
20
60
40
80
100
-0.2
In[18]:= ListPlot[%]
4
3
2
1
20
40
60
80
-1
You can use ListConvolve and ListCorrelate to handle symbolic as well as numerical data.
This forms the convolution of two
symbolic lists.
Out[19]= a u, b u a v, c u b v a w, c v b w, c w
Out[20]= a u b u x a v x c u x2
b v x2 a w x2 c v x3 b w x3 c w x4
941
In[23]:= ListConvolve[{{1,1,1},{1,-8,1},{1,1,1}}, g] ;
942
Cellular automata provide a convenient way to represent many kinds of systems in which the values
of cells in an array are updated in discrete steps according to a local rule.
CellularAutomaton[rnum, init, t]
{a , a , ... }
{{a , a , ... }, b}
{{a , a , ... }, blist}
{{{a , a , ... }, {d }}, ... }, blist
If you give an explicit list of initial values, CellularAutomaton will take the elements in this list
to correspond to all the cells in the system, arranged cyclically.
943
It is often convenient to set up initial conditions in which there is a small seed region, superimposed on a constant background. By default, CellularAutomaton automatically fills in enough
background to cover the size of the pattern that can be produced in the number of steps of evolution
you specify.
This shows rule 30 evolving from an
initial condition containing a single
black cell.
Particularly in studying interactions between structures, you may sometimes want to specify initial
conditions for cellular automata in which certain blocks are placed at particular offsets.
This sets up an initial condition with
black cells at offsets M
.
In[7]:= CAPlot[CellularAutomaton[30,
{{{ {1}, {-40} }, {{1}, {40}}}, 0}, 100]]
944
{n, k}
k = 2, r = 1, elementary rule
general nearest-neighbor rule with k colors
{n, k, r}
In the simplest cases, a cellular automaton allows k possible values or colors for each cell, and
has rules that involve up to r neighbors on each side. The digits of the rule number n then specify
what the color of a new cell should be for each possible configuration of the neighborhood.
This evolves a single neighborhood for
1 step.
In[9]:= Table[IntegerDigits[i,2,3],{i,7,0,-1}]
In[11]:= FromDigits[%, 2]
Out[10]= 0, 0, 0, 1, 1, 1, 1, 0
Out[11]= 30
945
For a general cellular automaton rule, each digit of the rule number specifies what color a different
possible neighborhood of r cells should yield. To find out which digit corresponds to which
neighborhood, one effectively treats the cells in a neighborhood as digits in a number. For an r
cellular automaton, the number is obtained from the list of elements neig in the neighborhood by
neig . {k^2, k, 1}.
It is sometimes convenient to consider totalistic cellular automata, in which the new value of a
cell depends only on the total of the values in its neighborhood. One can specify totalistic cellular
automata by rule numbers or codes in which each digit refers to neighborhoods with a given total
value, obtained for example from neig . {1, 1, 1}.
In general, CellularAutomaton allows one to specify rules using any sequence of weights. Another
choice sometimes convenient is {k, 1, k}, which yields outer totalistic rules.
This runs the k
, r totalistic rule
with code number 867.
Rules with range r involve all cells with offsets r through r. Sometimes it is convenient to think
about rules that involve only cells with specific offsets. You can do this by replacing a single r with a
list of offsets.
Any k cellular automaton rule can be thought of as corresponding to a Boolean function. In the
simplest case, basic Boolean functions like And or Nor take two arguments. These are conveniently
specified in a cellular automaton rule as being at offsets {{0}, {1}}. Note that for compatibility
with handling higher-dimensional cellular automata, offsets must always be given in lists, even for
one-dimensional cellular automata.
This generates the truth table for
2-cell-neighborhood rule number 7,
which turns out to be the Boolean
function NAND.
Rule numbers provide a highly compact way to specify cellular automaton rules. But sometimes
it is more convenient to specify rules by giving an explicit function that should be applied to each
possible neighborhood.
946
In[15]:= CAPlot[CellularAutomaton[
{Mod[Apply[Plus, #], 4]&, {}, 1}, {{1}, 0}, 100]]
In[16]:= CAPlot[CellularAutomaton[
{Mod[Apply[Plus, #] + #2, 4]&, {}, 1}, {{1}, 0}, 100]]
In[17]:= CAPlot[CellularAutomaton[
{Mod[1/2 Apply[Plus, #], 1] &, {}, 1}, {{1}, 0}, 100]]
947
CellularAutomaton[rnum, init, t]
The step specification spect works very much like taking elements from a list with Take. One
difference, though, is that the initial condition for the cellular automaton is considered to be step 0.
Note that any step specification of the form { ... } must be enclosed in an additional list.
All
u
-u
{u}
{u , u }
{u , u , d}
948
CellularAutomaton[rnum, init, t]
Much as you can specify which steps to keep in a cellular automaton evolution, so also you can
specify which cells to keep. If you give an initial condition such as {a , a , ... }, blist, then ai is
taken to have offset 0 for the purpose of specifying which cells to keep.
All
Automatic
-x
{x}
{-x}
{x , x }
{x , x , dx}
949
If you give an initial condition such as {{a , a , ... }, blist}, then CellularAutomaton will always
effectively do the cellular automaton as if there were an infinite number of cells. By using a specx such
as {x , x } you can tell CellularAutomaton to include only cells at specific offsets x through x in
its output. CellularAutomaton by default includes cells out just far enough that their values never
simply stay the same as in the background blist.
In general, given a cellular automaton rule with range r, cells out to distance r t on each side
could in principle be affected in the evolution of the system. With specx being All, all these cells are
included; with the default setting of Automatic , cells whose values effectively stay the same as in blist
are trimmed off.
By default, only the parts that are not
constant black are kept.
950
{n, {k, {{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}}, {1, 1}}
two-dimensional 5-neighbor totalistic rule
{n, {k, {{0, k, 0}, {k, 1, k}, {0, k, 0}}}, {1, 1}}
two-dimensional 5-neighbor outer totalistic rule
{n + k^5 (k - 1), {k, {{0, 1, 0}, {1, 4 k + 1, 1}, {0, 1, 0}}}, {1, 1}}
two-dimensional 5-neighbor growth rule
Higher-dimensional rule specifications.
In[29]:= CAPlot[Map[First,
CellularAutomaton[code797, {{{1}}, 0}, 70,
{All, {0}, All}]]]
951
1
0
In[2]:= N[%]
Out[2]= 0.430606
When Mathematica cannot find an explicit result for something like a definite integral, it returns a
symbolic form. You can take this symbolic form, and try to get an approximate numerical value by
applying N.
By giving a second argument to N, you
can specify the numerical precision to
use.
If you want to evaluate an integral numerically in Mathematica, then using Integrate and applying
N to the result is not the most efficient way to do it. It is better instead to use the function NIntegrate ,
which immediately gives a numerical answer, without first trying to get an exact, symbolic, result.
You should realize that even when Integrate does not in the end manage to give you an exact result,
it may spend a lot of time trying to do so.
NIntegrate evaluates numerical
integrals directly, without first trying to
get a symbolic result.
Integrate
NIntegrate
definite integrals
Sum
NSum
sums
Product
NProduct
products
Solve
NSolve
DSolve
NDSolve
Maximize
NMaximize
maximization
952
1
0.8
0.6
0.4
0.2
-10
-5
10
953
Although NIntegrate follows the principle of looking only at the numerical values of your integrand, it nevertheless tries to make the best possible use of the information that it can get. Thus, for
example, if NIntegrate notices that the estimated error in the integral in a particular region is large,
it will take more samples in that region. In this way, NIntegrate tries to adapt its operation to the
particular integrand you have given.
The kind of adaptive procedure that NIntegrate uses is similar, at least in spirit, to what Plot does
in trying to draw smooth curves for functions. In both cases, Mathematica tries to go on taking more
samples in a particular region until it has effectively found a smooth approximation to the function in
that region.
The kinds of problems that can appear in numerical integration can also arise in doing other
numerical operations on functions.
For example, if you ask for a numerical approximation to the sum of an infinite series, Mathematica
samples a certain number of terms in the series, and then does an extrapolation to estimate the
contributions of other terms. If you insert large terms far out in the series, they may not be detected
when the extrapolation is done, and the result you get for the sum may be incorrect.
A similar problem arises when you try to find a numerical approximation to the minimum of a
function. Mathematica samples only a finite number of values, then effectively assumes that the actual
function interpolates smoothly between these values. If in fact the function has a sharp dip in a
particular region, then Mathematica may miss this dip, and you may get the wrong answer for the
minimum.
If you work only with numerical values of functions, there is simply no way to avoid the kinds of
problems we have been discussing. Exact symbolic computation, of course, allows you to get around
these problems.
In many calculations, it is therefore worthwhile to go as far as you can symbolically, and then resort
to numerical methods only at the very end. This gives you the best chance of avoiding the problems
that can arise in purely numerical computations.
954
Out[1]= 0.89298
Out[2]= 2.66667
An important feature of NIntegrate is its ability to deal with functions that blow up at known
points. NIntegrate automatically checks for such problems at the end points of the integration region.
The function x blows up at x ,
but NIntegrate still succeeds in getting
the correct value for the integral.
Out[3]= 2.
Out[4]= 2
NIntegrate::slwcon:
Numerical integration converging too slowly; suspect
one of the following: singularity, value of the
integration being 0, oscillatory integrand, or
insufficient WorkingPrecision. If your integrand is
oscillatory try using the option Method->Oscillatory
in NIntegrate.
NIntegrate::ncvb:
NIntegrate failed to converge to prescribed accuracy
after 7 recursive bisections in x near x =
-57
4.36999 10
.
Out[5]= 23953.1
955
NIntegrate does not automatically look for singularities except at the end points of your integration region. When other singularities are present, NIntegrate may not give you the right answer
for the integral. Nevertheless, in following its adaptive procedure, NIntegrate will often detect the
presence of potentially singular behavior, and will warn you about it.
NIntegrate does not handle the
singularity in /x/ in the middle of
the integration region. However, it
warns you of a possible problem. In
this case, the final result is numerically
quite close to the correct answer.
Out[6]= 4.79343
If you know that your integrand has singularities at particular points, you can explicitly tell
NIntegrate to deal with them. NIntegrate[expr, {x, xmin, x , x , ... , xmax}] integrates expr
from xmin to xmax, looking for possible singularities at each of the intermediate points xi .
This again gives the integral
Out[7]= 4.82843
You can also use the list of intermediate points xi in NIntegrate to specify an integration contour
to follow in the complex plane. The contour is taken to consist of a sequence of line segments, starting
at xmin, going through each of the xi , and ending at xmax.
This integrates x around a closed
contour in the complex plane, going
from , through the points i, 1 and
i, then back to .
The integral gives i, as expected
from Cauchys Theorem.
In[9]:= N[ 2 Pi I ]
Out[9]= 0. 6.28319
956
option name
default value
MinRecursion
MaxRecursion
SingularityDepth
MaxPoints
Automatic
When NIntegrate tries to evaluate a numerical integral, it samples the integrand at a sequence
of points. If it finds that the integrand changes rapidly in a particular region, then it recursively
takes more sample points in that region. The parameters MinRecursion and MaxRecursion specify
the minimum and maximum number of levels of recursive subdivision to use. Increasing the value of
MinRecursion guarantees that NIntegrate will use a larger number of sample points. MaxRecursion
limits the number of sample points which NIntegrate will ever try to use. Increasing MinRecursion
or MaxRecursion will make NIntegrate work more slowly. SingularityDepth specifies how many
levels of recursive subdivision NIntegrate should try before it concludes that the integrand is blowing up at one of the endpoints, and does a change of variables.
With the default settings for all
options, NIntegrate misses the peak in
expx near x , and gives the
wrong answer for the integral.
Out[11]= 0.99187
957
Out[12]= 1.77245
Out[13]= 1.77245
For integrals in many dimensions, it can take a long time for NIntegrate to get a precise answer.
However, by setting the option MaxPoints , you can tell NIntegrate to give you just a rough estimate,
sampling the integrand only a limited number of times.
This gives an estimate of the volume of
the unit sphere in three dimensions.
Out[1]= 0.64703
1
Out[2]=
i3 i9
i=1
958
In[3]:= N[%]
Out[3]= 0.64703
The way NSum works is to include a certain number of terms explicitly, and then to try and estimate
the contribution of the remaining ones. There are two approaches to estimating this contribution. The
first uses the Euler-Maclaurin method, and is based on approximating the sum by an integral. The
second method, known as the Wynn epsilon method, samples a number of additional terms in the
sum, and then tries to fit them to a polynomial multiplied by a decaying exponential.
option name
default value
Method
Automatic
NSumTerms
15
NSumExtraTerms
12
If you do not explicitly specify the method to use, NSum will try to choose between the methods
it knows. In any case, some implicit assumptions about the functions you are summing have to be
made. If these assumptions are not correct, you may get inaccurate answers.
The most common place to use NSum is in evaluating sums with infinite limits. You can, however,
also use it for sums with finite limits. By making implicit assumptions about the objects you are
evaluating, NSum can often avoid doing as many function evaluations as an explicit Sum computation
would require.
This finds the numerical value of
n by extrapolation techniques.
n e
Out[4]= 1.58198
Out[5]= 1.58198
NProduct works in essentially the same way as NSum, with analogous options.
959
In[1]:= Solve[x^5 + 7x + 1 == 0, x]
Out[1]=
x Root1 7 #1 #15
x Root1 7 #1 #15
x Root1 7 #1 #15
x Root1 7 #1 #15
x Root1 7 #1 #15
In[2]:= N[%]
NSolve[poly==0, x]
NSolve[poly==0, x, n]
&,
&,
&,
&,
&,
1!,
2!,
3!,
4!,
5!!
NSolve will always give you the complete set of numerical solutions to any polynomial equation in
one variable.
You can also get numerical solutions to sets of simultaneous polynomial equations. You can use
Solve to unwind the simultaneous equations, and then apply N to get numerical results.
960
In[5]:= First[
Solve[{x^2 + y^2 == 1, x^3 + y^3 == 2}, {x, y}]]
1
Out[5]= x Root3 3 #12 4 #13 3 #14 2 #16 &, 1
3
3 6 Root3 3 #12 4 #13 3 #14 2 #16 &, 1
2
In[6]:= N[%]
Out[6]= x 1.09791 0.839887 , y 1.09791 0.839887
NSolve gives you a general way to find numerical approximations to the solutions of polynomial
equations. Finding numerical solutions to more general equations, however, can be much more difficult, as discussed in Section 3.4.2. FindRoot gives you a way to search for a numerical solution to an
arbitrary equation, or set of equations.
FindRoot[lhs==rhs, {x, x }]
-
0.5
-1
-0.5
0.5
-0.5
-1
961
In trying to find a solution to your equation, FindRoot starts at the point you specify, and then
progressively tries to get closer and closer to a solution. Even if your equations have several solutions,
FindRoot always returns the first solution it finds. Which solution this is will depend on what starting
point you chose. If you start sufficiently close to a particular solution, FindRoot will usually return
that solution.
The equation sinx has an infinite
number of solutions of the form
x n. If you start sufficiently close to
a particular solution, FindRoot will
give you that solution.
Out[3]= x 3.14159
Out[4]= x 6.28319
Out[6]=
The variables used by FindRoot can have values that are lists. This allows you to find roots of
functions that take vectors as arguments.
This is a way to solve a linear equation
for the variable x.
In[8]:= FindRoot[{{1, 2}, {3, 4}} . x == {5, 6}, {x, {1, 1}}]
962
functions yi , but all of these functions must depend on a single independent variable x, which is
the same for each function. Partial differential equations involve two or more independent variables.
NDSolve can also handle differential-algebraic equations that mix differential equations with algebraic
ones.
When you use NDSolve, the initial or boundary conditions you give must be sufficient to determine
the solutions for the yi completely. When you use DSolve to find symbolic solutions to differential
equations, you can get away with specifying fewer initial conditions. The reason is that DSolve
automatically inserts arbitrary constants C[i] to represent degrees of freedom associated with initial
conditions that you have not specified explicitly. Since NDSolve must give a numerical solution, it
cannot represent these kinds of additional degrees of freedom. As a result, you must explicitly give
all the initial or boundary conditions that are needed to determine the solution.
963
In a typical case, if you have differential equations with up to nth derivatives, then you need to
give initial conditions for up to n th derivatives, or give boundary conditions at n points.
With a third-order equation, you need
to give initial conditions for up to
second derivatives.
In[4]:= NDSolve[
{ y'''[x] + 8 y''[x] + 17 y'[x] + 10 y[x] == 0,
y[0] == 6, y'[0] == -20, y''[0] == 84},
y, {x, 0, 1} ]
Out[4]= y InterpolatingFunction
0., 1., ?>
6
5
4
3
2
1
0.2
0.4
0.6
0.8
In[6]:= NDSolve[
{ y'''[x] + Sin[x] == 0,
y[0] == 4, y[1] == 7, y[2] == 0 }, y, {x, 0, 2}]
Out[6]= y InterpolatingFunction
0., 2., ?>
In most cases, all the initial conditions you give must involve the same value of x, say x . As a
result, you can avoid giving both xmin and xmax explicitly. If you specify your range of x as {x, x },
then Mathematica will automatically generate a solution over the range x to x .
This generates a solution over the
range 0 to 2.
You can give initial conditions as equations of any kind. In some cases, these equations may have
multiple solutions. In such cases, NDSolve will correspondingly generate multiple solutions.
The initial conditions in this case lead
to multiple solutions.
1.,
1.,
1.,
1.,
?>
x,
?>
x,
?>
x,
?>
x
964
4
2
0.2
0.4
0.6
0.8
-2
-4
1
0.75
0.5
0.25
2
10
-0.25
-0.5
1
0.75
0.5
0.25
-0.4
-0.2
-0.25
-0.5
0.2
0.4
0.6
0.8
965
Out[14]= y
2
x y
1
x y
2
x,
<
y
3
x y
2
x y
3
x,
<
<
y
4
x y
3
x y
4
x, y
1
x y
1
x,
<
y
5
x y
4
x, y
1
0 1, y
2
0 0,
y
3
0 0, y
4
0 0, y
5
0 0
10.,
10.,
10.,
10.,
10.,
?>,
?>,
?>,
?>,
?>
10
NDSolve can handle functions whose values are lists or arrays. If you give initial conditions like
y[0] == {v , v , ... , vn }], then NDSolve will assume that y is a function whose values are lists of
length n.
This solves a system of four coupled
differential equations.
966
6
4
2
2
-2
-4
-6
option name
default value
MaxSteps
Automatic
StartingStepSize
Automatic
MaxStepSize
Infinity
NormFunction
Automatic
NDSolve has many methods for solving equations, but essentially all of them at some level work
by taking a sequence of steps in the independent variable x, and using an adaptive procedure to
determine the size of these steps. In general, if the solution appears to be varying rapidly in a
particular region, then NDSolve will reduce the step size or change the method so as to be able to
track the solution better.
This solves a differential equation in
which the derivative has a
discontinuity.
In[19]:= NDSolve[
{y'[x] == If[x < 0, 1/(x-1), 1/(x+1)],
y[-5] == 5},
y, {x, -5, 5}]
Out[19]= y InterpolatingFunction
5., 5., ?>
967
5
4.75
4.5
4.25
-4
-2
3.75
3.5
3.25
Through its adaptive procedure, NDSolve is able to solve stiff differential equations in which
there are several components which vary with x at very different rates.
In these equations, y varies much more
rapidly than z.
0.2
0.4
0.6
0.8
NDSolve follows the general procedure of reducing step size until it tracks solutions accurately.
There is a problem, however, when the true solution has a singularity. In this case, NDSolve might go
on reducing the step size forever, and never terminate. To avoid this problem, the option MaxSteps
specifies the maximum number of steps that NDSolve will ever take in attempting to find a solution.
For ordinary differential equations the default setting is MaxSteps -> 10000.
968
Out[23]=
y
x InterpolatingFunction
1., 1.00413 10172 !!, ?>
x!!
-1
-0.8
-0.6
-0.4
-0.2
-50
-100
-150
-200
-250
The default setting for MaxSteps should be sufficient for most equations with smooth solutions.
When solutions have a complicated structure, however, you may occasionally have to choose larger
settings for MaxSteps . With the setting MaxSteps -> Infinity there is no upper limit on the number
of steps used.
To take the solution to the Lorenz
equations this far, you need to remove
the default bound on MaxSteps .
969
40
30
20
10
0
-10
-5
10
When NDSolve solves a particular set of differential equations, it always tries to choose a step size
appropriate for those equations. In some cases, the very first step that NDSolve makes may be too
large, and it may miss an important feature in the solution. To avoid this problem, you can explicitly
set the option StartingStepSize to specify the size to use for the first step.
The equations you give to NDSolve do not necessarily all have to involve derivatives; they can also
just be algebraic. You can use NDSolve to solve many such differential-algebraic equations.
This solves a system of
differential-algebraic equations.
970
1
0.75
0.5
0.25
1
-0.25
-0.5
NDSolve[{eqn , eqn , ... }, u, {t, tmin, tmax}, {x, xmin, xmax}, ... ]
solve a system of partial differential equations for u
NDSolve[{eqn , eqn , ... }, {u , u , ... }, {t, tmin, tmax}, {x, xmin, xmax}, ... ]
solve a system of partial differential equations for several
functions ui
Finding numerical solutions to partial differential equations.
1
0.75
5
0.5
0.25
0
0
2.5
0
2
-2.5
4
-5
6
971
In[31]:= NDSolve[
{D[u[t, x], t, t] ==
D[u[t, x], x, x] + (1 - u[t, x]^2)(1 + 2u[t, x]),
u[0, x] == Exp[-x^2], Derivative[1, 0][u][0, x] == 0,
u[t, -10] == u[t, 10]}, u, {t, 0, 10}, {x, -10, 10}]
Out[31]= u InterpolatingFunction
0., 10., ..., 10., 10., ..., ?>
10
1
0
-1
0
0
2
4
-5
6
8
10 -10
0
-10
-5
10
972
In[36]:= Show[GraphicsArray[
Partition[
Table[ Plot3D[Evaluate[u[t, x, y] /. First[%]],
{x, -5, 5}, {y, -5, 5}, PlotRange -> All,
PlotPoints -> 100, Mesh -> False,
DisplayFunction -> Identity], {t, 1, 4}], 2]]]
1
0.9
0.8
0.7
0.6
-4
4
2
-2
0
-2
0
2
4
-4
0
-2
0
4
0
4
-2
-4
0
-2
2
2
-2
4
2
-4
0.4
0.2
-4
1.4
1.3
1.2
-4
0.75
0.5
0.25
0
4
2
-4
-2
0
-2
0
2
4
-4
973
FindMinimum[f, {x, x }]
-
Out[2]= 0.885603
Like FindRoot, FindMinimum and FindMaximum work by starting from a point, then progressively
searching for a minimum or maximum. But since they return a result as soon as they find anything,
they may give only a local minimum or maximum of your function, not a global one.
This curve has two local minima.
-3
-2
-1
-2
974
NMinimize[f, x]
NMaximize[f, x]
NMinimize and NMaximize are numerical analogs of Minimize and Maximize. But unlike Minimize
and Maximize they usually cannot guarantee to find absolute global minima and maxima. Nevertheless, they typically work well when the function f is fairly smooth, and has a limited number of local
minima and maxima.
1
2
Out[9]= 5 , x
, y
5
5
In[11]:= N[%]
Out[11]= 0.617273, x 0.447214, y 0.894427
975
If both the objective function f and the constraints cons are linear in all variables, then minimization
and maximization correspond to a linear programming problem. Sometimes it is convenient to state such
problems not in terms of explicit equations, but instead in terms of matrices and vectors.
LinearProgramming[c, m, b]
,
LinearProgramming[c, m, b, l]
In[12]:= Minimize[{2x + 3y, x + 5y >= 10, x - y >= 2, x >= 1}, {x, y}]
32
10
4
Out[12]= , x , y
3
3
3
10 4
Out[13]= ,
3
3
You can specify a mixture of equality and inequality constraints by making the list b be a sequence
of pairs {bi , si }. If si is 1, then the ith constraint is mi . x bi . If si is 0 then it is mi . x == bi , and if
si is -1 then it is mi . x bi .
This makes the first inequality use *.
In LinearProgramming[c, m, b, l], you can make l be a list of pairs {{l , u }, {l , u }, ... }
representing lower and upper bounds on the xi .
In doing large linear programming problems, it is often convenient to give the matrix m as a
SparseArray object.
Out[1]= 0.430606
Out[2]= 0.430606103120690604912377
976
When you give a setting for WorkingPrecision , this typically defines an upper limit on the precision of the results from a computation. But within this constraint you can tell Mathematica how
much precision and accuracy you want it to try to get. You should realize that for many kinds of
numerical operations, increasing precision and accuracy goals by only a few digits can greatly increase
the computation time required. Nevertheless, there are many cases where it is important to ensure
that high precision and accuracy are obtained.
WorkingPrecision
PrecisionGoal
AccuracyGoal
Out[4]= 0.430606103120690604912377355248
Giving a particular setting for WorkingPrecision , each of the functions for numerical operations
in Mathematica uses certain default settings for PrecisionGoal and AccuracyGoal . Typical is the case
of NDSolve , in which these default settings are equal to half the setting given for WorkingPrecision .
The precision and accuracy goals normally apply both to the final results returned, and to various
norms or error estimates for them. Functions for numerical operations in Mathematica typically try to
refine their results until either the specified precision goal or accuracy goal is reached. If the setting
for either of these goals is Infinity, then only the other goal is considered.
In doing ordinary numerical evaluation with N[expr, n], Mathematica automatically adjusts its internal computations to achieve n-digit precision in the result. But in doing numerical operations on
functions, it is in practice usually necessary to specify WorkingPrecision and PrecisionGoal more
explicitly.
977
Functions in Mathematica are carefully set up so that you normally do not have to know how they
work inside. But particularly for numerical functions that use iterative algorithms, it is sometimes
useful to be able to monitor the internal progress of these algorithms.
StepMonitor
EvaluationMonitor
Note the importance of using option :> expr rather than option -> expr. You need a delayed rule :>
to make expr be evaluated each time it is used, rather than just when the rule is given.
Reap and Sow provide a convenient
way to make a list of the steps taken.
To take a successful step towards an answer, iterative numerical algorithms sometimes have to
do several evaluations of the functions they have been given. Sometimes this is because each step
requires, say, estimating a derivative from differences between function values, and sometimes it is
because several attempts are needed to achieve a successful step.
This shows the successful steps taken
in reaching the answer.
978
200
300
400
-0.1
-0.2
-0.3
There are often several different methods known for doing particular types of numerical computations. Typically Mathematica supports most generally successful ones that have been discussed in the
literature, as well as many that have not. For any specific problem, it goes to considerable effort to
pick the best method automatically. But if you have sophisticated knowledge of a problem, or are
studying numerical methods for their own sake, you may find it useful to tell Mathematica explicitly
what method it should use. The Reference Guide lists some of the methods built into Mathematica;
others are discussed in Section A.9.4 or in advanced or online documentation.
This solves a differential equation using
method m, and returns the number of
steps and evaluations needed.
In[8]:= try[Automatic]
Out[8]= 1118, 2329
979
The action of FractionalPart[2 x] is particularly simple in terms of the binary digits of the
number x: it justs drops the first one, and shifts the remaining ones to the left. After several steps,
this means that the results one gets are inevitably sensitive to digits that are far to the right, and have
an extremely small effect on the original value of x.
This shows the shifting process
achieved by FractionalPart[2 x] in
the first 8 binary digits of x.
0,
0,
1,
1,
1,
0,
1,
1,
1,
0,
1,
1,
1,
0,
0,
1,
1,
0,
0,
0,
1,
0,
0,
1,
1,
0,
0,
1,
0,
1,
0,
1,
0,
0,
1,
0,
0,
0,
0,
0
If you give input only to a particular precision, you are effectively specifying only a certain number
of digits. And once all these digits have been excavated you can no longer get accurate results, since
to do so would require knowing more digits of your original input. So long as you use arbitraryprecision numbers, Mathematica automatically keeps track of this kind of degradation in precision,
indicating a number with no remaining significant digits by 0. 10e, as discussed on page 734.
980
In[5]:= Map[Precision, %]
Out[4]=
0.11111111111111111111, 0.4444444444444444444,
0.77777777777777778, 0.1111111111111111,
0.44444444444444, 0.777777777778, 0.11111111111,
0.444444444, 0.77777778, 0.111111, 0.4444,
0.778, 0.1, 0. 101 , 0. 101 , 0. 103 ,
0. 104 , 0. 106 , 0. 107 , 0. 109 , 0. 1011 !
1 4 7 1 4 7 1 4 7 1 4
Out[6]= , , , , , , , , , ,
9 9 9 9 9 9 9 9 9 9 9
It is important to realize that if you use approximate numbers of any kind, then in an example
like the one above you will always eventually run out of precision. But so long as you use arbitraryprecision numbers, Mathematica will explicitly show you any decrease in precision that is occurring.
However, if you use machine-precision numbers, then Mathematica will not keep track of precision,
and you cannot tell when your results become meaningless.
If you use machine-precision numbers,
Mathematica will no longer keep track
of any degradation in precision.
0.444444,
0.777778,
0.496185,
0.757813,
0.777778, 0.111111,
0.111111, 0.444445, 0.77781,
0.847383, 0.89534, 0.813599,
0.3125, 0.5, 0., 0., 0.
By iterating the operation FractionalPart[2 x] you extract successive binary digits in whatever
number you start with. And if these digits are apparently randomas in a number like then the
results will be correspondingly random. But if the digits have a simple patternas in any rational
numberthen the results you get will be correspondingly simple.
By iterating an operation such as FractionalPart[3/2 x] it turns out however to be possible to
get seemingly random sequences even from very simple input. This is an example of a very general
phenomenon first identified by me in the mid-1980s, which has nothing directly to do with sensitive
dependence on input.
This generates a seemingly random
sequence, even starting from simple
input.
In[9]:= N[%]
1 3 1
Out[8]= 1, , , ,
2 4 8
651
1953
, ,
1024 2048
3
9
27
81
243 217
, , , , , ,
16 32 64 128 256 512
1763 5289 15867 14833
, , ,
981
Many kinds of iterative procedures yield functions that depend sensitively on their input. Such
functions also arise when one looks at solutions to differential equations. In effect, varying the independent parameter in the differential equation is a continuous analog of going from one step to the
next in an iterative procedure.
This finds a solution to the Duffing
equation with initial condition 1.
1.5
1
0.5
10
20
30
40
50
-0.5
-1
-1.5
1.5
1
0.5
10
-0.5
-1
20
30
40
50
982
In a Mathematica notebook, you can use special characters just like you use standard keyboard
characters. You can include special characters both in ordinary text and in input that you intend to
give to Mathematica.
Some special characters are set up to have an immediate meaning to Mathematica. Thus, for example, is taken to be the symbol Pi. Similarly, ! is taken to be the operator >=, while is equivalent
to the function Union.
983
In[1]:= 3
or \[Union] is immediately
interpreted as the Union function.
? or \[SquareUnion] has no
immediate meaning to Mathematica.
Out[1]= True
Out[2]= a, b, c, d, e
Among ordinary characters such as E and i, some have an immediate meaning to Mathematica, but
most do not. And the same is true of special characters.
Thus, for example, while and have an immediate meaning to Mathematica, and do not.
This allows you to set up your own definitions for and .
has no immediate meaning in
Mathematica.
%&&&&&&&&&&
x2 1
In[5]:= x_ :
Characters such as and are treated by Mathematica as lettersjust like ordinary keyboard letters
like a or b.
But characters such as K and * are treated by Mathematica as operators. And although these particular characters are not assigned any built-in meaning by Mathematica, they are nevertheless required
to follow a definite syntax.
? is an infix operator.
In[8]:= x_ $ y_ := Join[x, y]
The details of how input you give to Mathematica is interpreted depends on whether you are
using StandardForm or TraditionalForm , and on what additional information you supply in
InterpretationBox and similar constructs.
But unless you explicitly override its built-in rules by giving your own definitions for
MakeExpression , Mathematica will always assign the same basic syntactic properties to any particular
special character.
984
These properties not only affect the interpretation of the special characters in Mathematica input, but
also determine the structure of expressions built with these special characters. They also affect various
aspects of formatting; operators, for example, have extra space left around them, while letters do not.
Letters
a, E, , l, , etc.
Letter-like forms
, Z, , , etc.
Operators
K, ", N, , etc.
In using special characters, it is important to make sure that you have the correct character for a
particular purpose. There are quite a few examples of characters that look similar, yet are in fact quite
different.
A common issue is operators whose forms are derived from letters. An example is or \[Sum],
which looks very similar to C or \[CapitalSigma] .
As is typical, however, the operator form is slightly less elaborate and more stylized than the
letter form C. In addition, is an extensible character which grows depending on the summand,
while C has a size determined only by the current font.
\[Product] , \[CapitalPi]
\[Angstrom] , \[CapitalARing]
\[Union] , keyboard U
\[EmptySet] , \[CapitalOSlash]
\[Element] , \[Epsilon]
m A
\[CapitalAlpha] , keyboard A
( d
\[DifferentialD] , keyboard d
C
B
\[Sum], \[CapitalSigma]
U
i
\[Micro] , \[Mu]
\[ImaginaryI] , keyboard i
In cases such as \[CapitalAlpha] versus A, both characters are letters. However, Mathematica treats
these characters as different, and in some fonts, for example, they may look quite different.
The result contains four distinct
characters.
985
The way Mathematica does this is to use a special character 7 or \[DifferentialD] as the differential
operator. This special character can be entered using the alias , dd ,.
Mathematica uses a special character for
the differential operator, so there is no
conflict with an ordinary d.
In[11]:= xd x
x1d
Out[11]=
1d
When letters and letter-like forms appear in Mathematica input, they are typically treated as names
of symbols. But when operators appear, functions must be constructed that correspond to these operators. In almost all cases, what Mathematica does is to create a function whose name is the full name
of the special character that appears as the operator.
Mathematica constructs a CirclePlus
function to correspond to the operator
O, whose full name is \[CirclePlus] .
In[12]:= a b c // FullForm
Out[12]//FullForm= CirclePlus a, b, c
Out[13]//FullForm= And a, b, c
Following the correspondence between operator names and function names, special characters such
as that represent built-in Mathematica functions have names that correspond to those functions.
Thus, for example, J is named \[Divide] to correspond to the built-in Mathematica function Divide,
and n is named \[Implies] to correspond to the built-in function Implies.
In general, however, special characters in Mathematica are given names that are as generic as possible, so as not to prejudice different uses. Most often, characters are thus named mainly according to
their appearance. The character K is therefore named \[CirclePlus] , rather than, say \[DirectSum] ,
and N is named \[TildeTilde] rather than, say, \[ApproximatelyEqual] .
b
\[Times] , \[Cross]
+
\[And], \[Wedge]
\[Backslash] , keyboard \
,
\[Or], \[Vee]
& .
\[CenterDot] , keyboard .
^
\[Star] , keyboard *
# #
\[Rule] , \[RightArrow]
n n
\[Implies] , \[DoubleRightArrow]
\[VerticalBar] , keyboard |
\[LongEqual] , keyboard =
\[VerticalSeparator] , keyboard |
\[Wedge] , keyboard ^
There are sometimes characters that look similar but which are used to represent different operators. An example is \[Times] and \[Cross]. \[Times] corresponds to the ordinary Times function
for multiplication; \[Cross] corresponds to the Cross function for vector cross products. The
for \[Cross] is drawn slightly smaller than b for Times, corresponding to usual careful usage in
mathematical typography.
986
In[16]:= {a " b, a ( b}
Out[15]= 15, 9, 3
Out[16]= a b, ab
In the example of \[And] and \[Wedge] , the \[And] operatorwhich happens to be drawn slightly
largercorresponds to the built-in Mathematica function And, while the \[Wedge] operator has a
generic name based on the appearance of the character and has no built-in meaning.
You can mix \[Wedge] and \[And]
operators. Each has a definite
precedence.
Some of the special characters commonly used as operators in mathematical notation look similar
to ordinary keyboard characters. Thus, for example, or \[Wedge] looks similar to the ^ character
on a standard keyboard.
Mathematica interprets a raw ^ as a power. But it interprets as a generic Wedge function. In cases
such as this where there is a special character that looks similar to an ordinary keyboard character,
the convention is to use the ordinary keyboard character as the alias for the special character. Thus,
for example, , ^ , is the alias for \[Wedge] .
The raw ^ is interpreted as a power,
but the , ^ , is a generic wedge
operator.
In[18]:= {x ^ y, x H ^ H y}
Out[18]= xy , x . y
A related convention is that when a special character is used to represent an operator that can
be typed using ordinary keyboard characters, those characters are used in the alias for the special
character. Thus, for example, , -> , is the alias for # or \[Rule], while , && , is the alias for + or
\[And].
, -> , is the alias for \[Rule], and , && ,
for \[And].
The most extreme case of characters that look alike but work differently occurs with vertical bars.
987
form
character name
alias
interpretation
x|y
keyboard |
xy
\[VerticalSeparator]
,|,
VerticalSeparator[x, y]
x3y
\[VerticalBar]
, | ,
VerticalBar[x, y]
@xA
\[LeftBracketingBar]
, l| ,
BracketingBar[x]
\[RightBracketingBar]
, r| ,
Alternatives[x, y]
Notice that the alias for \[VerticalBar] is , | ,, while the alias for the somewhat more common
\[VerticalSeparator] is , | ,. Mathematica often gives similar-looking characters similar aliases; it
is a general convention that the aliases for the less commonly used characters are distinguished by
having spaces at the beginning.
HnnnH
HnnnH
H.nnnH
H,nnnH
The notebook front end for Mathematica often allows you to set up your own aliases for special
characters. If you want to, you can overwrite the built-in aliases. But the convention is to use aliases
that begin with a dot or comma.
Note that whatever aliases you may use to enter special characters, the full names of the characters
will always be used when the characters are stored in files.
988
form
character name
alias
interpretation
\[Pi]
, p ,, , pi ,
equivalent to Pi
\[Infinity]
, inf ,
equivalent to Infinity
\[ExponentialE]
, ee ,
equivalent to E
\[ImaginaryI]
, ii ,
equivalent to I
\[ImaginaryJ]
, jj ,
equivalent to I
Symbols with built-in meanings whose names do not start with capital English letters.
Essentially all symbols with built-in meanings in Mathematica have names that start with capital
English letters. Among the exceptions are and , which correspond to E and I respectively.
Forms such as are used for both
input and output in StandardForm .
In OutputForm is output as E.
In[2]:= {, ^ (2 -), , ^ }
Out[2]= 1,
In[3]:= OutputForm[%]
Out[3]//OutputForm= {1, E
Pi
}
In written material, it is standard to use very short namesoften single lettersfor most of the
mathematical objects that one considers. But in Mathematica, it is usually better to use longer and
more explicit names.
In written material you can always explain that a particular single-letter name means one thing in
one place and another in another place. But in Mathematica, unless you use different contexts, a global
symbol with a particular name will always be assumed to mean the same thing.
As a result, it is typically better to use longer names, which are more likely to be unique, and
which describe more explicitly what they mean.
For variables to which no value will be assigned, or for local symbols, it is nevertheless convenient
and appropriate to use short, often single-letter, names.
It is sensible to give the global function
LagrangianL a long and explicit name.
The local variables can be given short
names.
In[4]:= LagrangianL_, _ 2 2
2
Out[4]= 2 2
989
form
input
interpretation
xn
Subscript[x, n]
x
SubPlus[x]
x
SubMinus[x]
x[
SubStar[x]
x
SuperPlus[x]
SuperMinus[x]
SuperStar[x]
SuperDagger[x]
x
x
OverBar[x]
OverVector[x]
OverTilde[x]
OverHat[x]
OverDot[x]
UnderBar[x]
StyleBox[x, FontWeight->"Bold"]
Note that with a notebook front end, you can typically change the style of text using menu items.
Internally the result will be to insert StyleBox objects, but you do not need to do this explicitly.
option
SingleLetterItalics
Automatic
990
form
full name
aliases
[Alpha]
[Beta]
[Gamma]
[Delta]
[Epsilon]
[CurlyEpsilon]
[Zeta]
[Eta]
[Theta]
[CurlyTheta]
[Iota]
[Kappa]
[CurlyKappa]
[Lambda]
[Mu]
[Nu]
[Xi]
[Omicron]
[Pi]
[CurlyPi]
[Rho]
[CurlyRho]
[Sigma]
[FinalSigma]
[Tau]
[Upsilon]
, a , , , alpha ,
, b , , , beta ,
, g , , , gamma ,
, d , , , delta ,
, e , , , epsilon ,
, ce , , , cepsilon ,
, z , , , zeta ,
, h , , , et , , , eta ,
, q , , , th , , , theta ,
, cq , , , cth , , , ctheta ,
, i , , , iota ,
, k , , , kappa ,
, ck , , , ckappa ,
, l , , , lambda ,
, m , , , mu ,
, n , , , nu ,
, x , , , xi ,
, om , , , omicron ,
, p , , , pi ,
, cp , , , cpi ,
, r , , , rho ,
, cr , , , crho ,
, s , , , sigma ,
, fs ,
, t , , , tau ,
, u , , , upsilon ,
[Phi]
[CurlyPhi]
[Chi]
[Psi]
[Omega]
[Digamma]
[Koppa]
[Stigma]
[Sampi]
, f , , , ph , , , phi ,
, j , , , cph , , , cphi ,
, c , , , ch , , , chi ,
, y , , , ps , , , psi ,
, o , , , w , , , omega ,
, di , , , digamma ,
, ko , , , koppa ,
, sti , , , stigma ,
, sa , , , sampi ,
form
full name
aliases
[CapitalAlpha]
[CapitalBeta]
[CapitalGamma]
[CapitalDelta]
[CapitalEpsilon]
,A,,
,B,,
,G,,
,D,,
,E,,
u
v
@
[CapitalZeta]
[CapitalEta]
[CapitalTheta]
, Z , , , Zeta ,
, H , , , Et , , , Eta ,
, Q , , , Th , , , Theta ,
w
x
[CapitalIota]
[CapitalKappa]
, I , , , Iota ,
, K , , , Kappa ,
A
y
z
l
{
B
[CapitalLambda]
[CapitalMu]
[CapitalNu]
[CapitalXi]
[CapitalOmicron]
[CapitalPi]
, L , , , Lambda ,
, M , , , Mu ,
, N , , , Nu ,
, X , , , Xi ,
, Om , , , Omicron ,
, P , , , Pi ,
[CapitalRho]
, R , , , Rho ,
[CapitalSigma]
, S , , , Sigma ,
}
D
~
E
[CapitalTau]
[CapitalUpsilon]
[CurlyCapitalUpsilon]
[CapitalPhi]
, T , , , Tau ,
, U , , , Upsilon ,
, cU , , , cUpsilon ,
, F , , , Ph , , , Phi ,
F
G
H
[CapitalChi]
[CapitalPsi]
[CapitalOmega]
[CapitalDigamma]
[CapitalKoppa]
[CapitalStigma]
[CapitalSampi]
, C , , , Ch , , , Chi ,
, Y , , , Ps , , , Psi ,
, O , , , W , , , Omega ,
, Di , , , Digamma ,
, Ko , , , Koppa ,
, Sti , , , Stigma ,
, Sa , , , Sampi ,
m
h
?
t
, Alpha ,
, Beta ,
, Gamma ,
, Delta ,
, Epsilon ,
991
You can use Greek letters as the names of symbols. The only Greek letter with a built-in meaning in
StandardForm is , which Mathematica takes to stand for the symbol Pi.
Note that even though on its own is assigned a built-in meaning, combinations such as or x
have no built-in meanings.
The Greek letters C and B look very much like the operators for sum and product. But as discussed
above, these operators are different characters, entered as \[Sum] and \[Product] respectively.
Similarly, is different from the U operator \[Element] , and is different from or \[Micro].
Some capital Greek letters such as \[CapitalAlpha] look essentially the same as capital English
letters. Mathematica however treats them as different characters, and in TraditionalForm it uses
\[CapitalBeta] , for example, to denote the built-in function Beta.
Following common convention, lower-case Greek letters are rendered slightly slanted in the standard
fonts provided with Mathematica, while capital Greek letters are unslanted.
Almost all Greek letters that do not look similar to English letters are widely used in science and
mathematics. The capital xi l is rare, though it is used to denote the cascade hyperon particles, the
grand canonical partition function and regular language complexity. The capital upsilon D is also
rare, though it is used to denote bb particles, as well as the vernal equinox.
Curly Greek letters are often assumed to have different meanings from their ordinary counterparts.
Indeed, in pure mathematics a single formula can sometimes contain both curly and ordinary forms
of a particular letter. The curly pi q is rare, except in astronomy.
The final sigma r is used for sigmas that appear at the ends of words in written Greek; it is not
commonly used in technical notation.
The digamma , koppa , stigma and sampi are archaic Greek letters. These letters provide a
convenient extension to the usual set of Greek letters. They are sometimes needed in making correspondences with English letters. The digamma corresponds to an English w, and koppa to an English
q. Digamma is occasionally used to denote the digamma function PolyGamma[x] .
992
form
full name
alias
form
full name
alias
[ScriptL]
, scl ,
[DoubleStruckCapitalC]
, dsC ,
[ScriptCapitalE]
, scE ,
[DoubleStruckCapitalR]
, dsR ,
[ScriptCapitalH]
, scH ,
[DoubleStruckCapitalQ]
, dsQ ,
[ScriptCapitalL]
, scL ,
[DoubleStruckCapitalZ]
, dsZ ,
[GothicCapitalC]
, goC ,
[DoubleStruckCapitalN]
, dsN ,
[GothicCapitalH]
, goH ,
[GothicCapitalI]
, goI ,
[DotlessJ]
[GothicCapitalR]
, goR ,
[WeierstrassP]
[DotlessI]
, wp ,
By using menu items in the notebook front end, or explicit StyleBox objects, you can make changes
in the font and style of ordinary text. However, such changes are usually discarded whenever you
send input to the Mathematica kernel.
Script, gothic and double-struck characters are however treated as fundamentally different from
their ordinary forms. This means that even though a C that is italic or a different size will be
considered equivalent to an ordinary C when fed to the kernel, a double-struck will not.
Different styles and sizes of C are
treated as the same by the kernel. But
gothic and double-struck characters are
treated as different.
In[1]:= C C
C
Out[1]= 3 C
In standard mathematical notation, capital script and gothic letters are sometimes used interchangeably. The double-struck letters, sometimes called blackboard or openface letters, are conventionally
used to denote specific sets. Thus, for example, conventionally denotes the set of complex numbers,
and the set of integers.
Dotless i and j are not usually taken to be different in meaning from ordinary i and j; they are
simply used when overscripts are being placed on the ordinary characters.
993
full names
aliases
\[ScriptA] \[ScriptZ]
, sca , , scz ,
\[ScriptCapitalA] \[ScriptCapitalZ]
, scA , , scZ ,
\[GothicA] \[GothicZ]
, goa , , goz ,
\[GothicCapitalA] \[GothicCapitalZ]
, goA , , goZ ,
\[DoubleStruckA] \[DoubleStruckZ]
, dsa , , dsz ,
\[DoubleStruckCapitalA] \[DoubleStruckCapitalZ]
, dsA , , dsZ ,
Hebrew Letters
form
full name
alias
form
full name
[Aleph]
, al ,
[Gimel]
"
[Bet]
[Dalet]
Hebrew characters.
Hebrew characters are used in mathematics in the theory of transfinite sets; Y is for example used to
denote the total number of integers.
994
form
full name
alias
form
full name
alias
[Micro]
, mi ,
[Degree]
, deg ,
[Mho]
, mho ,
[EmptySet]
, es ,
[Angstrom]
, Ang ,
[Infinity]
, inf ,
[HBar]
, hb ,
[ExponentialE]
, ee ,
[Cent]
, cent ,
[ImaginaryI]
, ii ,
[Sterling]
[ImaginaryJ]
, jj ,
[Euro]
'
[DoubledPi]
, pp ,
&
[Yen]
[DoubledGamma]
, gg ,
Mathematica treats or \[Degree] as the symbol Degree, so that, for example, 30 is equivalent to
30 Degree.
(\[CapitalARing] ) and
Note that , and Z are all distinct from the ordinary letters (\[Mu]), A
(\[CapitalOSlash] ).
Mathematica interprets as Infinity , as E, and both and as I. The characters , and are
provided as alternatives to the usual upper-case letters E and I.
' and ( are not by default assigned meanings in StandardForm . You can therefore use ' to
represent a pi that will not automatically be treated as Pi. In TraditionalForm ( is interpreted as
EulerGamma .
form
full name
alias
form
full name
alias
"
[PartialD]
, pd ,
[Del]
, del ,
[DifferentialD]
, dd ,
[Sum]
, sum ,
[CapitalDifferentialD]
, DD ,
[Product]
, prod ,
are
995
form
full name
alias
form
full name
alias
[FilledVerySmallSquare]
, fvssq ,
[EmptySmallCircle]
, esci ,
[EmptySmallSquare]
, essq ,
[FilledSmallCircle]
, fsci ,
[FilledSmallSquare]
, fssq ,
[EmptyCircle]
, eci ,
[EmptySquare]
, esq ,
[GrayCircle]
, gci ,
[GraySquare]
, gsq ,
[FilledCircle]
, fci ,
[FilledSquare]
, fsq ,
[EmptyUpTriangle]
[DottedSquare]
[FilledUpTriangle]
[EmptyRectangle]
[EmptyDownTriangle]
[FilledRectangle]
[FilledDownTriangle]
[EmptyDiamond]
[FivePointedStar]
, *5 ,
[FilledDiamond]
[SixPointedStar]
, *6 ,
Shapes.
Shapes are most often used as dingbats to emphasize pieces of text. But Mathematica treats them as
letter-like forms, and also allows them to appear in the names of symbols.
In addition to shapes such as \[EmptySquare] , there are characters such as \[Square] which are
treated by Mathematica as operators rather than letter-like forms.
form
full name
alias
form
full name
aliases
[MathematicaIcon]
, math ,
[HappySmiley]
, :) , , , :-) ,
[KernelIcon]
[NeutralSmiley]
, :-| ,
[LightBulb]
[SadSmiley]
, :-( ,
[WarningSign]
[FreakedSmiley]
, :-@ ,
[WatchIcon]
[Wolf]
, wf , , , wolf ,
Icons.
996
form
full name
form
full name
[Angle]
[SphericalAngle]
[RightAngle]
[EmptyUpTriangle]
<
[MeasuredAngle]
>
[Diameter]
Since Mathematica treats characters like [ as letter-like forms, constructs like [BC are treated in
Mathematica as single symbols.
Textual Elements
form
full name
alias
form
full name
alias
[Dash]
,-,
[Prime]
,',
[LongDash]
, -- ,
[DoublePrime]
, '' ,
[Bullet]
, bu ,
[ReversePrime]
,`,
[Paragraph]
[ReverseDoublePrime]
, `` ,
[Section]
[LeftGuillemet]
, g<< ,
[DownQuestion]
, d? ,
[RightGuillemet]
, g>> ,
[DownExclamation]
, d! ,
[Ellipsis]
, ... ,
form
full name
form
full name
alias
[Copyright]
[Dagger]
, dg ,
[RegisteredTrademark]
[DoubleDagger]
, ddg ,
[Trademark]
[ClubSuit]
[Flat]
[DiamondSuit]
[Natural]
[HeartSuit]
[Sharp]
[SpadeSuit]
997
form
full name
alias
form
full name
alias
[HorizontalLine]
, hline ,
[UnderParenthesis]
, u( ,
[VerticalLine]
, vline ,
[OverParenthesis]
, o( ,
[Ellipsis]
, ... ,
[UnderBracket]
, u[ ,
[CenterEllipsis]
[OverBracket]
, o[ ,
[VerticalEllipsis]
[UnderBrace]
, u{ ,
[AscendingEllipsis]
[OverBrace]
, o{ ,
[DescendingEllipsis]
2
4
Out[1]= 1
4 x
6x
4 x3
x
998
form
full name
alias
form
full name
alias
a`
a
a
a
a
a
a
a
c
c
c
e`
e
e
e
e
e
`
F
n
o`
o
o
o
o
o
s
u`
u
u
u
u
G
[AGrave]
[AAcute]
[AHat]
[ATilde]
[ADoubleDot]
[ARing]
[ABar]
[ACup]
[AE]
[CAcute]
[CCedilla]
[CHacek]
[EGrave]
[EAcute]
[EBar]
[EHat]
[EDoubleDot]
[ECup]
[IGrave]
[IAcute]
[IHat]
[IDoubleDot]
[ICup]
[Eth]
[LSlash]
[NTilde]
[OGrave]
[OAcute]
[OHat]
[OTilde]
[ODoubleDot]
[ODoubleAcute]
[OSlash]
[SHacek]
[UGrave]
[UAcute]
[UHat]
[UDoubleDot]
[UDoubleAcute]
[YAcute]
[Thorn]
[SZ]
, a` ,
, a' ,
, a^ ,
, aM ,
, a" ,
, ao ,
, a- ,
, au ,
, ae ,
, c' ,
, c, ,
, cv ,
, e` ,
, e' ,
, e- ,
, e^ ,
, e" ,
, eu ,
, i` ,
, i' ,
, i^ ,
, i" ,
, iu ,
, d- ,
, l/ ,
, nM ,
, o` ,
, o' ,
, o^ ,
, oM ,
, o" ,
, o'' ,
, o/ ,
, sv ,
, u` ,
, u' ,
, u^ ,
, u" ,
, u'' ,
, y' ,
, thn ,
, sz , , , ss ,
`
A
C
C
C
`E
E
E
E
E
E
`I
I
I
I
I
H
I
N
`
O
S
`
U
U
J
K
[CapitalAGrave]
[CapitalAAcute]
[CapitalAHat]
[CapitalATilde]
[CapitalADoubleDot]
[CapitalARing]
[CapitalABar]
[CapitalACup]
[CapitalAE]
[CapitalCAcute]
[CapitalCCedilla]
[CapitalCHacek]
[CapitalEGrave]
[CapitalEAcute]
[CapitalEBar]
[CapitalEHat]
[CapitalEDoubleDot]
[CapitalECup]
[CapitalIGrave]
[CapitalIAcute]
[CapitalIHat]
[CapitalIDoubleDot]
[CapitalICup]
[CapitalEth]
[CapitalLSlash]
[CapitalNTilde]
[CapitalOGrave]
[CapitalOAcute]
[CapitalOHat]
[CapitalOTilde]
[CapitalODoubleDot]
[CapitalODoubleAcute]
[CapitalOSlash]
[CapitalSHacek]
[CapitalUGrave]
[CapitalUAcute]
[CapitalUHat]
[CapitalUDoubleDot]
[CapitalUDoubleAcute]
[CapitalYAcute]
[CapitalThorn]
, A` ,
, A' ,
, A^ ,
, AM ,
, A" ,
, Ao ,
, A- ,
, Au ,
, AE ,
, C' ,
, C, ,
, Cv ,
, E` ,
, E' ,
, E- ,
, E^ ,
, E" ,
, Eu ,
, I` ,
, I' ,
, I^ ,
, I" ,
, Iu ,
, D- ,
, L/ ,
, NM ,
, O` ,
, O' ,
, O^ ,
, OM ,
, O" ,
, O'' ,
, O/ ,
, Sv ,
, U` ,
, U' ,
, U^ ,
, U" ,
, U'' ,
, Y' ,
, Thn ,
999
Most of the characters shown are formed by adding diacritical marks to ordinary English letters.
Exceptions include \[SZ] , used in German, and \[Thorn] and \[Eth] , used primarily in Old
English.
You can make additional characters by explicitly adding diacritical marks yourself.
form
alias
full name
(keyboard character)
\[RawQuote]
acute accent
,',
\[Prime]
acute accent
(keyboard character)
\[RawBackquote]
\[ReversePrime]
grave accent
grave accent
\[RawWedge]
circumflex or hat
,`,
(keyboard characters)
(keyboard character)
umlaut or diaeresis
, esci ,
\[EmptySmallCircle]
ring
.
~
_
(keyboard character)
dot
(keyboard character)
\[RawDot]
\[RawTilde]
(keyboard character)
\[RawUnderscore]
bar or macron
, hc ,
\[Hacek]
hacek or check
, bv ,
, dbv ,
\[Breve]
\[DownBreve]
breve
, '' ,
\[DoublePrime]
long umlaut
, cd ,
\[Cedilla]
cedilla
tilde
tie accent
1000
3.10.4 Operators
Basic Mathematical Operators
form
full name
alias
form
full name
alias
[Times]
,*,
[Cross]
, cross ,
J
.
[Divide]
, div ,
[PlusMinus]
, +- ,
[Sqrt]
, sqrt ,
[MinusPlus]
, -+ ,
Note that the for \[Cross] is distinguished by being drawn slightly smaller than the b for \[Times] .
xy
Times[x, y]
multiplication
x
y
2x
Divide[x, y]
division
Sqrt[x]
square root
xy
Cross[x, y]
mx
PlusMinus[x]
xmy
PlusMinus[x, y]
x
MinusPlus[x]
xy
MinusPlus[x, y]
Operators in Calculus
form
full name
alias
form
full name
alias
[Del]
, del ,
[Integral]
, int ,
"
[PartialD]
, pd ,
[ContourIntegral]
, cint ,
[DifferentialD]
, dd ,
[DoubleContourIntegral]
[Sum]
, sum ,
[CounterClockwiseContourIntegral]
, cccint ,
[Product]
, prod ,
[ClockwiseContourIntegral]
, ccint ,
3.10.4 Operators
1001
form
full name
aliases
form
full name
alias
[And]
, && , , , and ,
[Implies]
, => ,
[Or]
, || , , , or ,
[RoundImplies]
[Not]
, ! , , , not ,
[Therefore]
[Element]
, el ,
[Because]
[ForAll]
, fa ,
[RightTee]
[Exists]
, ex ,
[LeftTee]
[NotExists]
, !ex ,
[DoubleRightTee]
[Xor]
, xor ,
[DoubleLeftTee]
[Nand]
, nand ,
[SuchThat]
, st ,
[Nor]
, nor ,
[VerticalSeparator]
,|,
[Colon]
,:,
, tf ,
The operators +, , and a are interpreted as corresponding to the built-in functions And, Or and Not,
and are equivalent to the keyboard operators &&, || and !. The operators ,
and correspond to
the built-in functions Xor, Nand and Nor. Note that a is a prefix operator.
xy and x!y are both taken to give the built-in function Implies[x, y].
function Element[x, y].
This is interpreted using the built-in
functions And and Implies .
Mathematica supports most of the standard syntax used in mathematical logic. In Mathematica, however, the variables that appear in the quantifiers , and M must appear as subscripts. If they appeared
directly after the quantifier symbols then there could be a conflict with multiplication operations.
\ and ] are essentially prefix operators
like 8.
1002
form
full name
alias
form
full name
alias
[SmallCircle]
, sc ,
[Wedge]
,^,
[CirclePlus]
, c+ ,
[Vee]
,v,
[CircleMinus]
, c- ,
[Union]
, un ,
[CircleTimes]
, c* ,
[UnionPlus]
[CircleDot]
, c. ,
[Intersection]
[Diamond]
, dia ,
[SquareIntersection]
&
[CenterDot]
,.,
[SquareUnion]
[Star]
, star ,
*
2
[Coproduct]
[VerticalTilde]
[Cap]
[Backslash]
[Cup]
[Square]
,\,
, inter ,
, coprod ,
, sq ,
Operators typically used to represent actions. All the operators except \[Square] are infix.
Following Mathematicas usual convention, all the operators in the table above are interpreted to give
functions whose names are exactly the names of the characters that appear in the operators.
In[1]:= x y
z // FullForm
All the operators in the table above, except for , are infix, so that they must appear in between
their operands.
Bracketing Operators
form
full name
alias
form
full name
alias
[LeftFloor]
, lf ,
[LeftAngleBracket]
,<,
[RightFloor]
, rf ,
[RightAngleBracket]
,>,
&
[LeftCeiling]
, lc ,
[LeftBracketingBar]
, l| ,
'
[RightCeiling]
, rc ,
[RightBracketingBar]
, r| ,
[LeftDoubleBracket]
, [[ ,
[LeftDoubleBracketingBar]
, l|| ,
[RightDoubleBracket]
, ]] ,
[RightDoubleBracketingBar]
, r|| ,
3.10.4 Operators
1003
DxE
Floor[x]
FxG
Ceiling[x]
m+i,j, ... ,
Part[m, i, j, ... ]
/x,y, ... 0
AngleBracket[x, y, ... ]
@x,y, ... A
BracketingBar[x, y, ... ]
Bx,y, ... C
DoubleBracketingBar[x, y, ... ]
form
full name
alias
form
full name
alias
[Equal]
, == ,
[NotEqual]
, != ,
[LongEqual]
, l= ,
[NotCongruent]
, !=== ,
[Congruent]
, === ,
[NotTilde]
, !K ,
[Tilde]
,K,
[NotTildeTilde]
, !KK ,
[TildeTilde]
, KK ,
[NotTildeEqual]
, !K= ,
[TildeEqual]
, K= ,
[NotTildeFullEqual]
, !K== ,
[TildeFullEqual]
, K== ,
[NotEqualTilde]
, !=K ,
[EqualTilde]
, =K ,
[NotHumpEqual]
, !h= ,
[HumpEqual]
, h= ,
[NotHumpDownHump]
[HumpDownHump]
[NotCupCap]
[CupCap]
[Proportional]
[DotEqual]
[Proportion]
In[1]:= {a == b, a 2 b, a != b, a
Out[1]= a b, a b, a b, a b
b}
, prop ,
1004
form
full name
alias
form
full name
alias
[GreaterEqual]
, >= ,
[NotGreaterEqual]
, !>= ,
[LessEqual]
, <= ,
[NotLessEqual]
, !<= ,
[GreaterSlantEqual]
, >/ ,
[NotGreaterSlantEqual]
, !>/ ,
[LessSlantEqual]
, </ ,
[NotLessSlantEqual]
, !</ ,
[GreaterFullEqual]
[NotGreaterFullEqual]
[LessFullEqual]
[NotLessFullEqual]
[GreaterTilde]
, >K ,
[NotGreaterTilde]
, !>K ,
[LessTilde]
, <K ,
[NotLessTilde]
, !<K ,
[GreaterGreater]
[NotGreaterGreater]
[LessLess]
[NotLessLess]
[NestedGreaterGreater]
[NotNestedGreaterGreater]
[NestedLessLess]
[NotNestedLessLess]
[GreaterLess]
[NotGreaterLess]
[LessGreater]
[NotLessGreater]
[GreaterEqualLess]
[NotGreater]
, !> ,
[LessEqualGreater]
[NotLess]
, !< ,
form
full name
alias
form
full name
alias
[Subset]
, sub ,
[NotSubset]
, !sub ,
[Superset]
, sup ,
[NotSuperset]
, !sup ,
[SubsetEqual]
, sub= ,
[NotSubsetEqual]
, !sub= ,
[SupersetEqual]
, sup= ,
[NotSupersetEqual]
, !sup= ,
[Element]
, el ,
[NotElement]
, !el ,
[ReverseElement]
, mem ,
[NotReverseElement]
, !mem ,
3.10.4 Operators
1005
form
full name
form
full name
[Succeeds]
[NotSucceeds]
[Precedes]
[NotPrecedes]
[SucceedsEqual]
[NotSucceedsEqual]
[PrecedesEqual]
[NotPrecedesTilde]
[SucceedsSlantEqual]
[NotSucceedsSlantEqual]
[PrecedesSlantEqual]
[NotPrecedesSlantEqual]
[SucceedsTilde]
[NotSucceedsTilde]
[PrecedesTilde]
[NotPrecedesEqual]
[RightTriangle]
[NotRightTriangle]
[LeftTriangle]
[NotLeftTriangle]
[RightTriangleEqual]
[NotRightTriangleEqual]
[LeftTriangleEqual]
[NotLeftTriangleEqual]
[RightTriangleBar]
[NotRightTriangleBar]
[LeftTriangleBar]
[NotLeftTriangleBar]
[SquareSuperset]
[NotSquareSuperset]
[SquareSubset]
[NotSquareSubset]
[SquareSupersetEqual]
[NotSquareSupersetEqual]
[SquareSubsetEqual]
[NotSquareSubsetEqual]
form
full name
alias
form
full name
alias
[VerticalBar]
, | ,
[NotVerticalBar]
, !| ,
[DoubleVerticalBar]
, || ,
[NotDoubleVerticalBar]
, !|| ,
1006
In[1]:= x + y /. x 3
Out[1]= 3 y
form
full name
alias
form
full name
alias
[Rule]
, -> ,
[Implies]
, => ,
[RuleDelayed]
, :> ,
[RoundImplies]
form
full name
alias
form
full name
[RightArrow]
, -> ,
[UpArrow]
[LeftArrow]
, <- ,
[DownArrow]
[LeftRightArrow]
, <-> ,
[UpDownArrow]
[LongRightArrow]
, --> ,
[LongLeftArrow]
, <-- ,
[DownTeeArrow]
[LongLeftRightArrow]
, <--> ,
&
[UpArrowBar]
[ShortRightArrow]
[DownArrowBar]
[ShortLeftArrow]
'
[RightTeeArrow]
[DoubleDownArrow]
[LeftTeeArrow]
[DoubleUpDownArrow]
"
[RightArrowBar]
[RightArrowLeftArrow]
[LeftArrowBar]
[LeftArrowRightArrow]
[DoubleRightArrow]
, => ,
[UpArrowDownArrow]
[DoubleLeftArrow]
, <= ,
[DownArrowUpArrow]
[DoubleLeftRightArrow]
, <=> ,
+
,
[LowerRightArrow]
[DoubleLongRightArrow]
, ==> ,
[LowerLeftArrow]
[DoubleLongLeftArrow]
, <== ,
[UpperLeftArrow]
[DoubleLongLeftRightArrow]
, <==> ,
[UpperRightArrow]
Ordinary arrows.
[UpTeeArrow]
[DoubleUpArrow]
3.10.4 Operators
1007
form
full name
alias
form
full name
[RightVector]
, vec ,
[LeftUpVector]
[LeftVector]
[LeftDownVector]
[LeftRightVector]
[LeftUpDownVector]
[DownRightVector]
A
B
[DownLeftVector]
[RightDownVector]
[DownLeftRightVector]
[RightUpDownVector]
[RightTeeVector]
D
E
[LeftTeeVector]
[LeftDownTeeVector]
[DownRightTeeVector]
[RightUpTeeVector]
[DownLeftTeeVector]
[RightDownTeeVector]
[RightVectorBar]
[LeftUpVectorBar]
[LeftVectorBar]
[LeftDownVectorBar]
<
[DownRightVectorBar]
[RightUpVectorBar]
[DownLeftVectorBar]
[RightDownVectorBar]
[Equilibrium]
[UpEquilibrium]
>
[ReverseEquilibrium]
[ReverseUpEquilibrium]
, equi ,
[RightUpVector]
[LeftUpTeeVector]
Tees.
In[2]:= x y z
Out[2]= x
y
z
form
full name
alias
form
full name
[RightTee]
, rT ,
[DoubleRightTee]
[LeftTee]
, lT ,
[DoubleLeftTee]
[UpTee]
, uT ,
[DownTee]
, dT ,
1008
alias
full name
alias
[InvisibleComma]
,,,
[AlignmentMarker]
, am ,
[InvisibleApplication]
,@,
[NoBreak]
, nb ,
[InvisibleSpace]
, is ,
[Null]
, null ,
Invisible characters.
In[1]:= m12
In[2]:= FullFormxy
Out[1]= m1,2
Out[2]//FullForm= Times x, y
Out[3]= f x, a
Out[4]//DisplayForm=
b c d
a b c
full name
alias
full name
alias
[VeryThinSpace]
,,
[NegativeVeryThinSpace]
, - ,
[ThinSpace]
, ,
[NegativeThinSpace]
, - ,
[MediumSpace]
, ,
[NegativeMediumSpace]
, - ,
[ThickSpace]
, ,
[NegativeThickSpace]
, - ,
[InvisibleSpace]
, is ,
[NonBreakingSpace]
, nbs ,
[IndentingNewLine]
, nl ,
[NewLine]
Spacing and newline characters.
form
full name
alias
form
full name
alias
[SelectionPlaceholder]
, spl ,
[Placeholder]
, pl ,
1009
In the buttons in a palette, you often want to set up a template with placeholders to indicate where expressions should be inserted. \[SelectionPlaceholder] marks the position where an expression that
is currently selected should be inserted when the contents of the button are pasted. \[Placeholder]
marks other positions where subsequent expressions can be inserted. The TAB key will take you from
one such position to the next.
form
full name
alias
form
full name
[SpaceIndicator]
, space ,
[RoundSpaceIndicator]
alias
[ReturnIndicator]
, ret ,
[ControlKey]
, ctrl ,
[ReturnKey]
, ret ,
[CommandKey]
, cmd ,
[EnterKey]
, ent ,
[LeftModified]
,[,
[EscapeKey]
, esc ,
[RightModified]
,],
[AliasIndicator]
, esc ,
[CloverLeaf]
, cl ,
In describing how to enter input into Mathematica, it is sometimes useful to give explicit representations for keys you should press. You can do this using characters like ` and . Note that _ and V
are actually treated as spacing characters by Mathematica.
This string shows how to type 2 .
In[5]:= "\[EscapeKey]a\[EscapeKey]
\[ControlKey]\[LeftModified]^\[RightModified]2
\[ControlKey]\[LeftModified]\[SpaceIndicator]\[RightModified]"
Out[5]= a ^2
form
full name
form
full name
[Continuation]
[SkeletonIndicator]
[LeftSkeleton]
[ErrorIndicator]
[RightSkeleton]
In[6]:= 60!
Out[6]= 8320987112741390144276341183223364380754172606361
245952449277696409600000000000000
1010
form
full name
form
full name
[RawTab]
[RawSlash]
[NewLine]
[RawColon]
[RawReturn]
[RawSemicolon]
[RawSpace]
<
[RawLess]
[RawExclamation]
[RawEqual]
"
[RawDoubleQuote]
>
[RawGreater]
[RawNumberSign]
[RawQuestion]
[RawDollar]
[RawAt]
[RawPercent]
[RawLeftBracket]
&
[RawAmpersand]
[RawBackslash]
[RawQuote]
[RawRightBracket]
[RawLeftParenthesis]
[RawWedge]
[RawRightParenthesis]
[RawUnderscore]
[RawStar]
[RawBackquote]
[RawPlus]
[RawLeftBrace]
[RawComma]
[RawVerticalBar]
[RawDash]
[RawRightBrace]
[RawDot]
[RawTilde]
The fonts that are distributed with Mathematica contain their own renderings of many ordinary keyboard characters. The reason for this is that standard system fonts often do not contain appropriate
renderings. For example, ^ and M are often drawn small and above the centerline, while for clarity in
Mathematica they must be drawn larger and centered on the centerline.
Appendix
This appendix gives a definitive summary of the complete Mathematica
system. Most of what it contains you will never need to know for any
particular application of Mathematica.
You should realize that this appendix describes all the features of
Mathematica, independent of their importance in typical usage.
Other parts of this book are organized along pedagogical lines,
emphasizing important points, and giving details only when they
are needed.
This appendix gives all the details of every feature. As a result, you
will often find obscure details discussed alongside very common and
important functions. Just remember that this appendix is intended for
reference purposes, not for sequential reading. Do not be put off by
the complexity of some of what you see; you will almost certainly never
have to use it. But if you do end up having to use it, you will probably
be happy that it is there.
By experimenting with Mathematica, you may find features that
go beyond what is described in this appendix. You should not use
any such features: there is no certainty that features which are not
documented will continue to be supported in future versions of
Mathematica.
Appendix
A.1
A.2
Input Syntax
A.3
A.4
Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . 1045
A.5
A.6
A.7
A.8
A.9
. . . . . . . . . . . . . . . . . . . . . . . 1018
1402
1014
Part[expr, i , i , ... ], expr[[i , i , ... ]] or Extract[expr, {i , i , ... }] gives the piece of expr
found by successively extracting parts of subexpressions with indices i , i , ... . If you think of
expressions as trees, the indices specify which branch to take at each node as you descend from the
root.
The pieces of an expression that are specified by giving a sequence of exactly n indices are defined
to be at level n in the expression. You can use levels to determine the domain of application of
functions like Map. Level 0 corresponds to the whole expression.
The depth of an expression is defined to be the maximum number of indices needed to specify any
part of the expression, plus one. A negative level number -n refers to all parts of an expression that
have depth n.
A.1.2 Symbols
Symbols are the basic named objects in Mathematica.
The name of a symbol must be a sequence of letters, letter-like forms and digits, not starting with
a digit. Upper- and lower-case letters are always distinguished in Mathematica.
aaaaa
user-defined symbol
Aaaaa
system-defined symbol
$Aaaa
aaaa$
aa$nn
1015
Essentially all system-defined symbols have names that contain only ordinary English letters, together with numbers and $. The exceptions are , , , and ".
System-defined symbols conventionally have names that consist of one or more complete English
words. The first letter of each word is capitalized, and the words are run together.
Once created, an ordinary symbol in Mathematica continues to exist unless it is explicitly removed
using Remove. However, symbols created automatically in scoping constructs such as Module carry
the attribute Temporary which specifies that they should automatically be removed as soon as they
no longer appear in any expression.
When a new symbol is to be created, Mathematica first applies any value that has been assigned to
$NewSymbol to strings giving the name of the symbol, and the context in which the symbol would be
created.
If the message General::newsym is switched on, then Mathematica reports new symbols that are
created. This message is switched off by default. Symbols created automatically in scoping constructs
are not reported.
If the message General::spell is switched on, then Mathematica prints a warning if the name of a
new symbol is close to the names of one or more existing symbols.
A.1.3 Contexts
The full name of any symbol in Mathematica consists of two parts: a context, and a short name. The
full name is written in the form context`name. The context context` can contain the same characters as
the short name. It may also contain any number of context mark characters `, and must end with a
context mark.
At any point in a Mathematica session, there is a current context $Context and a context search path
$ContextPath consisting of a list of contexts. Symbols in the current context, or in contexts on the
context search path can be specified by giving only their short names.
name
`name
context`name
`context`name
1016
With Mathematica packages, it is conventional to associate contexts whose names correspond to the
names of the packages. Packages typically use BeginPackage and EndPackage to define objects in
the appropriate context, and to add the context to the global $ContextPath . EndPackage prints a
warning about any symbols that were created in a package but which are shadowed by existing
symbols on the context search path.
The context is included in the printed form of a symbol only if it would be needed to specify the
symbol at the time of printing.
Symbol
String
Integer
Real
Rational
Complex
Atomic objects.
Atomic objects in Mathematica are considered to have depth 0 and yield True when tested with
AtomQ.
As an optimization for some special kinds of computations, the raw data in Mathematica atomic
objects can be given explicitly using Raw[head, "hexstring"]. The data is specified as a string of hexadecimal digits, corresponding to an array of bytes. When no special output form exists, InputForm
prints special objects using Raw. The behavior of Raw differs from one implementation of Mathematica to
another; its general use is strongly discouraged.
1017
A.1.5 Numbers
Integer
Real
Rational
Complex
integer nnnn
approximate real number nnn.nnn
rational number nnn/nnn
complex number nnn + nnn I
All numbers in Mathematica can contain any number of digits. Mathematica does exact computations when possible with integers and rational numbers, and with complex numbers whose real and
imaginary parts are integers or rational numbers.
There are two types of approximate real numbers in Mathematica: arbitrary precision and machine precision. In manipulating arbitrary-precision numbers, Mathematica always tries to modify the precision
so as to ensure that all digits actually given are correct.
With machine-precision numbers, all computations are done to the same fixed precision, so some
digits given may not be correct.
Unless otherwise specified, Mathematica treats as machine-precision numbers all approximate real
numbers that lie between $MinMachineNumber and $MaxMachineNumber and that are input with less
than $MachinePrecision digits.
In InputForm , Mathematica prints machine-precision numbers with $MachinePrecision digits, except when trailing digits are zero.
In any implementation of Mathematica, the magnitudes of numbers (except 0) must lie between
$MinNumber and $MaxNumber . Numbers with magnitudes outside this range are represented by
Underflow[ ] and Overflow[ ].
1018
All printable ASCII characters can be entered directly. Those that are not alphanumeric are assigned
explicit names in Mathematica, allowing them to be entered even on keyboards where they do not
explicitly appear.
\[RawSpace]
\[RawSemicolon]
\[RawExclamation]
<
\[RawLess]
"
\[RawDoubleQuote]
\[RawEqual]
\[RawNumberSign]
>
\[RawGreater]
\[RawDollar]
\[RawQuestion]
\[RawPercent]
\[RawAt]
&
\[RawAmpersand]
\[RawLeftBracket]
'
\[RawQuote]
\[RawBackslash]
\[RawLeftParenthesis]
\[RawRightBracket]
\[RawRightParenthesis]
\[RawWedge]
\[RawStar]
\[RawUnderscore]
\[RawPlus]
\[RawBackquote]
\[RawComma]
\[RawLeftBrace]
\[RawDash]
\[RawVerticalBar]
\[RawDot]
\[RawRightBrace]
\[RawSlash]
\[RawTilde]
\[RawColon]
1019
All characters which are entered into the Mathematica kernel are interpreted according to the setting
for the CharacterEncoding option for the stream from which they came.
In the Mathematica front end, characters entered on the keyboard are interpreted according to the
current setting of the CharacterEncoding option for the current notebook.
\[Name]
\nnn
\.nn
\:nnnn
Codes for characters can be generated using ToCharacterCode . The Unicode standard is followed,
with various extensions.
8-bit characters have codes less than 256; 16-bit characters have codes between 256 and 65535.
Approximately 750 characters are assigned explicit names in Mathematica. Other characters must be
entered using their character codes.
\\
\b
\t
\n
\f
\r
\000
1020
Options can be set to specify what form of input should be accepted by a particular cell in a
notebook or from a particular stream.
The input syntax in TraditionalForm , for example, is different from that in InputForm and
StandardForm .
In general, what input syntax does is to determine how a particular string or collection of boxes
should be interpreted as an expression. When boxes are set up, say with the notebook front end, there
can be hidden InterpretationBox or TagBox objects which modify the interpretation of the boxes.
a character string
\"
\\
Character strings can contain any sequence of 8- or 16-bit characters. Characters entered by name or
character code are stored the same as if they were entered directly.
Single newlines followed by spaces or tabs are converted to a single space when a string is entered,
unless these characters occur within \< ... \>, in which case they are left unchanged.
Within \!\( ... \) any box structures represented using backslash sequences can be used.
`name
context`name
symbol name
symbol name in current context
symbol name in specified context
Symbol names and contexts can contain any characters that are treated by Mathematica as letters or
letter-like forms. They can contain digits but cannot start with them.
1021
A.2.5 Numbers
digits
integer
digits.digits
approximate number
base^^digits
base^^digits.digits
mantissa*^n
base^^mantissa*^n
number`
number`s
number``s
Numbers can be entered with the notation base^^digits in any base from 2 to 36. The base itself
is given in decimal. For bases larger than 10, additional digits are chosen from the letters az or
AZ. Upper- and lower-case letters are equivalent for these purposes. Floating-point numbers can be
specified by including . in the digits sequence.
In scientific notation, mantissa can contain ` marks. The exponent n must always be an integer,
specified in decimal.
The precision or accuracy s can be any real number; it does not need to be an integer.
In the form base^^number`s the precision s is given in decimal, but it gives the effective number of
digits of precision in the specified base, not in base 10.
An approximate number x is taken to be machine precision if the number of digits given in it is
Ceiling[$MachinePrecision] + 1 or less. If more digits are given, then x is taken to be an arbitraryprecision number. The accuracy of x is taken to be the number of digits that appear to the right of
the decimal point, while its precision is taken to be Log[10, Abs[x]] + Accuracy[x].
A number entered in the form 0``s is taken to have precision Indeterminate and accuracy s.
1022
(* any text *)
(expr)
comment
parenthesization: grouping of input
Comments can be nested, and can continue for any number of lines. They can contain any 8- or
16-bit characters.
Parentheses must enclose a single complete expression; neither (e, e) nor ( ) are allowed.
{e , e , ... }
/ e , e , ... 0
List[e , e , ... ]
AngleBracket[e , e , ... ]
D expr E
Floor[expr]
F expr G
Ceiling[expr]
@ e , e , ... A
BracketingBar[e , e , ... ]
B e , e , ... C
DoubleBracketingBar[e , e , ... ]
\(input\)
Throughout this book the notation ... is used to stand for any sequence of expressions.
{e , e , ... } can include any number of elements, with successive elements separated by commas.
{ } is List[ ], a list with zero elements.
/ e , e , ... 0 can be entered as \[LeftAngleBracket] e , e , ... \[RightAngleBracket] .
The character \[InvisibleComma] can be used interchangeably with ordinary commas; the only
difference is that \[InvisibleComma] will not be displayed.
When the delimiters are special characters, it is a convention that they are named \[LeftName]
and \[RightName].
\( ... \) is used to enter boxes using one-dimensional strings. Note that within the outermost
\( ... \) in a piece of input the syntax used is slightly different from outside, as described on
page 1036.
1023
h[e , e , ... ]
standard expression
e[[i , i , ... ]]
Part[e, i , i , ... ]
e+ i , i , ... ,
Part[e, i , i , ... ]
Bracketed objects with heads explicitly delimit all their operands except the head. A precedence
must be assigned to define the extent of the head.
The precedence of h[e] is high enough that !h[e] is interpreted as Not[h[e]]. However, h_s[e] is
interpreted as (h_s)[e].
any expression
any symbol
any pattern object
filename
1024
operator form
full form
grouping
MessageName[expr, "string"]
MessageName[expr, "string ", "string "]
<< filename
Get["filename"]
e
expr2
e
expr1
expr \& expr
expr1
Overscript[expr , expr ]
Overscript[expr , expr ]
Underscript[expr , expr ]
e
e\&(e\&e)
e
expr \+ expr
Underscript[expr , expr ]
e\+(e\+e)
expr2
expr3
ee
expr1
expr1
Subscript[expr , expr ]
eee
expr \_ expr
expr \_ expr \% expr
Subscript[expr , expr ]
Power[Subscript[expr , expr ], expr
]
e\_(e\_e)
\!boxes
expr ?expr
PatternTest[expr , expr ]
expr [expr ,
Part[expr ,
Part[expr ,
Part[expr ,
\*expr
expr++
expr--
expr2
expr2
Hexpr2 ,I
... ]
expr , ... ]
expr , ... ]
expr , ... ]
(e[e])[e]
(e[[e]])[[e]]
(e+e,)+e,
e+e, +e,
1025
operator form
full form
++expr
--expr
PreIncrement[expr]
PreDecrement[expr]
grouping
expr @ expr
expr [expr ]
expr expr (invisible application, input as expr H @ H expr )
expr [expr ]
e @ (e @ e)
(e M e M e) M e M e
expr
expr
expr
expr
Map[expr , expr ]
MapAll[expr , expr ]
Apply[expr , expr ]
Apply[expr , expr , {1}]
e
e
e
e
/@ expr
//@ expr
@@ expr
@@@ expr
/@ (e /@ e)
//@ (e //@ e)
@@ (e @@ e)
@@@ (e @@@ e)
expr!
expr!!
Factorial[expr]
Factorial2[expr]
expr'
expr'' ... ' (n times)
Derivative[1][expr]
Derivative[n][expr]
e <> e <> e
expr ^ expr
Power[expr , expr ]
e^(e^e)
ee
expr1
expr2
Power[expr , expr ]
expr1 expr3
expr2
expr 7 expr
e2
e3 ]7e4
2(2e)
\@(\@e)
Integrate[expr , expr ]
( e 7 e) 7 e
Integrate[e
, {e
, e , e }]
( e 7 e) 7 e
e1
8expr1 expr2
D[expr , expr ]
8e 8e e
Y expr
Del[expr]
Y (Y e)
expr
expr expr expr
Square[expr]
SmallCircle[expr , expr , expr
]
( e)
eee
1026
operator form
full form
grouping
eee
eee
e.e.e
-expr
+expr
m expr
expr
Times[-1, expr]
expr
PlusMinus[expr]
MinusPlus[expr]
expr / expr
expr
expr
expr \/ expr
(e / e) / e
(e
e)
e
(e\/e)\/e
e-e-e
enene
eee
e#e#e
egege
eoeoe
eee
e*e*e
eee
e[e[e
Product[e
, {e , e , e
}]
* (* e)
e$e$e
e1e1e
e%e%e
e&e&e
eOeOe
(e ' e) ' e
e3
( e4
e1 =e2
operator form
1027
full form
grouping
Sum[e
, {e , e , e
}]
) () e)
e+e+e
(e - e) - e
(e m e) m e
(e e) e
expr expr
other intersection operators
Intersection[expr , expr ]
eee
expr expr
other union operators
Union[expr , expr ]
eee
expr == expr
Equal[expr , expr ]
expr expr
Equal[expr , expr ]
expr expr
Equal[expr , expr ]
expr != expr
Unequal[expr , expr ]
expr expr
Unequal[expr , expr ]
other equality and similarity operators
Greater[expr , expr ]
expr > expr
expr >= expr
GreaterEqual[expr , expr ]
expr expr
GreaterEqual[expr , expr ]
expr expr
GreaterEqual[expr , expr ]
expr < expr
Less[expr , expr ]
expr <= expr
LessEqual[expr , expr ]
expr expr
LessEqual[expr , expr ]
expr ( expr
LessEqual[expr , expr ]
other ordering operators
VerticalBar[expr , expr ]
expr 3 expr
NotVerticalBar[expr , expr ]
expr expr
DoubleVerticalBar[expr , expr ]
expr 4 expr
expr expr
NotDoubleVerticalBar[expr , expr ]
horizontal arrow and vector operators
diagonal arrow operators
e
e
e
e
e
== e == e
ee
ee
!= e != e
ee
e
e
e
e
e
e
e
e
>e>e
>= e >= e
ee
ee
<e<e
<= e <= e
ee
(e(e
e
e
e
e
3e3e
ee
4e4e
ee
e === e === e
e =!= e =!= e
e3
e4
e1 =e2
expr
expr
expr
expr
+
m
expr + expr
expr
expr
expr
SameQ[expr , expr ]
UnsameQ[expr , expr ]
1028
operator form
full form
grouping
expr expr
expr ^ expr
expr p expr
expr q expr
other set relation operators
Element[expr , expr ]
NotElement[expr , expr ]
Subset[expr , expr ]
Superset[expr , expr ]
e
e
e
e
e
e
e
e
\expr1 expr2
ForAll[expr , expr ]
\e \e e
]expr1 expr2
Exists[expr , expr ]
]e ]e e
expr1 expr2
NotExists[expr , expr ]
e e e
!expr
expr
Not[expr]
Not[expr]
!(!e)
( e)
e && e && e
eee
eee
eee
e || e || e
eee
eee
expr expr
expr ! expr
Implies[expr , expr ]
Implies[expr , expr ]
e(ee)
e!(e!e)
RightTee[expr , expr ]
DoubleRightTee[expr , expr ]
LeftTee[expr , expr ]
DoubleLeftTee[expr , expr ]
e (e e)
e ) (e ) e)
(e * e) * e
(e + e) + e
expr _ expr
SuchThat[expr , expr ]
e _ (e _ e)
expr..
expr...
Repeated[expr]
RepeatedNull[expr]
expr | expr
Alternatives[expr , expr ]
symb:expr
patt:expr
Pattern[symb, expr]
Optional[patt, expr]
expr
expr
expr
expr
)
*
+
expr
expr
expr
expr
^
p
q
e
e
e
e
^
p
q
e|e|e
1029
operator form
full form
grouping
expr /; expr
Condition[expr , expr ]
(e/;e)/;e
expr
expr
expr
expr
Rule[expr , expr ]
Rule[expr , expr ]
RuleDelayed[expr , expr ]
RuleDelayed[expr , expr ]
e
e
e
e
-> (e -> e)
(e e)
:> (e :> e)
(e
e)
expr /. expr
expr //. expr
ReplaceAll[expr , expr ]
ReplaceRepeated[expr , expr ]
(e /. e) /. e
(e //. e) //. e
expr
expr
expr
expr
AddTo[expr , expr ]
SubtractFrom[expr , expr ]
TimesBy[expr , expr ]
DivideBy[expr , expr ]
e
e
e
e
-> expr
expr
:> expr
expr
+=
-=
*=
/=
expr
expr
expr
expr
+=
-=
*=
/=
(e
(e
(e
(e
+=
-=
*=
/=
e)
e)
e)
e)
expr &
Function[expr]
expr : expr
Colon[expr , expr ]
e:e:e
expr // expr
expr [expr ]
(e // e) // e
expr expr
VerticalSeparator[expr , expr ]
eee
expr i expr
expr , expr
Therefore[expr , expr ]
Because[expr , expr ]
e i (e i e)
(e , e) , e
expr = expr
expr := expr
expr ^= expr
expr ^:= expr
symb/: expr = expr
symb/: expr := expr
expr =.
symb/: expr =.
Set[expr , expr ]
SetDelayed[expr , expr ]
UpSet[expr , expr ]
UpSetDelayed[expr , expr ]
TagSet[symb, expr , expr ]
TagSetDelayed[symb, expr , expr ]
Unset[expr]
TagUnset[symb, expr]
e
e
e
e
Put[expr, "filename"]
PutAppend[expr, "filename"]
expr \` expr
FormBox[expr , expr ]
= (e = e)
:= (e := e)
^= (e ^= e)
^:= (e ^:= e)
e \` (e \` e)
1030
#
#n
##
##n
%
%%
%% ... % (n times)
%n
_
_expr
__
__expr
___
___expr
_.
symb_
symb_expr
symb__
symb__expr
symb___
symb___expr
symb_.
full form
Slot[1]
Slot[n]
SlotSequence[1]
SlotSequence[n]
Out[ ]
Out[-2]
Out[-n]
Out[n]
Blank[ ]
Blank[expr]
BlankSequence[ ]
BlankSequence[expr]
BlankNullSequence[ ]
BlankNullSequence[expr]
Optional[Blank[ ]]
Pattern[symb, Blank[ ]]
Pattern[symb, Blank[expr]]
Pattern[symb, BlankSequence[ ]]
Pattern[symb, BlankSequence[expr]]
Pattern[symb, BlankNullSequence[ ]]
Pattern[symb, BlankNullSequence[expr]]
Optional[Pattern[symb, Blank[ ]]]
Special Characters
Special characters that appear in operators usually have names that correspond to the names of the
functions they represent. Thus the character K has name \[CirclePlus] and yields the function
CirclePlus . Exceptions are \[GreaterSlantEqual] , \[LessSlantEqual] and \[RoundImplies] .
The delimiters in matchfix operators have names \[LeftName] and \[RightName].
Pages 13541401 give a complete listing of special characters that appear in operators.
keyboard characters
1031
special character
keyboard characters
special character
->
\[Rule]
>=
\[GreaterEqual]
:>
\[RuleDelayed]
>=
\[GreaterSlantEqual]
==
\[Equal]
<=
\[LessEqual]
!=
\[NotEqual]
<=
\[LessSlantEqual] (
keyboard character
special character
keyboard character
special character
\[CenterDot] o
\[RawColon] :
\[Colon] :
\[RawDot] .
\[RawTilde] M
\[Tilde] M
\[RawVerticalBar] |
\[VerticalBar] 3
\[RawWedge] ^
\[Wedge]
\[RawVerticalBar] |
\[RawWedge] ^
\[And]
\[RawVerticalBar] |
\[VerticalSeparator]
\[LeftBracketingBar] @
\[RawStar] *
\[Star] [
\[RawBackslash] \
\[Backslash] -
\[RawDash] ...
\[Dash]
\[Ellipsis] r
1032
xyz
2x
x*y*z
2*x
2(x+1)
2*(x+1)
c(x+1)
c*(x+1)
(x+1)(y+2)
x! y
x!y
(x+1)*(y+2)
x!*y
x!*y
An expression like x!y could potentially mean either (x!)*y or x*(!y). The first interpretation is
chosen because Factorial has higher precedence than Not.
Spaces within single input forms are ignored. Thus, for example, a + b is equivalent to a+b. You
will often want to insert spaces around lower precedence operators to improve readability.
You can give a coefficient for a symbol by preceding it with any sequence of digits. When you
use numbers in bases larger than 10, the digits can include letters. (In bases other than 10, there must
be a space between the end of the coefficient, and the beginning of the symbol name.)
1033
Spaces to Avoid
You should avoid inserting any spaces between the different characters in composite operators such as
/., =. and >=. Although in some cases such spaces are allowed, they are liable to lead to confusion.
Another case where spaces must be avoided is between the characters of the pattern object x_. If
you type x _, Mathematica will interpret this as x*_, rather than the single named pattern object x_.
Similarly, you should not insert any spaces inside pattern objects like x_:value.
Spacing Characters
Relational Operators
Relational operators can be mixed. An expression like a > b >= c is converted to
Inequality[a, Greater, b, GreaterEqual, c], which effectively evaluates as (a > b) && (b >= c).
(The reason for the intermediate Inequality form is that it prevents objects from being evaluated
twice when input like a > b >= c is processed.)
File Names
Any file name can be given in quotes after <<, >> and >>>. File names can also be given without
quotes if they contain only alphanumeric characters, special characters and the characters `, /, ., \, !,
-, _, :, $, *, M and ?, together with matched pairs of square brackets enclosing any characters other
than spaces, tabs and newlines. Note that file names given without quotes can be followed only by
spaces, tabs or newlines, or by the characters ), ], as well as semicolon and comma.
1034
xmax
xmin y 7x
Power[x, y]
Divide[x, y]
x
n
x
Sqrt[x]
7x
xmax
xmin y w]
z
Power[x, 1/n]
a11 a12
a21 a22
xmax
y
x=xmin
xmax
8x y
D[y, x]
8x, y
y
x=xmin
D[y, x, ... ]
Any array of expressions represented by a GridBox is interpreted as a list of lists. Even if the GridBox
has only one row, the interpretation is still {{a , a , ... }}.
xmax
In the form
xmin
7x
y]w] the limits xmin and xmax can be omitted, as can y and w.
z
xy
Subscript[x, y]
x
SubPlus[x]
x
SubMinus[x]
x[
SubStar[x]
x
SuperPlus[x]
x
SuperMinus[x]
x[
SuperStar[x]
SuperDagger[x]
Overscript[x, y]
Underscript[x, y]
N
x
=
x
K
x
f
x
xL
x
N
OverBar[x]
OverVector[x]
OverTilde[x]
OverHat[x]
OverDot[x]
UnderBar[x]
There is no issue of precedence for forms such as
x and f
x in which operands are effectively
spanned by the operator. For forms such as xy and x a left precedence does need to be specified,
so such forms are included in the main table of precedences above.
1035
Control Keys
1 or !
activate \! form
2 or @
square root
5 or %
6 or ^
superscript
7 or &
overscript
8 or *
9 or (
0 or )
- or @
subscript
= or +
underscript
J (CONTROL-RETURN)
,
.
/
fraction
(CONTROL-SPACE)
, a , b , c
On English-language keyboards both forms will work where alternates are given. On other keyboards
the first form should work but the second may not.
1036
A RowBox is constructed to hold each operator and its operands. The nesting of RowBox objects is
determined by the precedence of the operators in standard Mathematica syntax.
Note that spacing characters are not automatically discarded. Instead, each sequence of consecutive
such characters is made into a separate token.
String-Based Input
\( ... \)
\!\( ... \)
Any textual input that you give between \( and \) is taken to specify boxes to construct. The boxes
are only interpreted if you specify with \! that this should be done. Otherwise x \^ y is left for
example as SuperscriptBox[x, y], and is not converted to Power[x, y].
Within the outermost \( ... \), further \( ... \) specify grouping and lead to the insertion of
RowBox objects.
1037
box \^ box
SuperscriptBox[box , box ]
box \_ box
SubscriptBox[box , box ]
OverscriptBox[box , box ]
box \+ box
UnderscriptBox[box , box ]
\@ box
form \` box
\* input
\
insert a space
\n
insert a newline
\t
In string-based input between \( and \) spaces, tabs and newlines are discarded. \ can be
used to insert a single space. Special spacing characters such as \[ThinSpace] , \[ThickSpace] or
\[NegativeThinSpace] are not discarded.
1038
You can however explicitly tell Mathematica that a particular expression is incomplete by putting a
\ or a (\[Continuation] ) at the end of the line. Mathematica will then include the next line in the
same expression, discarding any spaces or tabs that occur at the beginning of that line.
If you are using StandardForm input in a notebook front end, then Mathematica will also not treat
an expression on a particular line as being complete if the line that follows it could not be complete
without being combined with its predecessor. Thus, for example, if a line begins with an infix operator such as b or /, then Mathematica will combine this line with the previous one to try to obtain a
complete expression. If a line begins with , , M, or another operator that can be used both in infix
or prefix form, then Mathematica will still combine the line with the previous one, but will issue a
warning to say what it is doing.
get information
??symbol
?s s ...
!command
!!file
In most implementations of Mathematica, you can give a line of special input anywhere in your input.
The only constraint is that the special input must start at the beginning of a line.
Some implementations of Mathematica may not allow you to execute external commands using
!command.
1039
A.3.3 Options
Some built-in functions can take options. Each option has a name, represented as a symbol, or in some
cases a string. Options are set by giving rules of the form name->value or name:>value. Such rules
must appear after all the other arguments in a function. Rules for different options can be given in
any order. If you do not explicitly give a rule for a particular option, a default setting for that option
is used.
1040
Options[f]
Options[expr]
Options[expr, name]
AbsoluteOptions[expr, name]
Operations on options.
element n (starting at 1)
-n
0
All
head
all elements
Numbering of parts.
all elements
None
no elements
elements 1 through n
-n
last n elements
{n}
element n only
{m, n}
{m, n, s}
The sequence specification {m, n, s} corresponds to elements m, m + s, m + 2s, ... , up to the largest
element not greater than n.
Sequence specifications are used in the functions Drop, Ordering , StringDrop , StringTake , Take
and Thread.
1041
Infinity
{n}
{n , n }
Heads -> True
Heads -> False
levels 1 through n
levels 1 through Infinity
level n only
levels n through n
include heads of expressions
do not include heads of expressions
Level specifications.
1042
A.3.7 Iterators
{imax}
{i, imax}
Iterator notation.
local parameters
local constants
local variables
1043
When nested scoping constructs are evaluated, new symbols are automatically generated in the
inner scoping constructs so as to avoid name conflicts with symbols in outer scoping constructs.
In general, symbols with names of the form xxx are renamed xxx$.
When a transformation rule or definition is used, ReplaceAll (/.) is effectively used to replace the
pattern names that appear on the right-hand side. Nevertheless, new symbols are generated when
necessary to represent other objects that appear in scoping constructs on the right-hand side.
Each time it is evaluated, Module generates symbols with unique names of the form xxx$nnn as
replacements for all local variables that appear in its body.
1044
Numerical evaluation leads to results of a precision no higher than can be justified on the basis
of the precision of the arguments. Thus N[Gamma[27/10], 100] yields a high-precision result, but
N[Gamma[2.7], 100] cannot.
When possible, symbolic derivatives, integrals and series expansions of built-in mathematical functions are evaluated in terms of other built-in functions.
A.3.12 Protection
Mathematica allows you to make assignments that override the standard operation and meaning of
built-in Mathematica objects.
To make it difficult to make such assignments by mistake, most built-in Mathematica objects have
the attribute Protected . If you want to make an assignment for a built-in object, you must first
remove this attribute. You can do this by calling the function Unprotect .
There are a few fundamental Mathematica objects to which you absolutely cannot assign your own
values. These objects carry the attribute Locked, as well as Protected . The Locked attribute prevents
you from changing any of the attributes, and thus from removing the Protected attribute.
\\* etc.
Metacharacters used in string patterns.
literal *, etc.
A.4 Evaluation
1045
A.4 Evaluation
A.4.1 The Standard Evaluation Sequence
The following is the sequence of steps that Mathematica follows in evaluating an expression like
h[e , e , ... ]. Every time the expression changes, Mathematica effectively starts the evaluation sequence over again.
If the expression is a raw object (e.g., Integer , String, etc.), leave it unchanged.
Evaluate the head h of the expression.
Evaluate each element ei of the expression in turn. If h is a symbol with attributes HoldFirst ,
HoldRest , HoldAll or HoldAllComplete , then skip evaluation of certain elements.
Unless h has attribute HoldAllComplete strip the outermost of any Unevaluated wrappers that
appear in the ei .
Unless h has attribute SequenceHold , flatten out all Sequence objects that appear among the ei .
If h has attribute Flat, then flatten out all nested expressions with head h.
If h has attribute Listable , then thread through any ei that are lists.
If h has attribute Orderless , then sort the ei into order.
Unless h has attribute HoldAllComplete , use any applicable transformation rules associated with f
that you have defined for objects of the form h[ f [e , ... ], ... ].
Use any built-in transformation rules associated with f for objects of the form h[ f [e , ... ], ... ].
Use any applicable transformation rules that you have defined for h[e , e , ... ] or for
h[ ... ][ ... ].
Use any built-in transformation rules for h[e , e , ... ] or for h[ ... ][ ... ].
1046
Control structures
Conditionals
Logical operations
Iteration functions
Tracing functions
Assignments
Pure functions
Scoping constructs
Holding functions
Logical Operations
In an expression of the form e &&e &&e
the ei are evaluated in order. As soon as any ei is found to be
False, evaluation is stopped, and the result False is returned. This means that you can use the ei to
represent different branches in a program, with a particular branch being evaluated only if certain
conditions are met.
The Or function works much like And; it returns True as soon as it finds any argument that is True.
Xor, on the other hand, always evaluates all its arguments.
Iteration Functions
An iteration function such as Do[f, {i, imin, imax}] is evaluated as follows:
The iteration specification is evaluated. If it is not found to be of the form {i, imin, imax}, the
evaluation stops.
The value of the iteration variable i is made local, effectively using Block.
imin and imax are used to determine the sequence of values to be assigned to the iteration variable i.
A.4 Evaluation
1047
The iteration variable is successively set to each value, and f is evaluated in each case.
The local values assigned to i are cleared.
If there are several iteration variables, the same procedure is followed for each variable in turn, for
every value of all the preceding variables.
Unless otherwise specified, f is not evaluated until a specific value has been assigned to i, and is then
evaluated for each value of i chosen. You can use Evaluate[f] to make f be evaluated immediately,
rather than only after a specific value has been assigned to i.
Assignments
The left-hand sides of assignments are only partially evaluated.
If the left-hand side is a symbol, no evaluation is performed.
If the left-hand side is a function without hold attributes, the arguments of the function are
evaluated, but the function itself is not evaluated.
The right-hand side is evaluated for immediate (=), but not for delayed (:=), assignments.
Any subexpression of the form HoldPattern[expr] that appears on the left-hand side of an assignment is not evaluated, but is replaced by the unevaluated form of expr before the assignment is done.
By using Evaluate , you can get any argument of a function evaluated immediately, even if the
argument would usually be evaluated later under the control of the function.
1048
Hold[expr]
HoldComplete[expr]
HoldForm[expr]
HoldPattern[expr]
Unevaluated[expr]
Trace shows evaluation chains as lists, and shows subsidiary evaluations corresponding to recursion
in sublists.
The expressions associated with the sequence of subsidiary evaluations which lead to an expression
currently being evaluated are given in the list returned by Stack[ ].
$RecursionLimit
$IterationLimit
A.4.6 Aborts
You can ask Mathematica to abort at any point in a computation, either by calling the function Abort[ ],
or by typing appropriate interrupt keys.
When asked to abort, Mathematica will terminate the computation as quickly as possible. If the
answer obtained would be incorrect or incomplete, then Mathematica returns $Aborted instead of
giving that answer.
Aborts can be caught using CheckAbort , and can be postponed using AbortProtect .
1049
_
x_
x:pattern
pattern ? test
_h
x_h
__
___
Optional[x_h]
pattern..
pattern...
HoldPattern[pattern]
Verbatim[expr]
Pattern objects.
any expression
1050
When several pattern objects with the same name occur in a single pattern, all the objects must
stand for the same expression. Thus f[x_, x_] can stand for f[2, 2] but not f[2, 3].
In a pattern object such as _h, the head h can be any expression, but cannot itself be a pattern.
A pattern object such as x__ stands for a sequence of expressions. So, for example, f[x__] can stand
for f[a, b, c], with x being Sequence[a, b, c]. If you use x, say in the result of a transformation
rule, the sequence will be spliced into the function in which x appears. Thus g[u, x, u] would
become g[u, a, b, c, u].
When the pattern objects x_:v and x_. appear as arguments of functions, they represent arguments
which may be omitted. When the argument corresponding to x_:v is omitted, x is taken to have
value v. When the argument corresponding to x_. is omitted, x is taken to have a default value that
is associated with the function in which it appears. You can specify this default value by making
assignments for Default[f] and so on.
Default[f]
Default[f, n]
Default[f, n, tot]
default value for the nth argument when there are a total of
tot arguments
Default values.
A pattern like f[x__, y__, z__] can match an expression like f[a, b, c, d, e] with several different choices of x, y and z. The choices with x and y of minimum length are tried first. In general,
when there are multiple __ or ___ in a single function, the case that is tried first takes all the __ and
___ to stand for sequences of minimum length, except the last one, which stands for the rest of the
arguments.
When x_:v or x_. are present, the case that is tried first is the one in which none of them correspond
to omitted arguments. Cases in which later arguments are dropped are tried next.
Orderless
Flat
OneIdentity
Attributes used in matching patterns.
1051
Pattern objects like x_ can represent any sequence of arguments in a function f with attribute
Flat. The value of x in this case is f applied to the sequence of arguments. If f has the attribute
OneIdentity , then e is used instead of f [e] when x corresponds to a sequence of just one argument.
A.5.2 Assignments
lhs = rhs
lhs := rhs
Assignments in Mathematica specify transformation rules for expressions. Every assignment that you
make must be associated with a particular Mathematica symbol.
f [args] = rhs
f [g[args]] ^= rhs
In the case of an assignment like f [args] = rhs, Mathematica looks at f, then the head of f, then the
head of that, and so on, until it finds a symbol with which to associate the assignment.
When you make an assignment like lhs ^= rhs, Mathematica will set up transformation rules associated with each distinct symbol that occurs either as an argument of lhs, or as the head of an argument
of lhs.
The transformation rules associated with a particular symbol s are always stored in a definite
order, and are tested in that order when they are used. Each time you make an assignment, the
corresponding transformation rule is inserted at the end of the list of transformation rules associated
with s, except in the following cases:
The left-hand side of the transformation rule is identical to a transformation rule that has already
been stored, and any /; conditions on the right-hand side are also identical. In this case, the new
transformation rule is inserted in place of the old one.
Mathematica determines that the new transformation rule is more specific than a rule already present,
and would never be used if it were placed after this rule. In this case, the new rule is placed before
the old one. Note that in many cases it is not possible to determine whether one rule is more
specific than another; in such cases, the new rule is always inserted at the end.
1052
attributes of f
default values for arguments of f
values for f [... ], f [ ... ][ ... ], etc.
print forms associated with f
messages associated with f
NValues[f ]
Options[f ]
OwnValues[f ]
UpValues[f ]
Clear[s , s , ... ]
ClearAll[s , s , ... ]
Remove[s , s , ... ]
Clear, ClearAll and Remove can all take string patterns as arguments, to specify action on all symbols
whose names match the string pattern.
Clear, ClearAll and Remove do nothing to symbols with the attribute Protected .
Replacements for pattern variables that appear in transformation rules are effectively done using
ReplaceAll (the /. operator).
1053
name.nb
name.ma
name.mx
name.exe
name.tm
name.ml
Most files used by Mathematica are completely system independent. .mx and .exe files are however
system dependent. For these files, there is a convention that bundles of versions for different computer
systems have names with forms such as name/$SystemID/name.
In general, when you refer to a file, Mathematica tries to resolve its name as follows:
If the name starts with !, Mathematica treats the remainder of the name as an external command,
and uses a pipe to this command.
If the name contains metacharacters used by your operating system, then Mathematica passes the
name directly to the operating system for interpretation.
Unless the file is to be used for input, no further processing on the name is done.
Unless the name given is an absolute file name under your operating system, Mathematica will
search each of the directories specified in the list $Path .
If what is found is a directory rather than a file, then Mathematica will look for a file
name/$SystemID/name.
For names of the form name` the following further translations are done in Get and related
functions:
A file name.mx is used if it exists.
A file name.m is used if it exists.
1054
A.6.2 Streams
InputStream["name", n]
OutputStream["name", n]
Types of streams.
option name
default value
CharacterEncoding
$CharacterEncoding
encoding to use for special characters
DOSTextFormat
True
FormatType
InputForm
PageWidth
78
TotalWidth
Infinity
You can test options for streams using Options , and reset them using SetOptions .
1055
-pwpath
-run
-initfile
-initpath
-noinit
-mathlink
If the Mathematica front end is called with a notebook file as a command-line argument, then this
notebook will be made the initial selected notebook. Otherwise, a new notebook will be created for
this purpose.
Mathematica kernels and front ends can also take additional command-line options specific to
particular window environments.
$MATHINIT
$MATHKERNELINIT
-
$MATHEMATICA_BASE
$MATHEMATICA_USERBASE
Environment variables.
If no command-line options are explicitly given, Mathematica will read the values of operating
system environment variables, and will use these values like command lines.
1056
A.7.2 Initialization
On startup, the Mathematica kernel does the following:
Perform license management operations.
Run Mathematica commands specified in any -runfirst options passed to the kernel executable.
Run Mathematica commands specified in any -run options passed to the kernel executable.
Run the Mathematica commands in the user-specific kernel init.m file.
Run the Mathematica commands in the system-wide kernel init.m file.
Load init.m and Kernel/init.m files in Autoload directories.
Begin running the main loop.
1057
A.7.4 Messages
During a Mathematica session messages can be generated either by explicit calls to Message, or in the
course of executing other built-in functions.
f::name::lang
f::name
General::name
Message names.
If no language is specified for a particular message, text for the message is sought in each of
the languages specified by $Language . If f::name is not defined, a definition for General::name is
sought. If still no message is found, any value defined for $NewMessage is applied to f and "name".
Off[message] prevents a specified message from ever being printed. Check allows you to determine
whether particular messages were generated during the evaluation of an expression. $MessageList
and MessageList[n] record all the messages that were generated during the evaluation of a particular
line in a Mathematica session.
Messages are specified as strings to be used as the first argument of StringForm . $MessagePrePrint
is applied to each expression to be spliced into the string.
A.7.5 Termination
Exit[ ] or Quit[ ]
$Epilog
$IgnoreEOF
end.m
terminate Mathematica
symbol to evaluate before Mathematica exits
whether to exit an interactive Mathematica session when an
end-of-file character is received
file to read when Mathematica terminates
Mathematica termination.
There are several ways to end a Mathematica session. If you are using Mathematica interactively, typing
Exit[ ] or Quit[ ] on an input line will always terminate Mathematica.
If you are taking input for Mathematica from a file, Mathematica will exit when it reaches the end of
the file. If you are using Mathematica interactively, it will still exit if it receives an end-of-file character
(typically d ). You can stop Mathematica from doing this by setting $IgnoreEOF=True .
1058
network license
Copies of Mathematica can be set up with either single-machine or network licenses. A network license
is indicated by a line in the mathpass file starting with !name, where name is the name of the server
machine for the network license.
Network licenses are controlled by the Mathematica license management program mathlm. This
program must be running whenever a Mathematica with a network license is being used. Typically
you will want to set up your system so that mathlm is started whenever the system boots.
When mathlm is not started directly from a command line, it normally sets itself up as a background
process, and continues running until it is explicitly terminated. Note that if one mathlm process is
running, any other mathlm processes you try to start will automatically exit immediately.
1059
-logfile file
-pwfile file
-timeout n
-restrict file
-install
-uninstall file
-formatlog string
-localtime
-trfile file
-verbose n
-help
-logginglevel n
-trlang language
-noremotemonitor
You can use the mathlm -restrict file to tell the network license manager to authorize only certain
sessions. The detailed syntax of a restriction script is explained in the Network Mathematica System
Administrators Guide.
monitorlm
Monitoring network license activity.
1060
You can use the program monitorlm to get information on current Mathematica license activity on
your computer network.
-server name
-template file
-output file
-localtime
-format format
Command-line options for monitorlm.
1061
C:\ProgramFiles\WolframResearch\Mathematica\5.0
Windows
/Applications/Mathematica 5.0.app
Macintosh
/usr/local/mathematica
Unix
The executable programs that launch Mathematica are typically in the main installation directory.
Sometimes there may also be links to them, or scripts accessing them, in other locations. From
within a Mathematica kernel, First[$CommandLine] gives the full name of the executable program
corresponding to that kernel.
Mathematica
MathKernel
math
mcc
The main installation directory has three standard subdirectories that contain material distributed
with Mathematica. Under normal circumstances, none of the contents of these directories should ever
be modified, except, for example, if you choose to edit a shared style sheet.
1062
AddOns
Documentation
SystemFiles
Particularly on Unix systems, Mathematica often has executable files for different computer architectures and systems stored in a single overall directory structure. Each system is in a subdirectory
with a name given by $SystemID . Some resource directories may also contain files specific both to
particular languages and particular computing environments. These files are given in subdirectories
such as Japanese/Windows .
Kernel/Binaries/system
Kernel/SystemResources/system
Kernel/TextResources
FrontEnd/Binaries/system
FrontEnd/SystemResources
FrontEnd/TextResources
FrontEnd/StyleSheets
FrontEnd/Palettes
Libraries/system
Fonts
CharacterEncodings
SpellingDictionaries
SystemDocumentation/env
Graphics/Binaries/system
Graphics/SystemResources
Graphics/Packages
1063
Installation
IncludeFiles
Java
Bundled with versions of Mathematica are various standard add-on items. These are placed in the
AddOns subdirectory of the main installation directory.
StandardPackages
MathLink
JLink
NETLink
The default contents of the Mathematica Help Browser are stored in the Documentation directory. BrowserCategories files in each subdirectory set up the categories used in the Help Browser.
BrowserIndex files provide data for the master index.
RefGuide
MainBook
AddOns
GettingStarted
OtherInformation
1064
$BaseDirectory
$UserBaseDirectory
C:\DocumentsandSettings\AllUsers\ApplicationData\Mathematica
Windows
/Library/Mathematica
/usr/share/Mathematica
Macintosh
Unix
C:\DocumentsandSettings\username\ApplicationData\Mathematica
Windows
M/Library/Mathematica
M/.Mathematica
Macintosh
Unix
You can specify different locations for these directories by setting operating system environment
variables when you launch Mathematica, as discussed on page 1055.
Applications
Autoload
FrontEnd
Kernel
Licensing
SystemFiles
1065
Some files in base directories serve as configuration files, automatically used by the Mathematica
kernel or front end.
Kernel/init.m
Kernel/end.m
FrontEnd/init.m
SystemFiles/FrontEnd/StyleSheets/
customized notebook style sheets
SystemFiles/FrontEnd/Palettes/
additional palettes to appear in the front end menu
Some typical kernel and front end configuration files.
Kernel configuration files can contain any Mathematica commands. These commands can test global
variables such as $SystemID and $MachineName to determine what operations to perform. Front end
configuration files can contain only certain special commands, as described on page 1038.
Applications/name/
Autoload/name/
With the default setting for the kernel $Path variable, an add-on can be loaded from within a
Mathematica session simply by using the command <<name`. This will load the init.m file for the
add-on, which should in turn be set up to load other necessary files or packages.
By placing an add-on under the Autoload subdirectory of $BaseDirectory or $UserBaseDirectory ,
you can have Mathematica automatically load the add-on whenever you start the kernel or the front
end.
init.m or Kernel/init.m
FrontEnd/init.m
Documentation/
Note that with the default setting for the front end documentation path, all documentation in
Documentation directories will automatically show up in the front end Help Browser.
1066
1067
Random uses the Wolfram rule 30 cellular automaton generator for integers.
subtract-with-borrow generator for real numbers.
- Number-theoretical
It uses a Marsaglia-Zaman
functions
interleaves the HGCD algorithm, the Jebelean-Sorenson-Weber accelerated GCD algorithm, and a combination of
Euclids algorithm and an algorithm based on iterative removal of powers of 2.
PrimeQ first tests for divisibility using
small primes, then uses the Miller-Rabin strong pseudoprime test base 2 and base 3, and then uses a Lucas test.
As
of 1997, this procedure is known to be correct only for n ) , and it is conceivable that for larger n it could claim a
composite number to be prime.
The package NumberTheory`PrimeQ` contains a much slower algorithm which has
been proved correct for all n. It can return an explicit certificate of primality.
FactorInteger switches between trial
division, Pollard p , Pollard rho and quadratic sieve algorithms.
The package NumberTheory`FactorIntegerECM`
contains an elliptic curve algorithm suitable for factoring some very large integers.
Prime and PrimePi use sparse
caching and sieving. For large n, the Lagarias-Miller-Odlyzko algorithm for PrimePi is used, based on asymptotic
estimates of the density of primes, and is inverted to give Prime.
LatticeReduce uses the Lenstra-Lenstra-Lovasz
lattice reduction algorithm.
To find a requested number of terms ContinuedFraction uses a modification of Lehmers
indirect method, with a self-restarting divide-and-conquer algorithm to reduce the numerical precision required at each
step.
ContinuedFraction uses recurrence relations to find periodic continued fractions for quadratic irrationals.
FromContinuedFraction uses iterated matrix multiplication optimized by a divide-and-conquer method.
- GCD
Combinatorial functions
Pi
1068
Special functions
For machine precision most special functions use Mathematica-derived rational minimax approximations. The notes that
follow apply mainly to arbitrary precision.
Orthogonal polynomials use stable recursion formulas for polynomial cases
and hypergeometric functions in general.
Gamma uses recursion, functional equations and the Binet asymptotic
formula.
Incomplete gamma and beta functions use hypergeometric series and continued fractions.
PolyGamma uses
Euler-Maclaurin summation, functional equations and recursion.
PolyLog uses Euler-Maclaurin summation, expansions
Zeta and related functions use Euler-Maclaurin
in terms of incomplete gamma functions and numerical quadrature.
summation and functional equations. Near the critical strip they also use the Riemann-Siegel formula.
StieltjesGamma uses Keipers algorithm based on numerical quadrature of an integral representation of the zeta
function.
The error function and functions related to exponential integrals are all evaluated using incomplete gamma
functions.
The inverse error functions use binomial search and a high-order generalized Newtons method.
Bessel
functions use series and asymptotic expansions. For integer orders, some also use stable forward recursion.
The
hypergeometric functions use functional equations, stable recurrence relations, series expansions and asymptotic series.
Methods from NSum and NIntegrate are also sometimes used.
ProductLog uses high-order Newtons method starting
Elliptic integrals are evaluated using the descending Gauss
from rational approximations and asymptotic expansions.
transformation.
Elliptic theta functions use series summation with recursive evaluation of series terms.
Other
elliptic functions mostly use arithmetic-geometric mean methods.
Mathieu functions use Fourier series. The Mathieu
characteristic functions use generalizations of Blanchs Newton method.
Numerical integration
With Method->Automatic , NIntegrate uses GaussKronrod in one dimension, and MultiDimensional otherwise.
If an
explicit setting for MaxPoints is given, NIntegrate by default uses Method->QuasiMonteCarlo .
GaussKronrod:
adaptive Gaussian quadrature with error estimation based on evaluation at Kronrod points.
DoubleExponential :
Trapezoidal: elementary trapezoidal method. Oscillatory:
non-adaptive double-exponential quadrature.
transformation to handle certain integrals containing trigonometric and Bessel functions.
MultiDimensional : adaptive
Genz-Malik algorithm.
MonteCarlo: non-adaptive Monte Carlo.
QuasiMonteCarlo : non-adaptive
Halton-Hammersley-Wozniakowski algorithm.
Numerical sums and products
If the ratio test does not give 1, the Wynn epsilon algorithm is applied to a sequence of partial sums or products.
Otherwise Euler-Maclaurin summation is used with Integrate or NIntegrate.
Numerical differential equations
For ordinary differential equations, NDSolve by default uses an LSODA approach, switching between a non-stiff Adams
method and a stiff Gear backward differentiation formula method.
For linear boundary value problems the
Gelfand-Lokutsiyevskii chasing method is used.
Differential-algebraic equations use IDA, based on repeated BDF and
Newton iteration methods.
For n -dimensional PDEs the method of lines is used.
NDSolve supports explicit
Method settings that cover most known methods from the literature.
The code for NDSolve and related functions is
about 1400 pages long.
Approximate equation solving and optimization
Polynomial root finding is done based on the Jenkins-Traub algorithm.
For sparse linear systems, Solve and NSolve
use several efficient numerical methods, mostly based on Gauss factoring with Markowitz products (approximately 250
pages of code).
For systems of algebraic equations, NSolve computes a numerical Grobner
1069
Data manipulation
Fourier uses the FFT algorithm with decomposition of the length into prime factors. When the prime factors are large,
fast convolution methods are used to maintain On logn asymptotic complexity.
For real input, Fourier uses a real
transform method.
ListConvolve and ListCorrelate use FFT algorithms when possible. For exact integer inputs,
enough digits are computed to deduce exact integer results.
InterpolatingFunction uses divided differences to
construct Lagrange or Hermite interpolating polynomials.
Fit works using singular value decomposition. FindFit
uses the same method for the linear least-squares case, the Levenberg-Marquardt method for nonlinear least-squares,
CellularAutomaton uses bit-packed parallel operations with bit
and general FindMinimum methods for other norms.
slicing. For elementary rules, absolutely optimal Boolean functions are used, while for totalistic rules,
just-in-time-compiled bit-packed tables are used. In two dimensions, sparse bit-packed arrays are used when possible,
with only active clusters updated.
Approximate numerical linear algebra
Machine-precision matrices are typically converted to a special internal representation for processing.
SparseArray
with rules involving patterns uses cylindrical algebraic decomposition to find connected array components. Sparse arrays
For dense arrays,
are stored internally using compressed sparse row formats, generalized for tensors of arbitrary rank.
LAPACK algorithms extended for arbitrary precision are used when appropriate.
BLAS technology is used to optimize
for particular machine architectures.
LUDecomposition , Inverse, RowReduce and Det use Gaussian elimination with
partial pivoting. LinearSolve uses the same methods, together with iterative improvement for high-precision numbers.
For sparse arrays, LinearSolve uses UMFPACK multifrontal direct solver methods and with Method->"Krylov" uses
Krylov iterative methods preconditioned by an incomplete LU factorization.Eigenvalues and Eigenvectors use
ARPACK Arnoldi methods.
SingularValueDecomposition uses the QR algorithm with Givens rotations.
PseudoInverse, NullSpace and MatrixRank are based on SingularValueDecomposition .
QRDecomposition uses
SchurDecomposition uses QR iteration.
MatrixExp uses Schur decomposition.
Householder transformations.
Exact numerical linear algebra
Inverse and LinearSolve use efficient row reduction based on numerical approximation.
With Modulus->n, modular
Gaussian elimination is used.
Det uses modular methods and row reduction, constructing a result using the Chinese
Remainder Theorem.
Eigenvalues works by interpolating the characteristic polynomial.
MatrixExp uses Putzers
method or Jordan decomposition.
1070
- Exact
For linear equations Gaussian elimination and other methods of linear algebra are used.
Root objects representing
algebraic numbers are usually isolated and manipulated using validated numerical methods. With
ExactRootIsolation->True , Root uses for real roots a continued fraction version of an algorithm based on Descartes
rule of signs, and for complex roots the Collins-Krandick algorithm.
For single polynomial equations, Solve uses
explicit formulas up to degree four, attempts to reduce polynomials using Factor and Decompose, and recognizes
For systems of polynomial equations, Solve constructs a Grobner
basis.
cyclotomic and other special polynomials.
Solve and GroebnerBasis use an efficient version of the Buchberger algorithm.
For non-polynomial equations,
Solve attempts to change variables and add polynomial side conditions.
The code for Solve and related functions is
about 500 pages long. - For polynomial systems Reduce uses cylindrical algebraic decomposition for real domains and
Grobner
bases over prime fields for polynomial equations. For composite moduli, it uses Hermite normal form and
Grobner
optimization
, For
linear cases, Minimize and Maximize use exact linear programming methods. For polynomial cases they use
cylindrical algebraic decomposition.
- Simplification
FullSimplify automatically applies about 40 types of general algebraic transformations, as well as about 400 types of
rules for specific mathematical functions.
Generalized hypergeometric functions are simplified using about 70 pages of
Mathematica transformation rules. These functions are fundamental to many calculus operations in Mathematica.
FunctionExpand uses an extension of Gausss algorithm to expand trigonometric functions with arguments that are
rational multiples of .
Simplify and FullSimplify cache results when appropriate. - When assumptions specify
that variables are real, polynomial constraints are handled by cylindrical algebraic decomposition, while linear
constraints are handled by the simplex algorithm or Loos-Weispfenning linear quantifier elimination. For strict
polynomial inequalities, Strzebonskis generic CAD algorithm is used.
When assumptions involve equations among
polynomials, Grobner
- Differential
1071
equations
Systems of linear equations with constant coefficients are solved using matrix exponentiation.
Second-order linear
equations with variable coefficients whose solutions can be expressed in terms of elementary functions and their
integrals are solved using the Kovacic algorithm.
Higher-order linear equations are solved using Abramov and
Bronstein algorithms.
Systems of linear equations with rational function coefficients whose solutions can be given as
rational functions are solved using Abramov-Bronstein elimination algorithms.
Linear equations with polynomial
When possible, nonlinear equations
coefficients are solved in terms of special functions by using Mellin transforms.
are solved by symmetry reduction techniques. For first-order equations classical techniques are used; for second-order
equations and systems integrating factor and Bocharov techniques are used.
The algorithms in Mathematica cover most
of the ordinary differential equations in standard reference books such as Kamke.
For partial differential equations,
separation of variables and symmetry reduction are used. - For differential-algebraic equations, a method based on
isolating singular parts by core nilpotent decomposition is used.
DSolve uses about 300 pages of Mathematica code
and 200 pages of C code.
Sums and products
Polynomial series are summed using Bernoulli and Euler polynomials.
Series involving rational and factorial functions
are summed using Adamchik techniques in terms of generalized hypergeometric functions, which are then simplified.
Series involving polygamma functions are summed using integral representations.
Dirichlet and related series are
summed using pattern matching.
For infinite series, dAlembert and Raabe convergence tests are used.
The
algorithms in Mathematica cover at least 90% of the sums in standard reference books such as Gradshteyn-Ryzhik.
Products are done primarily using pattern matching.
Sum and Product use about 100 pages of Mathematica code.
Series and limits
Series works by recursively composing series expansions of functions with series expansions of their arguments.
Limits are found from series and using other methods.
, Recurrence
equations
solves systems of linear equations with constant coefficients using matrix powers. , Linear equations with
polynomial coefficients whose solutions can be given as hypergeometric terms are solved using van Hoeij algorithms.
, Systems of linear equations with rational function coefficients whose solutions can be given as rational functions are
solved using Abramov-Bronstein elimination algorithms. , Nonlinear equations are solved by transformation of
variables, Gokta
s symmetry reduction methods or Germundsson trigonometric power methods. , The algorithms in
Mathematica cover most of the ordinary and q-difference equations ever discussed in the mathematical literature. , For
difference-algebraic equations, a method based on isolating singular parts by core nilpotent decomposition is used.
, RSolve
1072
1073
object or feature whose functionality was extensively changed since Version 4.0
New in Version ... indicates in what version of Mathematica a function first appeared.
Modified in Version ... indicates in what version substantial changes of functionality were last made.
The internal code of Mathematica is continually improved and enhanced, and between each major
version the code for a great many built-in functions is modified in some way or another. So even if an
object is not indicated by , , - or Modified in ... in this listing, it may well have been substantially
enhanced in its efficiency or in the quality of results it gives.
This listing includes only standard built-in Mathematica objects that reside in the System` context.
In a typical version of Mathematica there may be additional objects present both in the System` context,
as well as in the Developer` and Experimental` contexts. For production work it is best to use only
documented objects in the System` context, since the specifications of other objects may change in
future versions. The online documentation for your version of Mathematica may contain information
on Developer` and Experimental` objects. Further information is available at the Wolfram Research
website.
1074
System`
Developer`
Experimental`
In many versions of Mathematica, you can access the text given in this section directly, typically
using the Help Browser (see page 57). Typing ?F to the Mathematica kernel will also give you the
main description of the object F from this section.
More information on related packages mentioned in this listing can be found using the Help
Browser, or by looking at Standard Add-on Packages published by Wolfram Research. Note that the
specifications of functions in packages are subject to incompatible changes in future versions of
Mathematica.
There are a total of 1226 objects in this listing.
Note that for items modified in Version 5 this listing makes no distinction between those new in
Version 3 and those not.
Abort AbsoluteOptions
1075
Abort
Abort[ ] generates an interrupt to abort a computation.
You can call Abort anywhere within a computation. It has the same effect as an interactive interrupt in which you
select the abort option. You can use Abort as an emergency stop in a computation. Once Abort has been
called, Mathematica functions currently being evaluated return as quickly as possible. In an interactive session, the
final result from an aborted computation is $Aborted. You can use CheckAbort to catch returns from an abort.
See page 371. See also: Throw, TimeConstrained , MemoryConstrained , Return. New in Version 2.
AbortProtect
AbortProtect[expr] evaluates expr, saving any aborts until the evaluation is complete.
Aborts that are generated during an AbortProtect take effect as soon as the execution of the AbortProtect is
over. CheckAbort can be used inside AbortProtect to catch and absorb any aborts that occur. AbortProtect
also protects against aborts generated by TimeConstrained and MemoryConstrained . See page 371. New in
Version 2.
Abs
Abs[z] gives the absolute value of the real or complex number z.
For complex numbers z, Abs[z] gives the modulus /z/. Abs[z] is left unevaluated if z is not a numeric quantity.
See pages 745 and 746. See also: Re, Im, Arg, Mod, ComplexExpand, Norm. New in Version 1.
AbsoluteDashing
AbsoluteDashing[{d , d , ... }] is a graphics directive which specifies that lines which
follow are to be drawn dashed, with successive segments having absolute lengths d , d , ...
(repeated cyclically).
The absolute lengths are measured in units of printers points, approximately equal to
of an inch.
AbsoluteDashing[{ }] specifies that lines should be solid. AbsoluteDashing can be used in both two- and
three-dimensional graphics. See page 501. See also: AbsoluteThickness , Offset, Thickness, GrayLevel, Hue,
RGBColor. New in Version 2.
AbsoluteOptions
AbsoluteOptions[expr] gives the absolute settings of options specified in an expression such
as a graphics object.
AbsoluteOptions[expr, name] gives the absolute setting for the option name.
AbsoluteOptions[expr, {name , name , ... }] gives a list of the absolute settings for the
options namei .
AbsoluteOptions[object] gives the absolute settings for options associated with an external
object such as a NotebookObject .
AbsoluteOptions gives the actual settings for options used internally by Mathematica when the setting given is
Automatic or All. AbsoluteOptions returns lists of rules, just like Options. You can use AbsoluteOptions on
graphics options such as PlotRange and Ticks. If you ask for AbsoluteOptions[NotebookObject[. . . ], name]
the kernel will send a request to the front end to find the result. See pages 145 and 490. See also: Options,
FullGraphics. Related package: Utilities`FilterOptions` . New in Version 4.
AbsolutePointSize AccountingForm
1076
AbsolutePointSize
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.
The absolute diameter is measured in units of printers points, approximately equal to
of an inch.
AbsolutePointSize can be used in both two- and three-dimensional graphics. See page 500. See also: Offset,
PointSize, AbsoluteThickness , Thickness. New in Version 2; modified in Version 3.
AbsoluteThickness
AbsoluteThickness[d] is a graphics directive which specifies that lines which follow are to be
drawn with absolute thickness d.
The absolute thickness is measured in units of printers points, approximately equal to
of an inch.
AbsoluteThickness can be used in both two- and three-dimensional graphics. See page 501. See also: Offset,
AbsoluteDashing , AbsolutePointSize , PointSize, Dashing. New in Version 2.
AbsoluteTime
AbsoluteTime[ ] gives the total number of seconds since the beginning of January 1, 1900, in
your time zone.
AbsoluteTime[ ] uses whatever date and time have been set on your computer system. It performs no corrections
for time zones, daylight saving time, etc. AbsoluteTime[z] gives the result for time zone z. This is inferred by
knowing your local date and time, and local time zone. The time zone is given as the number of hours to be
added to Greenwich mean time to obtain local time. - AbsoluteTime[ ] is always accurate down to a granularity
of $TimeUnit seconds, but on many systems is much more accurate. There are 2208988800 seconds from the
beginning of January 1, 1900 to the beginning of January 1, 1970 and 2840140800 seconds to the beginning of
January 1, 1990. See page 710. See also: Date, SessionTime, TimeUsed, AbsoluteTiming , Timing, TimeZone,
ToDate, FromDate. Related package: Miscellaneous`Calendar` . New in Version 2.
,
AbsoluteTiming
AbsoluteTiming[expr] evaluates expr, returning a list of the absolute time that has elapsed,
together with the result obtained.
AbsoluteTiming gives the absolute number of seconds of real time that have elapsed, multiplied by the symbol
Second. AbsoluteTiming has attribute HoldAll. AbsoluteTiming[expr;] will give {timing, Null}.
First[AbsoluteTiming[expr;]] /. Second->1 yields just the number of seconds of time elapsed in the
evaluation of expr. AbsoluteTiming is always accurate down to a granularity of $TimeUnit seconds, but on many
systems is much more accurate. See page 711. See also: Timing, TimeConstrained , SessionTime, AbsoluteTime.
New in Version 5.0.
AccountingForm
AccountingForm[expr] prints with all numbers in expr given in standard accounting notation.
AccountingForm[expr, n] prints with numbers given to n-digit precision.
AccountingForm never uses scientific notation. AccountingForm uses parentheses to indicate negative numbers.
AccountingForm takes the same options as NumberForm, but uses a different default function for
ExponentFunction , and a different default for NumberSigns. AccountingForm acts as a wrapper, which affects
printing, but not evaluation. See page 435. See also: PaddedForm, NumberForm. New in Version 2.
Accuracy AddTo
1077
Accuracy
Accuracy[x] gives the effective number of digits to the right of the decimal point in the
number x.
Accuracy[x] gives a measure of the absolute uncertainty in the value of x. , With uncertainty dx, Accuracy[x]
is -Log[10, dx]. For exact numbers such as integers, Accuracy[x] is Infinity. - Accuracy[x] does not
normally yield an integer result, and need not be positive. - For machine-precision numbers, Accuracy[x] gives
the same as $MachinePrecision - Log[10, Abs[x]]. , Accuracy[0.] is Log[10, $MinMachineNumber] .
, Numbers entered in the form digits``a are taken to have accuracy a.
If x is not a number, Accuracy[x] gives
the minimum value of Accuracy for all the numbers that appear in x. See page 727. See also: Precision, N,
Chop, SetAccuracy. New in Version 1; modified in Version 5.0.
,
AccuracyGoal
AccuracyGoal is an option for various numerical operations which specifies how many
effective digits of accuracy should be sought in the final result.
AccuracyGoal is an option for such functions as NIntegrate, NDSolve and FindRoot.
- AccuracyGoal -> Automatic normally yields an accuracy goal equal to half the setting for WorkingPrecision .
AccuracyGoal -> Infinity specifies that accuracy should not be used as the criterion for terminating the
numerical procedure. PrecisionGoal is typically used in this case. Even though you may specify
AccuracyGoal->n, the results you get may sometimes have much less than n-digit accuracy. In most cases, you
must set WorkingPrecision to be at least as large as AccuracyGoal. AccuracyGoal effectively specifies the
absolute error allowed in a numerical procedure. With AccuracyGoal->a and PrecisionGoal->p, Mathematica
attempts to make the numerical error in a result of size x be less than a /x/p . See page 976. See also:
PrecisionGoal, WorkingPrecision . New in Version 1; modified in Version 5.0.
Active
Active is an option for ButtonBox , Cell and Notebook which specifies whether a button
should be active.
With Active->False the contents of a button can be edited. With Active->True a button will perform an action
when it is clicked. Active cells are indicated by an A in their cell bracket. See page 607. See also:
ButtonStyle, Evaluator. New in Version 3.
AddTo
x += dx adds dx to x and returns the new value of x.
AddTo has the attribute HoldFirst. x += dx is equivalent to x = x + dx.
PreIncrement, Set, PrependTo. New in Version 1.
AdjustmentBox AiryBiPrime
1078
AdjustmentBox
AdjustmentBox[box, opts] displays with the placement of box adjusted using the options
given.
In the notebook front end, AdjustmentBox objects can typically be inserted and modified using a , ,
b and c . These keys move your current selection by one pixel at the current screen magnification. The
following options can be given:
BoxMargins
BoxBaselineShift
Horizontal motion specifications are in ems; vertical ones in x-heights. Motion specifications can be either
positive or negative numbers. Positive margin specifications increase the spacing around box; negative ones
decrease it. Moving the baseline affects for example vertical alignment in a RowBox. Top and bottom margins
affect for example placement in a FractionBox or an OverscriptBox. In StandardForm and InputForm input,
AdjustmentBox is by default ignored, so that AdjustmentBox[box, opts] is interpreted just as box would be.
Inserting an explicit spacing character such as \[ThinSpace] can have the same effect for display as
AdjustmentBox, but the spacing character by default affects interpretation. AdjustmentBox[box, opts] uses the
options given only to adjust the position of box itself. Unlike StyleBox, it does not propagate the options to
subboxes. See page 455. See also: StyleBox, GridBox, ScriptBaselineShifts . New in Version 3.
AiryAi
AiryAi[z] gives the Airy function Aiz.
Mathematical function (see Section A.3.10). The Airy function Aiz is a solution to the differential equation
y$$ xy . Aiz tends to zero as z # . AiryAi[z] is an entire function of z with no branch cut
discontinuities. See page 775. See also: AiryAiPrime, AiryBi, AiryBiPrime. New in Version 1.
AiryAiPrime
AiryAiPrime[z] gives the derivative of the Airy function Ai$ z.
Mathematical function (see Section A.3.10).
AiryBiPrime. New in Version 2.
AiryBi
AiryBi[z] gives the Airy function Biz.
Mathematical function (see Section A.3.10). The Airy function Biz is a solution to the differential equation
y$$ xy . Biz increases exponentially as z # . AiryBi[z] is an entire function of z with no branch cut
discontinuities. See page 775. See also: AiryAi, AiryBiPrime. New in Version 2.
AiryBiPrime
AiryBiPrime[z] gives the derivative of the Airy function Bi$ z.
Mathematical function (see Section A.3.10).
AiryAiPrime. New in Version 2.
Algebraics And
1079
Algebraics
Algebraics represents the domain of algebraic numbers, as in x Algebraics .
Algebraic numbers are defined to be numbers that solve polynomial equations with rational coefficients.
x Algebraics evaluates immediately only for quantities x that are explicitly constructed from rational numbers,
radicals and Root objects, or are known to be transcendental. Simplify[expr Algebraics] can be used to try to
determine whether an expression corresponds to an algebraic number. Algebraics is output in TraditionalForm
as . See page 817. See also: Element, Simplify, Integers, Root, Extension, Reals. New in Version 4.
All
All is a setting used for certain options.
In Part and related functions, All specifies all parts at a particular level.
For example, PlotRange -> All specifies that all points are to be included in a plot.
Automatic, None, Part. New in Version 1; modified in Version 4.0.
See also:
Alternatives
p | p | ... is a pattern object which represents any of the patterns pi .
Example: _Integer | _Real represents an object with head either Integer or Real. Unless the same set of
pattern names appears in all of the pi , you cannot use these pattern names on the right-hand side of transformation
rules for the pattern. Thus, for example, you can use x in a[x_] | b[x_], but you can use neither x nor y in
a[x_] | b[y_]. See page 269. See also: Optional. New in Version 2.
AmbientLight
AmbientLight is an option for Graphics3D and related functions that gives the level of
simulated ambient illumination in a three-dimensional picture.
The setting for AmbientLight must be a GrayLevel, Hue or RGBColor directive.
Lighting, LightSources , SurfaceColor. New in Version 1.
See also:
AnchoredSearch
AnchoredSearch is an option for Find and FindList which specifies whether the text
searched for must be at the beginning of a record.
With the default setting RecordSeparators -> {"\n"}, AnchoredSearch -> True specifies that the text must
appear at the beginning of a line. See page 651. New in Version 2.
And
e && e && ... is the logical AND function. It evaluates its arguments in order, giving False
immediately if any of them are False, and True if they are all True.
And[e , e , . . . ] can be input in StandardForm and InputForm as e e . . . . The character can be entered as
, && ,, , and , or \[And]. And evaluates its arguments in a non-standard way (see page 1046). And gives symbolic
results when necessary, removing initial arguments that are True. See page 87. See also: LogicalExpand,
BitAnd, Nand. New in Version 1; modified in Version 3.
AnimationDirection Append
1080
AnimationDirection
AnimationDirection is an option for Cell which specifies the direction to run an animation
which starts with the cell.
The setting AnimationDirection->Forward specifies that the animation should run through successive selected
graphics cells in the order that they appear in the notebook, and should then start again at the first cell.
AnimationDirection->Backward specifies that the reverse order should be used.
AnimationDirection->ForwardBackward specifies that the animation should run from the first cell to the last,
and should then reverse back to the first cell again. It is the setting of AnimationDirection for the first graphics
cell in the sequence selected that determines the animation direction for the whole sequence. See page 617. See
also: AnimationDisplayTime . New in Version 3.
AnimationDisplayTime
AnimationDisplayTime is an option for Cell which specifies the minimum time in seconds
for which a cell should be displayed in the course of an animation.
The default setting of AnimationDisplayTime->0.1 specifies that the animation should be run as fast as your
computer can. See page 617. See also: AnimationDirection . New in Version 3.
Apart
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.
Example: Apart[(x^2+1)/(x-1)] # 1 2 1 x x . Apart gives the partial fraction decomposition of a
rational expression. Apart[expr, var] writes expr as a polynomial in var together with a sum of ratios of
polynomials, where the degree in var of each numerator polynomial is less than that of the corresponding
denominator polynomial. Apart[(x + y)/(x - y), x] # 1 2 [ y x y .
Apart[(x + y)/(x - y), y] # 1 2 [ x x y . Apart[expr, Trig -> True] treats trigonometric
functions as rational functions of exponentials, and manipulates them accordingly. See page 802. See also:
Together, Cancel, PolynomialQuotient . New in Version 1.
AppellF1
AppellF1[a, b , b , c, x, y] is the Appell hypergeometric function of two variables
F ag b b g cg x y.
Mathematical function (see Section A.3.10). F ag b b g cg x y has series expansion
m n
F ag b b g cg x y reduces to F a bg cg z when x or y .
m n amn b m b n mdndcmn x y .
AppellF1[a, b , b , c, x, y] has singular lines in two-variable complex x y space at Rex and Rey ,
and has branch cut discontinuities along the rays from to in x and y. FullSimplify and FunctionExpand
include transformation rules for AppellF1. See page 780. See also: Hypergeometric2F1 . New in Version 4.
Append
Append[expr, elem] gives expr with elem appended.
Examples: Append[{a,b}, c] # a, b, c ; Append[f[a], b+c] # f
a, b c . - In iteratively building a list,
it is usually more efficient to use Sow and Reap than to use Append[list, new] at each step. , Append works on
SparseArray objects, returning ordinary lists if necessary. See pages 125 and 288. See also: Prepend, Insert,
AppendTo, PadRight, Sow. New in Version 1.
AppendTo ArcCsc
1081
AppendTo
AppendTo[s, elem] appends elem to the value of s, and resets s to the result.
AppendTo[s, elem] is equivalent to s = Append[s, elem]. AppendTo[s, elem] does not evaluate s. - You can use
AppendTo repeatedly to build up a list, though Sow and Reap will usually be more efficient. , AppendTo works on
SparseArray objects, returning ordinary lists if necessary. See page 306. See also: PrependTo, Sow. New in
Version 1.
Apply
Apply[f, expr] or f @@ expr replaces the head of expr by f.
Apply[f, expr, levelspec] replaces heads in parts of expr specified by levelspec.
Examples: Apply[f, {a, b, c}] # f
a, b, c ; Apply[Plus, g[a, b]] # a b . Level specifications are
described on page 1041. The default value for levelspec in Apply is {0}. f @@@ expr is equivalent to
Apply[f, expr, {1}]. Examples: Apply[f, {{a,b},{c,d}}] # f
a, b, c, d .
Apply[f, {{a,b},{c,d}}, {1}] # f
a, b, f
c, d . Apply[f, {{{{a}}}}, -2] # f
f
f
a .
, Apply operates on SparseArray objects just as it would on the corresponding ordinary lists.
See page 243.
See also: Map, Scan, Level, Operate, MapThread, Total. New in Version 1; modified in Version 4.0.
ArcCos
ArcCos[z] gives the arc cosine cos z of the complex number z.
Mathematical function (see Section A.3.10). All results are given in radians. For real z between and , the
results are always in the range to . ArcCos[z] has branch cut discontinuities in the complex z plane running
from to and to . See page 761. New in Version 1.
ArcCosh
ArcCosh[z] gives the inverse hyperbolic cosine cosh z of the complex number z.
Mathematical function (see Section A.3.10). ArcCosh[z] has a branch cut discontinuity in the complex z plane
running from to . See page 761. See also: ArcSech. New in Version 1.
ArcCot
ArcCot[z] gives the arc cotangent cot z of the complex number z.
Mathematical function (see Section A.3.10). All results are given in radians. For real z, the results are always in
the range to , excluding . ArcCot[z] has a branch cut discontinuity in the complex z plane running
from i to i. See page 761. New in Version 1.
ArcCoth
ArcCoth[z] gives the inverse hyperbolic cotangent coth z of the complex number z.
Mathematical function (see Section A.3.10). ArcCoth[z] has a branch cut discontinuity in the complex z plane
running from to . See page 761. New in Version 1.
ArcCsc
ArcCsc[z] gives the arc cosecant csc z of the complex number z.
Mathematical function (see Section A.3.10). All results are given in radians. For real z outside the interval to
, the results are always in the range to , excluding . ArcCsc[z] has a branch cut discontinuity in the
complex z plane running from to . See page 761. New in Version 1.
ArcCsch ArcTanh
1082
ArcCsch
ArcCsch[z] gives the inverse hyperbolic cosecant csch z of the complex number z.
Mathematical function (see Section A.3.10). ArcCsch[z] has a branch cut discontinuity in the complex z plane
running from i to i. See page 761. New in Version 1.
ArcSec
ArcSec[z] gives the arc secant sec z of the complex number z.
Mathematical function (see Section A.3.10). All results are given in radians. For real z outside the interval to
, the results are always in the range to , excluding . ArcSec[z] has a branch cut discontinuity in the
complex z plane running from to . See page 761. New in Version 1.
ArcSech
ArcSech[z] gives the inverse hyperbolic secant sech z of the complex number z.
Mathematical function (see Section A.3.10). ArcSech[z] has branch cut discontinuities in the complex z plane
running from to 0 and +1 to . See page 761. New in Version 1.
ArcSin
ArcSin[z] gives the arc sine sin z of the complex number z.
Mathematical function (see Section A.3.10). All results are given in radians. For real z between and , the
results are always in the range to . ArcSin[z] has branch cut discontinuities in the complex z plane
running from to and to . See page 761. New in Version 1.
ArcSinh
ArcSinh[z] gives the inverse hyperbolic sine sinh z of the complex number z.
Mathematical function (see Section A.3.10). ArcSinh[z] has branch cut discontinuities in the complex z plane
running from i to i and i to i. See page 761. See also: ArcCsch. New in Version 1.
ArcTan
ArcTan[z] gives the arc tangent tan z of the complex number z.
y
ArcTan[x, y] gives the arc tangent of x , taking into account which quadrant the point x y is
in.
Mathematical function (see Section A.3.10). All results are given in radians. For real z, the results are always in
the range to . ArcTan[z] has branch cut discontinuities in the complex z plane running from i to i
!
and i to i. If x or y is complex, then ArcTan[x, y] gives i log !x iy x y ". When x y ,
ArcTan[x, y] gives the number such that x cos and y sin . See page 761. See also: Arg. New in
Version 1.
ArcTanh
ArcTanh[z] gives the hyperbolic arc tangent tanh z of the complex number z.
Mathematical function (see Section A.3.10). See page 761. ArcTanh[z] has branch cut discontinuities in the
complex z plane running from to and to . See also: ArcCoth. New in Version 1.
Arg ArrayQ
1083
Arg
Arg[z] gives the argument of the complex number z.
Mathematical function (see Section A.3.10). Arg[z] is left unevaluated if z is not a numeric quantity. Arg[z]
gives the phase angle of z in radians. The result from Arg[z] is always between and . Arg[z] has a
branch cut discontinuity in the complex z plane running from to . See page 746. See also: ArcTan, Sign.
New in Version 1.
ArithmeticGeometricMean
ArithmeticGeometricMean[a, b] gives the arithmetic-geometric mean of a and b.
See page 788.
New in Version 1.
Array
Array[f, n] generates a list of length n, with elements f [i].
Array[f, {n , n , ... }] generates an n n array of nested lists, with elements
f [i , i , ... ].
Array[f, {n , n , ... }, {r , r , ... }] generates a list using the index origins ri (default 1).
Array[f, dims, origin, h] uses head h, rather than List, for each level of the array.
Examples: Array[f, 3] # f
1, f
2, f
3 .
Array[f, {2, 3}] # f
1, 1, f
1, 2, f
1, 3, f
2, 1, f
2, 2, f
2, 3 generates a
matrix.
Array[#1^#2 &, {2, 2}] # 1, 1, 2, 4 . Array[f, 3, 0] # f
0, f
1, f
2 generates an array
with index origin 0. Array[f, 3, 1, Plus] # f
1 f
2 f
3 . Note that the dimensions given to Array
are not in standard Mathematica iterator notation. See page 250. See also: Table, SparseArray. New in
Version 1; modified in Version 4.0.
,
ArrayDepth
- ArrayDepth[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, or is a SparseArray object.
ArrayQ
ArrayQ[expr] gives True if expr is a full array or a SparseArray object, and gives False
otherwise.
ArrayQ[expr, patt] requires expr to be a full array with a depth that matches the pattern patt.
ArrayQ[expr, patt, test] requires also that test yield True when applied to each of the array
elements in expr.
In a full array all parts at a particular level must be lists of the same length. ArrayQ[expr, 1|2] tests whether
expr is either a vector or a matrix. ArrayQ[expr, _, NumberQ] tests whether expr is a numerical array at all levels.
See page 290. See also: ArrayDepth, MatrixQ, VectorQ, Dimensions. New in Version 5.0.
ArrayRules Assumptions
1084
ArrayRules
ArrayRules[SparseArray[... ]] gives the rules {pos ->val , pos ->val , ... } specifying
elements in a sparse array.
ArrayRules[list] gives rules for SparseArray[list] .
The last element of ArrayRules[s] is always {_, _, . . . } -> def, where def is the default value for unspecified
elements in the sparse array. ArrayRules[list, val] takes the default value to be val. ArrayRules[list] assumes
a default value of 0. See page 922. See also: Position, Normal. New in Version 5.0.
AspectRatio
AspectRatio is an option for Show and related functions which specifies the ratio of height to
width for a plot.
AspectRatio determines the scaling for the final image shape. AspectRatio -> Automatic determines the ratio
of height to width from the actual coordinate values in the plot. The default value
AspectRatio -> 1/GoldenRatio is used for two-dimensional plots. AspectRatio -> Automatic is used for
three-dimensional plots. See page 509. See also: BoxRatios, PlotRegion. New in Version 1.
AspectRatioFixed
AspectRatioFixed is an option for Cell which specifies whether graphics in the cell should
be constrained to stay the same shape when they are interactively resized using the front end.
With AspectRatioFixed->False , the shape of an image is determined by the setting for ImageSize.
page 616. See also: ImageSize, AspectRatio. New in Version 3.
,
See
Assuming
Assuming[assum, expr] evaluates expr with assum appended to $Assumptions , so that assum is
included in the default assumptions used by functions such as Refine, Simplify and
Integrate .
Assuming affects the default assumptions for all functions that have an Assumptions option. The assumptions can
be equations, inequalities or domain specifications, or lists or logical combinations of these. Assumptions from
nested invocations of Assuming are combined. Assuming[assum, expr] is effectively equivalent to
Block[{$Assumptions = $Assumptions && assum}, expr]. Assuming converts lists of assumptions {a , a , . . . }
to a && a && . . . . See page 818. See also: Block, Module, Refine, Reduce. New in Version 5.0.
Assumptions
Assumptions is an option for functions such as Simplify , Refine and Integrate which
specifies default assumptions to be made about symbolic quantities.
, The default setting is Assumptions:>$Assumptions . - The assumptions can be equations, inequalities or
domain specifications, or lists or logical combinations of these. , Assuming modifies $Assumptions and so
modifies the value of default settings for Assumptions options. x Reals can be used to specify that x should
be treated as a real variable. See page 867. See also: Assuming, $Assumptions, GenerateConditions ,
Integrate, Refine, Limit. New in Version 3; modified in Version 5.0.
AtomQ Attributes
1085
AtomQ
AtomQ[expr] yields True if expr is an expression which cannot be divided into subexpressions,
and yields False otherwise.
You can use AtomQ in a recursive procedure to tell when you have reached the bottom of the tree corresponding to
an expression. - AtomQ gives True for symbols, numbers, strings and other raw objects, such as sparse arrays.
AtomQ gives True on any object whose subparts cannot be accessed using functions like Map. See page 268.
See also: NumberQ, Head, LeafCount, Length. New in Version 1; modified in Version 5.0.
Attributes
Attributes[symbol] gives the list of attributes for a symbol.
The attributes of a symbol can be set by assigning a value to Attributes[s]. If a single attribute is assigned, it
need not be in a list. Attributes[s] = {} clears all attributes of a symbol. Attributes[{s , s , . . . }] gives a
list of the attributes for each of the si . Attributes["str"] gives a list of the attributes for all symbols which
match the string pattern str. Attributes[HoldPattern[s]] is treated as equivalent to Attributes[s]. Attributes
for functions must be set before any definitions that involve the functions are given. The complete list of possible
attributes for a symbol f is:
Constant
Flat
HoldAll
HoldAllComplete
HoldFirst
HoldRest
Listable
Locked
NHoldAll
NHoldFirst
NHoldRest
NumericFunction
OneIdentity
Orderless
Protected
ReadProtected
SequenceHold
Stub
Temporary
See page 328.
AutoIndent Axes
1086
AutoIndent
AutoIndent is an option for Cell which specifies what automatic indentation should be done
at the beginning of a new line after an explicit return character has been entered.
Possible settings for AutoIndent are:
False
True
Automatic
do no indentation
indent the same as the previous line
indent according to the structure of the expression (default)
With AutoIndent->True , tabs or spaces used for indentation on the previous line are explicitly inserted at the
beginning of the new line. With AutoIndent->Automatic , line breaks are always indicated by an
IndentingNewLine character even if they were originally entered using ` or \[NewLine]. Indentation after an
\[IndentingNewLine] is automatically redone every time an expression is displayed. The amount of indentation
after an IndentingNewLine is determined by the settings for the LineIndent and LineIndentMaxFraction options.
See page 613. See also: LineIndent, ParagraphIndent, ShowAutoStyles. New in Version 3; modified in
Version 4.0.
AutoItalicWords
AutoItalicWords is an option for Cell which gives a list of words which should
automatically be put in italics when they are entered.
Typical settings for AutoItalicWords include "Mathematica" and "MathLink".
ordinary text strings, not elements of more general expressions. See page 613.
SingleLetterItalics . New in Version 3.
Automatic
Automatic represents an option value that is to be chosen automatically by a built-in function.
See page 136.
New in Version 1.
AutoSpacing
AutoSpacing is an option for StyleBox and Cell which specifies whether spaces between
successive characters should be adjusted automatically.
AutoSpacing->False leaves equal spaces between all characters. AutoSpacing->True inserts additional space
around lower-precedence operators. AutoSpacing->False is in effect automatically used inside ordinary strings
and comments. See page 454. See also: TextJustification . New in Version 3.
Axes
Axes is an option for graphics functions that specifies whether axes should be drawn.
Axes -> True draws all axes. Axes -> False draws no axes. Axes -> {False, True} draws a y axis but no x
axis in two dimensions. In two dimensions, axes are drawn to cross at the position specified by the option
AxesOrigin. In three dimensions, axes are drawn on the edges of the bounding box specified by the option
AxesEdge. See pages 511 and 549. See also: AxesLabel, Frame, GridLines, Boxed. New in Version 1.
AxesEdge Background
1087
AxesEdge
AxesEdge is an option for three-dimensional graphics functions that specifies on which edges
of the bounding box axes should be drawn.
AxesEdge->{{dir y , dirz }, {dirx , dirz }, {dirx , diry }} specifies on which three edges of the bounding box axes are
drawn. The diri must be either +1 or -1, and specify whether axes are drawn on the edge of the box with a larger
or smaller value of coordinate i, respectively. The default setting AxesEdge->Automatic chooses automatically on
which exposed box edges axes should be drawn. Any pair {diri , dirj } in the setting for AxesEdge can be
replaced by Automatic to specify that the position of the corresponding axis is to be chosen automatically. Any
pair {diri , dirj } can be replaced by None, in which case the corresponding axis will not be drawn. If you
explicitly specify on which edge to draw an axis, the axis will be drawn on that edge, whether or not the edge is
exposed with the view point you have chosen. See page 551. New in Version 2.
AxesLabel
AxesLabel is an option for graphics functions that specifies labels for axes.
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. By default, axes labels in two-dimensional graphics are placed at the ends of the axes. In
three-dimensional graphics, they are aligned with the middles of the axes. Any expression can be specified as a
label. It will be given in OutputForm. Arbitrary strings of text can be given as "text". See pages 512 and 552.
See also: PlotLabel, FrameLabel. New in Version 1.
AxesOrigin
AxesOrigin is an option for two-dimensional graphics functions which specifies where any
axes drawn should cross.
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. If the point {0, 0} is within, or close to, the
plotting region, then it is usually chosen as the axis origin. In contour and density plots,
AxesOrigin -> Automatic puts axes outside the plotting area. See page 512. New in Version 2.
AxesStyle
AxesStyle is an option for graphics functions which specifies how axes should be rendered.
AxesStyle can be used in both two- and three-dimensional graphics. 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. See pages 512
and 550. See also: Prolog, Epilog, PlotStyle, FrameStyle. New in Version 2.
Background
Background is an option which specifies the background color to use.
Background is an option for graphics functions, Text, Cell and ButtonBox. The setting for Background in
graphics functions must be a CMYKColor, GrayLevel, Hue or RGBColor directive. The default setting in graphics
functions is Background->Automatic , which produces a white background on most output devices. In Text,
Background->None draws no background rectangle around the text and Background->Automatic draws a
background rectangle in the same color as the background for the whole plot. In a cell, the background is used
only for the region inside any cell frame. See pages 504 and 604. See also: Prolog, DefaultColor, PlotRegion,
FontColor. New in Version 2; modified in Version 3.
BaseForm BesselJ
1088
BaseForm
BaseForm[expr, n] prints with the numbers in expr given in base n.
The maximum allowed base is 36. For bases larger than 10, additional digits are chosen from the letters az. You
can enter a number in an arbitrary base using base^^digits. When a number in an arbitrary base is given in
scientific notation, the exponent is still given in base 10. You can mix BaseForm with NumberForm and related
functions. BaseForm acts as a wrapper, which affects printing, but not evaluation. See pages 438 and 725.
See also: IntegerDigits, RealDigits. New in Version 1.
Begin
Begin["context`"] resets the current context.
Begin resets the value of $Context. The interpretation of symbol names depends on context. Begin thus affects
the parsing of input expressions. See page 398. See also: BeginPackage , End, $ContextPath. New in Version 1.
BeginPackage
BeginPackage["context`"] makes context` and System` the only active contexts.
BeginPackage["context`", {"need `", "need `", ... }] calls Needs on the needi .
BeginPackage is typically used at the beginning of a Mathematica package. BeginPackage resets the values of
both $Context and $ContextPath. The interpretation of symbol names depends on context. BeginPackage thus
affects the parsing of input expressions. See page 398. See also: EndPackage. New in Version 1.
BernoulliB
BernoulliB[n] gives the Bernoulli number Bn .
BernoulliB[n, x] gives the Bernoulli polynomial Bn x.
Mathematical function (see Section A.3.10). The Bernoulli polynomials satisfy the generating function relation
n
text et
The Bernoulli numbers are given by Bn Bn . See page 757. See also: EulerE.
n Bn xt nd.
New in Version 1.
BesselI
BesselI[n, z] gives the modified Bessel function of the first kind In z.
Mathematical function (see Section A.3.10). In z satisfies the differential equation z y$$ zy$ z n y .
BesselI[n, z] has a branch cut discontinuity in the complex z plane running from to . FullSimplify
and FunctionExpand include transformation rules for BesselI. See page 775. See also: BesselK, AiryBi,
BesselJ. New in Version 1.
BesselJ
BesselJ[n, z] gives the Bessel function of the first kind Jn z.
Mathematical function (see Section A.3.10). Jn z satisfies the differential equation z y$$ zy$ z n y .
BesselJ[n, z] has a branch cut discontinuity in the complex z plane running from to . FullSimplify
and FunctionExpand include transformation rules for BesselJ. See page 775. See also: BesselY, StruveH,
BesselK. Related package: NumericalMath`BesselZeros` . New in Version 1.
BesselK BitAnd
1089
BesselK
BesselK[n, z] gives the modified Bessel function of the second kind Kn z.
Mathematical function (see Section A.3.10). Kn z satisfies the differential equation z y$$ zy$ z n y .
BesselK[n, z] has a branch cut discontinuity in the complex z plane running from to . FullSimplify
and FunctionExpand include transformation rules for BesselK. See page 775. See also: BesselI, AiryAi,
BesselJ. New in Version 1.
BesselY
BesselY[n, z] gives the Bessel function of the second kind Yn z.
Mathematical function (see Section A.3.10). Yn z satisfies the differential equation z y$$ zy$ z n y .
BesselY[n, z] has a branch cut discontinuity in the complex z plane running from to . FullSimplify
and FunctionExpand include transformation rules for BesselY. See page 775. See also: BesselJ, StruveH,
BesselI. Related package: NumericalMath`BesselZeros` . New in Version 1.
Beta
Beta[a, b] gives the Euler beta function ha b.
Beta[z, a, b] gives the incomplete beta function hz a b.
Mathematical function (see Section A.3.10).
hz a b
z a
t
tb dt.
Beta[z, a, b] has a branch cut discontinuity in the complex z plane running from
z
Beta[z , z , a, b] gives the generalized incomplete beta function z t a tb dt. Note that the
arguments in the incomplete form of Beta are arranged differently from those in the incomplete form of Gamma.
In TraditionalForm, Beta is output using \[CapitalBeta] . See page 770. See also: BetaRegularized ,
InverseBetaRegularized . New in Version 1.
to .
BetaRegularized
BetaRegularized[z, a, b] gives the regularized incomplete beta function Iz a b.
Mathematical function (see Section A.3.10). For non-singular cases, Iz a b Bz a bBa b.
BetaRegularized[z , z , a, b] gives the generalized regularized incomplete beta function defined in
non-singular cases as Beta[z , z , a, b]/Beta[a, b]. Note that the arguments in BetaRegularized are arranged
differently from those in GammaRegularized . See page 770. See also: Beta, InverseBetaRegularized . New in
Version 2.
Binomial
Binomial[n, m] gives the binomial coefficient mn .
Integer mathematical function (see Section A.3.10). Binomial is evaluated symbolically when possible. Example:
Binomial[x+2, x] # 1 x [ 2 x 2 . In general, mn is defined by n m n m or
suitable limits of this. See page 757. Implementation notes: see page 1067. See also: Multinomial, Pochhammer.
New in Version 1.
BitAnd
BitAnd[n , n , ... ] gives the bitwise AND of the integers ni .
Integer mathematical function (see Section A.3.10). BitAnd[n , n , . . . ] yields the integer whose binary bit
representation has ones at positions where the binary bit representations of all of the ni have ones. For negative
integers BitAnd assumes a twos complement representation. See page 756. See also: BitOr, BitXor, BitNot,
And, IntegerDigits, DigitCount, CellularAutomaton . New in Version 4.
BitNot BlankNullSequence
1090
BitNot
BitNot[n] gives the bitwise NOT of the integer n.
Integer mathematical function (see Section A.3.10). BitNot[n] turns ones into zeros and vice versa in the binary
bit representation of n. Integers are assumed to be represented in twos complement form, with an unlimited
number of digits, so that BitNot[n] is simply equivalent to n. See page 756. See also: BitAnd, BitOr,
BitXor, Not. New in Version 4.
BitOr
BitOr[n , n , ... ] gives the bitwise OR of the integers ni .
Integer mathematical function (see Section A.3.10). BitOr[n , n , . . . ] yields the integer whose binary bit
representation has ones at positions where the binary bit representations of any of the ni have ones. For negative
integers BitOr assumes a twos complement representation. See page 756. See also: BitAnd, BitXor, BitNot, Or,
IntegerDigits, CellularAutomaton . New in Version 4.
BitXor
BitXor[n , n , ... ] gives the bitwise XOR of the integers ni .
Integer mathematical function (see Section A.3.10). BitXor[n , n , . . . ] yields the integer whose binary bit
representation has ones at positions where an odd number of the binary bit representations of the ni have ones.
For negative integers BitXor assumes a twos complement representation. See page 756. See also: BitAnd,
BitOr, BitNot, Xor, IntegerDigits, CellularAutomaton . New in Version 4.
Blank
_ or Blank[ ] is a pattern object that can stand for any Mathematica expression.
_h or Blank[h] can stand for any expression with head h.
The head h in _h cannot itself contain pattern objects.
New in Version 1.
BlankNullSequence
___ (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.
Blank sequences work slightly differently depending on whether or not the head of the expression in which they
appear is a symbol with the attribute Flat. Consider matching the pattern f [a , a , . . . , ___, c , . . . ] against
the expression f [a , a , . . . , b , . . . , c , . . . ]. If f is a symbol with attribute Flat, then the ___ will be taken to
stand for the expression f [b , . . . ]. If f is not a symbol with attribute Flat, then ___ will be taken to stand for the
sequence of expressions b , . . . . With a named pattern, such as x___, x can be used only as an element in an
expression. The sequence of expressions b , . . . is spliced in to replace x, thereby usually increasing the length of
the expression. If ___ matches a sequence of length more than one, then the sequence will be represented by a
Sequence object. In most uses of ___, however, the Sequence object will automatically be spliced into another
expression, and will never appear explicitly. See page 273. See also: Pattern, SlotSequence. New in Version 1.
BlankSequence BoxStyle
1091
BlankSequence
__ (two _ characters) or BlankSequence[ ] is a pattern object that can stand for any sequence
of one or more Mathematica expressions.
__h or BlankSequence[h] can stand for any sequence of one or more expressions, all of which
have head h.
See notes for BlankNullSequence .
New in Version 1.
Block
Block[{x, y, ... }, expr] specifies that expr is to be evaluated with local values for the
symbols x, y, ... .
Block[{x = x , ... }, expr] defines initial local values for x, ... .
Block allows you to set up an environment in which the values of variables can temporarily be changed. When
you execute a block, values assigned to x, y, . . . are cleared. When the execution of the block is finished, the
original values of these symbols are restored. Block affects only the values of symbols, not their names. Initial
values specified for x, y, . . . are evaluated before x, y, . . . are cleared. You can use Block[{vars}, body /; cond] as
the right-hand side of a transformation rule with a condition attached. Block has attribute HoldAll. Block
implements dynamic scoping of variables. Block is automatically used to localize values of iterators in iteration
constructs such as Do, Sum and Table. See page 389. See also: Module, With, CompoundExpression . New in
Version 1.
Booleans
Booleans represents the domain of booleans, as in x Booleans .
The domain of booleans is taken to consist of the symbols True and False. x Booleans evaluates immediately
if x is explicitly True or False. Simplify[expr Booleans] can be used to try to determine whether an
expression is boolean, with no undetermined variables. Boolean is output in TraditionalForm as . See
page 817. See also: Element, Simplify, True, False, Integers. New in Version 4.
Boxed
Boxed is an option for Graphics3D which specifies whether to draw the edges of the bounding
box in a three-dimensional picture.
Boxed -> True draws the box; Boxed -> False does not.
New in Version 1.
BoxRatios
BoxRatios is an option for Graphics3D and SurfaceGraphics which gives the ratios of side
lengths for the bounding box of the three-dimensional picture.
BoxRatios -> {sx , sy , sz } gives the side-length ratios.
New in Version 1.
BoxStyle
BoxStyle is an option for three-dimensional graphics functions which specifies how the
bounding box should be rendered.
BoxStyle can be set to a list of graphics directives such as Dashing, Thickness, GrayLevel and RGBColor.
pages 503 and 550. See also: AxesStyle, Prolog, Epilog, DisplayFunction. New in Version 2.
See
Break ButtonData
1092
Break
Break[ ] exits the nearest enclosing Do, For or While.
Break[ ] takes effect as soon as it is evaluated, even if it appears inside other functions. After a Break the value
Null is returned from the enclosing control structure. The function of Break can also be achieved using Throw
and Catch. See page 353. See also: Continue, Return, Goto, Abort. New in Version 1; modified in Version 3.
ButtonBox
ButtonBox[boxes] represents a button in a notebook, displaying boxes and performing an
action when it is clicked on.
The default action is to paste boxes at your current insertion point.
Other actions can be specified using options.
ButtonBox objects are used to implement palette buttons, hyperlinks and other active elements
in notebooks.
ButtonBox objects are active when either they or the cell that contains them has the option
Active->True .
When ButtonBox objects are active, they perform an action whenever they are clicked on. Otherwise, clicking on
them simply selects them or their contents. ButtonBox[boxes, ButtonStyle->"style"] takes the properties of the
ButtonBox from the specified style. The style for a ButtonBox can specify both its appearance and its action. The
following options affecting button appearance can be given:
Background
ButtonFrame
ButtonExpandable
ButtonMargins
ButtonMinHeight
Automatic
"Palette"
True
3.0
1.0
Active
ButtonData
ButtonEvaluator
ButtonFunction
ButtonNote
False
Null
None
(pasting function)
None
ButtonSource
Automatic
See
ButtonData
ButtonData is an option for ButtonBox which specifies the second argument to give to the
ButtonFunction for the button when the button is active and is clicked on.
The default is ButtonData->Automatic . ButtonData provides a convenient way to associate additional data with
a button that does not affect the display of the button. See page 597. See also: ButtonSource, ButtonNote,
ButtonStyle. New in Version 3.
ButtonEvaluator ButtonFunction
1093
ButtonEvaluator
ButtonEvaluator is an option for ButtonBox which specifies where the expression constructed
from ButtonFunction should be sent for evaluation.
The default setting is ButtonEvaluator->None .
None
Automatic
"name"
With ButtonEvaluator->Automatic the expression to be evaluated can contain any Mathematica objects. With
ButtonEvaluator->None the expression can contain only the specific notebook commands supported by the front
end. All these commands are in the context FrontEnd`. Expressions intended for processing purely by the front end
must be wrapped with FrontEndExecute . See page 597. See also: ButtonFunction, ButtonStyle,
SelectionEvaluate , ButtonNotebook . New in Version 3.
ButtonExpandable
ButtonExpandable is an option for ButtonBox which specifies whether the button should
expand to fill any GridBox position in which it appears.
The default setting is ButtonExpandable->True . This setting is usually used for all buttons that appear in
palettes. With ButtonExpandable->False the size of a button is determined purely by its contents, independent
of its environment. With ButtonExpandable->False , gutters will often be left between buttons in a GridBox.
See page 452. See also: ButtonMargins, ButtonMinHeight, TextJustification . New in Version 3.
ButtonFrame
ButtonFrame is an option for ButtonBox which specifies the type of frame to display around a
button.
Typical settings supported include:
"Palette"
"DialogBox"
None
a button in a palette
a button in a dialog box
no frame
Button frames generated by ButtonFrame are set up to follow the conventions for particular computer systems.
A button with a particular setting for ButtonFrame may look slightly different on different computer systems.
See page 452. See also: ButtonStyle, WindowFrame. New in Version 3.
ButtonFunction
ButtonFunction is an option for ButtonBox which specifies the function to execute when the
button is active and is clicked on.
The default setting for ButtonFunction causes the button to paste its contents at your current notebook selection.
ButtonFunction is used only with the setting Active->True either for the individual button, or for the cell
which contains it. With ButtonFunction->f the first argument supplied to f is specified by the setting for
ButtonSource, and the second argument by the setting for ButtonData. Standard Mathematica precedence rules
require parentheses in ButtonFunction->(body &). Settings for ButtonFunction are often inherited from button
styles via the ButtonStyle option. With the default setting ButtonEvaluator -> None the expression constructed
from the button function is sent to the front end for evaluation. See page 597. See also: ButtonEvaluator,
ButtonNote, NotebookApply, ButtonNotebook. New in Version 3.
ButtonMargins ButtonSource
1094
ButtonMargins
ButtonMargins is an option for ButtonBox which specifies how much space in printers points
to leave around the contents of a button when the button is displayed.
The default setting is ButtonMargins->3 .
in Version 3.
New
ButtonMinHeight
ButtonMinHeight is an option for ButtonBox which specifies the minimum total height in
units of font size that should be allowed for the button.
The default setting ButtonMinHeight->1 forces a button to have a total height which at least accommodates all the
characters in the current font. ButtonMinHeight->0 reduces the total height of a button as much as possible,
allowing buttons containing characters such as x and X to be different heights. See page 452. See also:
ButtonMargins, ButtonExpandable , RowMinHeight. New in Version 3.
ButtonNote
ButtonNote is an option for ButtonBox which specifies what should be displayed in the status
line of the current notebook window when the button is active and the cursor is placed on top
of it.
The default is to display whatever setting is given for ButtonData. Any expression can be specified as the setting
for ButtonNote, though most windows will only allow a single character height to be displayed. ButtonNote can
be used to display keyboard equivalents for buttons in a palette. See page 597. See also: ButtonData,
ButtonFunction , ButtonStyle. New in Version 3.
ButtonNotebook
ButtonNotebook[ ] gives the notebook, if any, that contains the button which initiated the
current evaluation.
ButtonNotebook returns a NotebookObject. If a button in a palette initiates evaluation in another notebook, then
ButtonNotebook[ ] will be the palette, but EvaluationNotebook[ ] will be the other notebook. If the current
evaluation was not initiated by a button, then ButtonNotebook[ ] will return $Failed. See page 579. See also:
Notebooks, EvaluationNotebook , SelectedNotebook , InputNotebook. New in Version 3.
ButtonSource
ButtonSource is an option for ButtonBox which specifies the first argument to give to the
ButtonFunction for the button when the button is active and is clicked on.
The default is ButtonSource->Automatic .
Automatic
ButtonContents
ButtonData
Cell
CellContents
Notebook
n
See page 597.
New in Version 3.
ButtonStyle Cancel
1095
ButtonStyle
ButtonStyle is an option for ButtonBox which specifies the default properties for the button.
Typical styles defined in the standard notebook front end are:
"Paste"
"Evaluate"
"EvaluateCell"
"CopyEvaluate"
"CopyEvaluateCell"
"Hyperlink"
The properties specified by a button style can affect both the appearance and action of a button. The properties
can be overridden by explicit settings for ButtonBox options. See page 595. See also: ButtonFrame,
ButtonFunction. New in Version 3.
Byte
Byte represents a single byte of data in Read.
See page 646.
New in Version 1.
ByteCount
ByteCount[expr] gives the number of bytes used internally by Mathematica to store expr.
ByteCount does not take account of any sharing of subexpressions. The results it gives assume that every part of
the expression is stored separately. ByteCount will therefore often give an overestimate of the amount of memory
currently needed to store a particular expression. When you manipulate the expression, however, subexpressions will
often stop being shared, and the amount of memory needed will be close to the value returned by ByteCount. See
page 714. See also: LeafCount, MemoryInUse, MaxMemoryUsed, Length, StringLength, Depth. New in Version 1.
C
C[i] is the default form for the ith parameter or constant generated in representing the results
of various symbolic computations.
The C[i] are often used to parameterize families of solutions to equations. , In functions like DSolve, the C[i]
can be thought of as corresponding to constants of integration. , In cases such as partial differential equations, the
C[i] represent functions rather than variables. , C is the default setting for the option GeneratedParameters in
such functions as DSolve, RSolve and Reduce. See pages 93 and 871. See also: GeneratedParameters , Unique.
New in Version 2.
,
Cancel
Cancel[expr] cancels out common factors in the numerator and denominator of expr.
Example: Cancel[(x^2-1)/(x-1)] # 1 x . Cancel is Listable. Cancel cancels out the greatest common
divisor of the numerator and denominator. Cancel[expr, Modulus->p] generates a result modulo p.
Cancel[expr, Extension->Automatic] allows operations to be performed on algebraic numbers in expr.
Cancel[expr, Trig -> True] treats trigonometric functions as rational functions of exponentials, and manipulates
them accordingly. See page 802. See also: Apart, GCD. New in Version 1; modified in Version 3.
CarmichaelLambda Ceiling
1096
CarmichaelLambda
CarmichaelLambda[n] gives the Carmichael function n, defined as the smallest integer m
such that km Q mod n for all k relatively prime to n.
Integer mathematical function (see Section A.3.10). CarmichaelLambda returns unevaluated if there is no integer m
satisfying the necessary conditions. See page 752. See also: MultiplicativeOrder , EulerPhi, RealDigits.
New in Version 4.
Cases
Cases[{e , e , ... }, pattern] gives a list of the ei that match the pattern.
Cases[{e , ... }, pattern -> rhs] gives a list of the values of rhs corresponding to the ei that
match the pattern.
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.
Cases[expr, pattern, levspec, n] gives the first n parts in expr which match the pattern.
Example: Cases[{2, x, 4}, _Integer] # 2, 4 . The first argument to Cases need not have head List.
, Cases[expr, pattern :> rhs] evaluates rhs only when the pattern is found.
Level specifications are described on
page 1041. See page 261. See also: Select, Position, ReplaceList, Collect, DeleteCases. Related package:
Statistics`DataManipulation` . New in Version 1.
Catalan
Catalan is Catalans constant, with numerical value .
k
Mathematical constant (see Section A.3.11). Catalans constant is given by the sum
k k .
page 765. Implementation notes: see page 1067. New in Version 1.
See
Catch
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].
Catch[expr, . . . ] always returns the value of expr if no Throw was generated during the evaluation. form can be
any expression, and is often a pattern. tag in Throw[value, tag] is re-evaluated every time it is compared to form.
See page 350. See also: Check, CheckAbort, Reap. New in Version 1; modified in Version 3.
Ceiling
Ceiling[x] gives the smallest integer greater than or equal to x.
Mathematical function (see Section A.3.10). Examples: Ceiling[2.4] # 3 ; Ceiling[2.6] # 3 ;
Ceiling[-2.4] # 2 ; Ceiling[-2.6] # 2 . Ceiling[x] can be entered in StandardForm and InputForm as
F x G, H lc H x H rc H or \[LeftCeiling] x \[RightCeiling]. Ceiling[x] returns an integer when x is any
numeric quantity, whether or not it is an explicit number. Example: Ceiling[Pi^2] # 10 . For exact numeric
quantities, Ceiling internally uses numerical approximations to establish its result. This process can be affected by
the setting of the global variable $MaxExtraPrecision . See page 745. Implementation notes: see page 1067.
See also: Floor, IntegerPart, Round, Chop. New in Version 1; modified in Version 3.
Cell CellBaseline
1097
Cell
Cell[contents, "style"] represents a cell in a Mathematica notebook.
A Mathematica notebook consists of a list of cells. You can see the form of a cell as an expression by using the
Show Expression command in the standard Mathematica front end. You can access cells in a notebook directly using
the front end. You can also access the cells from the kernel using NotebookRead and NotebookWrite , or using
Options and SetOptions on NotebookSelection[obj] . The contents of cells can be the following:
"text"
TextData[{text , text , . . . }]
BoxData[boxes]
GraphicsData["type", data]
OutputFormData["itext", "otext"]
RawData["data"]
CellGroupData[{cell , cell , . . . }, Open]
CellGroupData[{cell , cell , . . . }, Closed]
StyleData["style"]
plain text
general text objects
formatted Mathematica expressions
graphics or sounds
text as generated by InputForm and OutputForm
unformatted expressions
open group of cells
closed group of cells
sample cell for a particular style
In any given notebook, a collection of possible cell styles are defined, typically with names such as "Title",
"Section", "Input" and "Output". Cells can have many options, including:
Active
Background
Editable
CellFrame
CellTags
FontSize
TextAlignment
See page 599.
New in Version 3.
CellAutoOverwrite
CellAutoOverwrite is an option for Cell which specifies whether new output obtained by
evaluating this cell should overwrite old output.
Any sequence of cells with GeneratedCell->True which follow the given cell are assumed to correspond to
output. The output is deleted only when new output is ready to be inserted in its place. CellAutoOverwrite is
typically set for cells in "Output" style. See page 608. See also: GeneratedCell , CellEvaluationDuplicate ,
Deletable. New in Version 3.
CellBaseline
CellBaseline is an option for Cell which specifies where the baseline of the cell should be
assumed to be when it appears inside another cell.
CellBaseline is used to determine the vertical alignment of cells that are embedded in text, typically in TextData
objects. CellBaseline->pos specifies that position pos in the Cell should be assumed to be the baseline of the
Cell and should therefore be aligned with baselines of other boxes. Possible settings are:
Axis
Baseline
Bottom
Center
Top
New in Version 3.
CellDingbat CellGroupData
1098
CellDingbat
CellDingbat is an option for Cell which specifies what dingbat to use to emphasize a cell.
The setting CellDingbat->"" displays no dingbat. Dingbats are placed to the left of the main contents of a cell,
aligned with the first line of the contents. Dingbats are placed outside of any cell frame. The setting for
CellDingbat can be any string. A typical setting is "\[FilledSquare] ". CellDingbat is often set for styles of
cells rather than for individual cells. See page 604. See also: CellFrame, Background. New in Version 3.
CellEditDuplicate
CellEditDuplicate is an option for Cell which specifies whether the front end should make
a copy of the cell before actually applying any changes in its contents that you request.
CellEditDuplicate is by default set to True for cells that are generated as Mathematica output. New cells
generated when CellEditDuplicate->True have styles specified by the setting for DefaultDuplicateCellStyle
for the notebook. CellEditDuplicate is typically set for styles of cells rather than for individual cells. See
page 607. See also: CellEvaluationDuplicate , Editable. New in Version 3.
CellEvaluationDuplicate
CellEvaluationDuplicate is an option for Cell which specifies whether the front end should
make a copy of the cell before performing any evaluation of its contents that you request.
New cells generated when CellEvaluationDuplicate->True have styles specified by the setting for
DefaultDuplicateCellStyle for the notebook. CellEvaluationDuplicate is typically set for styles of cells
rather than for individual cells. See page 608. See also: CellEditDuplicate , Evaluatable, CellAutoOverwrite .
New in Version 3.
CellFrame
CellFrame is an option for Cell which specifies whether a frame should be drawn around a
cell.
The space left between the frame and the cell contents is determined by CellFrameMargins . Dingbats go outside
the frame. See page 604. See also: Background, CellDingbat, FrameBox. New in Version 3.
CellFrameMargins
CellFrameMargins is an option for Cell which specifies the absolute margins in printers
points to leave inside a frame that is drawn around a cell.
Possible settings are:
dist
{{left, right}, {bottom, top}}
See page 605.
New in Version 3.
CellGroupData
CellGroupData[{cell , cell , ... }, Open] represents an open group of cells in a notebook.
CellGroupData[{cell , cell , ... }, Closed] represents a closed group of cells.
When a group of cells is closed, only the first member of the group is visible. When cells are entered into a
notebook, they are automatically placed in groups unless CellGrouping->Manual is set. See page 600. See also:
Cell, CellGrouping, CellOpen. New in Version 3.
CellGrouping CellOpen
1099
CellGrouping
CellGrouping is an option for Notebook which specifies how cells in the notebook should be
assembled into groups.
The default setting is typically CellGrouping->Automatic . With CellGrouping->Automatic , cells are
automatically grouped in a hierarchical way based on their styles. With CellGrouping->Manual , cells must be
grouped manually, either by setting up explicit CellGroupData expressions, or by using the Group Cells menu item
in the notebook front end. See page 618. See also: CellGroupData . New in Version 3.
CellLabel
CellLabel is an option for Cell which gives the label to use for a particular cell.
CellLabel->"" specifies that no label should be used for a cell. Cell labels are displayed when the setting
ShowCellLabels->True is made. Cell labels are typically generated automatically when cells appear as input or
output to the Mathematica kernel. Cell labels are automatically deleted when a cell is modified if
CellLabelAutoDelete->True . See page 607. See also: CellTags. New in Version 3.
CellLabelAutoDelete
CellLabelAutoDelete is an option for Cell which specifies whether a label for the cell should
be automatically deleted if the contents of the cell are modified or the notebook containing the
cell is saved in a file.
Cell styles that represent Mathematica input and output typically have CellLabelAutoDelete->True .
CellLabelAutoDelete is more often set for styles of cells than for individual cells. See page 607.
CellLabel, ShowCellLabel, CellTags, CellAutoOverwrite . New in Version 3.
See also:
CellMargins
CellMargins is an option for Cell which specifies the absolute margins in printers points to
leave around a cell.
Possible settings are:
dist
{{left, right}, {bottom, top}}
The left margin gives the distance from the edge of the window to the left-hand side of the cell. The right
margin gives the distance from the inside of the cell bracket to the right-hand side of the cell. The left and right
margins can be set interactively in the front end using the Show Ruler ruler. The top and bottom margins determine
the amount of space to leave above and below the cell. The margins go to the edge of any cell frame that is
present. Cell dingbats are placed to the left of the left-hand side of the cell, and extend into the left cell margin.
See page 605. See also: CellFrameMargins , CellBaseline, ImageMargins, WindowMargins . New in Version 3.
CellOpen
CellOpen is an option for Cell which specifies whether the contents of a cell should be
explicitly displayed.
With CellOpen->False, a small cell bracket is still shown to indicate the presence of a cell. Cells which are not
open can still be evaluated automatically if you set InitializationCell->True . See page 604. See also:
Visible, CellGroupData , ConversionRules . New in Version 3.
CellPrint CellularAutomaton
1100
CellPrint
CellPrint[cell] inserts cell in a notebook immediately after the cell that is currently being
evaluated.
CellPrint[{cell , cell , ... }] inserts a sequence of cells.
The celli must all have head Cell. CellPrint is a special case of NotebookWrite. With a text-based front end,
CellPrint[cell] does the same as applying Print to the contents of cell. Cells generated by CellPrint by default
have GeneratedCell->True . See page 575. See also: StylePrint, Print, NotebookWrite, NotebookPrint . New
in Version 3.
CellTags
CellTags is an option for Cell which gives a list of tags to associate with a cell.
Cell tags are typically used to allow searching for cells. The tags are usually strings. Cell tags are displayed
when the setting ShowCellTags->True is made. See page 607. See also: CellLabel, ConversionRules . New in
Version 3.
,
CellularAutomaton
CellularAutomaton[rnum, init, t] generates a list representing the evolution of cellular
automaton rule rnum from initial condition init for t steps.
CellularAutomaton[rnum, init, t, {offt , offx , ... }] keeps only the parts of the evolution list
with the specified offsets.
Possible settings for rnum are:
n
{n, k}
{n, k, r}
{n, k, {r , r , . . . , rd }}
{n, k, {{off }, {off }, . . . , {offs }}}
{n, {k, 1}}
{n, {k, 1}, r}
{n, {k, {wt , wt , . . . }}, rspec}
{fun, {}, rspec}
k , r , elementary rule
general nearest-neighbor rule with k colors
general rule with k colors and range r
d-dimensional rule with r r rd neighborhood
rule with neighbors at specified offsets
k-color nearest-neighbor totalistic rule
k-color range r totalistic rule
rule in which neighbor i is assigned weight wti
applies the function fun to each list of neighbors, with a second argument
of the step number
1}}}, . . . ].
Common
totalistic rule
totalistic rule
outer totalistic rule
growth rule
Normally, all elements in init and the evolution list are integers between 0 and k . But when a general
function is used, the elements of init and the evolution list do not have to be integers. The second argument
passed to fun is the step number, starting at 0. Initial conditions are constructed from init as follows:
{a , a , . . . }
{{a , a , . . . }, b}
{{a , a , . . . }, {b , b , . . . }}
(continued)
CellularAutomaton
1101
(continued)
The first element of aspec is superimposed on the background at the first position in the positive direction in each
coordinate relative to the origin. This means that bspec[[1, 1, . . . ]] is aligned with aspec[[1, 1, . . . ]]. Time
offsets offt are specified as follows:
All
u
-1
{u}
{u , u }
{u , u , du}
In one dimension, the first element of aspec is taken by default to have space offset 0. In any number of
dimensions, aspec[[1, 1, 1, . . . ]] is taken by default to have space offset {0, 0, 0, . . . }. Each element of the
evolution list produced by CellularAutomaton is always the same size. With an initial condition specified by an
aspec of width w, the region that can be affected after t steps by a cellular automaton with a rule of range r has
width w rt. If no bspec background is specified, space offsets of All and Automatic will include every cell in
aspec. A space offset of All includes all cells that can be affected by the initial condition. A space offset of
Automatic can be used to trim off background from the sides of a cellular automaton pattern. In working out
how wide a region to keep, Automatic only looks at results on steps specified by offt . See page 942.
Implementation notes: see page 1069. See also: ListConvolve, Partition, BitXor. New in Version 4.2.
CForm
CForm[expr] prints as a C language version of expr.
Standard arithmetic functions and certain control structures are translated. No declarations are generated. CForm
acts as a wrapper, which affects printing, but not evaluation. See pages 213 and 425. See also: FortranForm,
Compile. New in Version 1.
Character
Character represents a single character in Read.
See page 646.
New in Version 1.
CharacterEncoding Check
1102
CharacterEncoding
CharacterEncoding is an option for input and output functions which specifies what raw
character encoding should be used.
The default is CharacterEncoding:>$CharacterEncoding . The possible settings for CharacterEncoding are the
same as for $CharacterEncoding . See pages 422 and 634. See also: ToCharacterCode, FromCharacterCode ,
StringReplace, $SystemCharacterEncoding , ShowSpecialCharacters . New in Version 3.
,
CharacteristicPolynomial
CharacteristicPolynomial[m, x] gives the characteristic polynomial for the matrix m.
m must be a square matrix. It can contain numeric or symbolic entries.
Eigenvalues, Det. New in Version 5.0.
See also:
CharacterRange
CharacterRange["c ", "c "] yields a list of the characters in the range from "c " to "c ".
Example: CharacterRange["A", "D"] # "A", "B", "C", "D" . CharacterRange["a", "z"] yields the
English alphabet. CharacterRange["0", "9"] yields a list of digits. CharacterRange["c ", "c "] gives the list
of characters with character codes from ToCharacterCode["c "] to ToCharacterCode["c "].
CharacterRange["b", "a"] gives { }. See page 413. See also: FromCharacterCode , Range, Sort, Symbol,
Unique. New in Version 3.
Characters
Characters["string"] gives a list of the characters in a string.
Each character is given as a length one string. Characters handles both ordinary and special characters. See
page 412. See also: StringJoin, StringLength, ToCharacterCode, StringToStream, CharacterRange. New in
Version 1; modified in Version 3.
ChebyshevT
ChebyshevT[n, x] gives the Chebyshev polynomial of the first kind Tn x.
Mathematical function (see Section A.3.10). Explicit polynomials are given for integer n. Tn cos cosn.
ChebyshevT[n, z] has a branch cut discontinuity in the complex z plane running from to . See page 766.
See also: ChebyshevU. New in Version 1.
ChebyshevU
ChebyshevU[n, x] gives the Chebyshev polynomial of the second kind Un x.
Mathematical function (see Section A.3.10). Explicit polynomials are given for integer n.
Un cos sinen fsin . ChebyshevU[n, z] has a branch cut discontinuity in the complex z plane running
from to . See page 766. See also: ChebyshevT. New in Version 1.
Check
Check[expr, failexpr] evaluates expr, and returns the result, unless messages were generated, in
which case it evaluates and returns failexpr.
Check[expr, failexpr, s ::t , s ::t , ... ] checks only for the specified messages.
Check has attribute HoldAll. Check tests only for messages that are actually output. It does not test for messages
that have been suppressed using Off. See page 481. See also: MessageList, $MessageList , Message,
Indeterminate, TimeConstrained , CheckAbort. New in Version 1.
CheckAbort Clear
1103
CheckAbort
CheckAbort[expr, failexpr] evaluates expr, returning failexpr if an abort occurs.
CheckAbort absorbs any aborts it handles, and does not propagate them further. CheckAbort works inside
AbortProtect. CheckAbort has attribute HoldAll. See page 371. See also: Catch, Check. New in Version 2.
,
CholeskyDecomposition
CholeskyDecomposition[m] gives the Cholesky decomposition of a matrix m.
The matrix m can be numerical or symbolic, but must be Hermitian and positive definite.
CholeskyDecomposition[m] yields an upper triangular matrix u so that Conjugate[Transpose[u]] . u == m.
See page 914. See also: LUDecomposition , LinearSolve, LinearSolveFunction , FindMinimum. New in
Version 5.0.
Chop
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. Chop uses a default tolerance
of . Chop works on both Real and Complex numbers. See page 730. See also: Rationalize, Round. New
in Version 1.
Circle
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}, {rx , ry }] yields an ellipse with semi-axes rx and ry .
Circle[{x, y}, r, { , }] represents a circular arc.
Angles are measured in radians counterclockwise from the positive x direction.
Circle[{x, y}, {rx , ry }, { , }] yields a segment of an ellipse obtained by transforming a circular arc with
the specified starting and ending angles. Scaled[{dr x , dry }] or Scaled[{dr x , dry }, {rx , ry }] can be used in the
radius specification. The dri are in scaled coordinates, and the ri are in ordinary coordinates. Offset[{ax , ay }]
can be used to specify radii in printers points. The thickness of the circle can be specified using the Thickness
primitive. See page 496. See also: Disk. New in Version 2; modified in Version 3.
Clear
Clear[symbol , symbol , ... ] clears values and definitions for the symboli .
Clear["form ", "form ", ... ] clears values and definitions for all symbols whose names
match any of the string patterns formi .
Clear does not clear attributes, messages, or defaults associated with symbols. Clear["form"] allows
metacharacters such as *, as specified on page 1044. Clear["context`*"] clears all symbols in a particular context.
Clear is HoldAll. Clear does not affect symbols with the attribute Protected. See pages 110, 304, 403
and 1052. See also: Remove. New in Version 1.
ClearAll Close
1104
ClearAll
ClearAll[symb , symb , ... ] clears all values, definitions, attributes, messages and defaults
associated with symbols.
ClearAll["form ", "form ", ... ] clears all symbols whose names textually match any of the
formi .
See notes for Clear.
New in Version 1.
ClearAttributes
ClearAttributes[s, attr] removes attr from the list of attributes of the symbol s.
ClearAttributes modifies Attributes[s]. ClearAttributes[s, {attr , attr , . . . }] removes several attributes at
a time. ClearAttributes[{s , s , . . . }, attrs] removes attributes from several symbols at a time.
ClearAttributes is HoldFirst. ClearAttributes does not affect symbols with the attribute Locked. See
page 328. See also: SetAttributes, Unprotect. New in Version 1.
ClebschGordan
ClebschGordan[{j , m }, {j , m }, {j, m}] gives the Clebsch-Gordan coefficient for
the decomposition of / j m in terms of / j m / j m .
The Clebsch-Gordan coefficients vanish except when m m m and the ji satisfy a triangle inequality. The
parameters of ClebschGordan can be integers, half-integers or symbolic expressions. Mathematica uses the standard
conventions of Edmonds for the phase of the Clebsch-Gordan coefficients. See page 760. Implementation notes:
see page 1067. See also: ThreeJSymbol, SixJSymbol, SphericalHarmonicY . New in Version 2.
ClipFill
ClipFill is an option for SurfaceGraphics that specifies how clipped parts of the surface are
to be drawn.
ClipFill specifies what is to be shown in places where the surface would extend beyond the bounding box.
possible settings are:
Automatic
None
color
{bottom, top}
The
The colors for clipped areas can be specified by GrayLevel, Hue or RGBColor directives, or SurfaceColor objects.
See page 540. New in Version 1.
Close
Close[stream] closes a stream.
The argument to Close can be an InputStream or OutputStream object. If there is only one stream with a
particular name, the argument to close can be "name". See page 632. See also: OpenAppend, SetOptions,
Streams. New in Version 1.
CMYKColor CoefficientList
1105
CMYKColor
CMYKColor[cyan, magenta, yellow, black] is a graphics directive which specifies that graphical
objects which follow are to be displayed in the color given.
Color levels outside the range 0 to 1 will be clipped. CMYKColor can be used to specify colors for color printing.
CMYKColor specifications are automatically converted to RGBColor when simulated lighting calculations are done.
See page 563. See also: RGBColor, ColorOutput. Related package: Graphics`Colors` . New in Version 2.
Coefficient
Coefficient[expr, form] gives the coefficient of form in the polynomial expr.
Coefficient[expr, form, n] gives the coefficient of form^n in expr.
Coefficient picks only terms that contain the particular form specified. x is not considered part of x
. form can
be a product of powers. Coefficient[expr, form, 0] picks out terms that are not proportional to form.
Coefficient works whether or not expr is explicitly given in expanded form. See page 799. See also:
Exponent, CoefficientList , SeriesCoefficient . New in Version 1; modified in Version 3.
,
CoefficientArrays
CoefficientArrays[polys, vars] gives the arrays of coefficients of the variables vars in the
polynomials polys.
CoefficientArrays gives a list containing SparseArray objects, which can be converted to ordinary arrays using
Normal. If CoefficientArrays[polys, vars] gives {m , m , m , . . . }, then polys can be reconstructed as
m + m . vars + m . vars . vars + . . . . Any element of polys of the form lhs == rhs is taken to correspond to
the polynomial lhs - rhs. CoefficientArrays[polys, {form , form , . . . }] takes all expressions in polys that
match any of the formi to be variables. CoefficientArrays[polys] is equivalent to
CoefficientArrays[polys, Variables[polys]] . The length of the list CoefficientArrays[polys, vars] is one
more than the total degree of polys. The mi are sparse arrays with ranks i + 1. The first element m has the
same length as the list polys. If polys is a single polynomial rather than a list, m is also not a list. For linear
equations, the solution to Thread[polys==0] is given by LinearSolve[m , -m ]. For nonlinear equations, the mi
are not unique. CoefficientArrays by default assigns non-zero coefficients only to monomials where the variables
appear in the same order as vars. CoefficientArrays[polys, vars, Symmetric->True] makes all the mi
symmetric in all their indices. The resulting arrays will generally be less sparse. See page 922. See also:
CoefficientList, SparseArray, Solve. New in Version 5.0.
CoefficientList
CoefficientList[poly, var] gives a list of coefficients of powers of var in poly, starting with
power 0.
CoefficientList[poly, {var , var , ... }] gives an array of coefficients of the vari .
Example: CoefficientList[x^2 + 2 x y - y, {x, y}] # 0, 1, 0, 2, 1, 0 . The dimensions of the
array returned by CoefficientList are determined by the values of the Exponent[poly, vari ]. Terms that do not
contain positive integer powers of a particular variable are included in the first element of the list for that variable.
CoefficientList always returns a full rectangular array. Combinations of powers that do not appear in poly give
zeros in the array. , CoefficientList[0, var] gives {}. CoefficientList works whether or not poly is
explicitly given in expanded form. See page 799. See also: Series, CoefficientArrays , SeriesCoefficient ,
Coefficient, Collect, FactorList. New in Version 1; modified in Version 3.
Collect ColorOutput
1106
Collect
Collect[expr, x] collects together terms involving the same powers of objects matching x.
Collect[expr, {x , x , ... }] collects together terms that involve the same powers of objects
matching x , x , ... .
Collect[expr, var, h] applies h to the expression that forms the coefficient of each term
obtained.
Collect[expr, x] effectively writes expr as a polynomial in x or a fractional power of x. Examples:
Collect[x + n x + m, x] # m 1 n x ;
Collect[(1+x+y)^3, x] # 1 x3 3 y 3 y2 y3 x2 3 3 y x 3 6 y 3 y2 . Collect[expr, x, Simplify]
can be used to simplify each coefficient separately. See page 797. See also: Series, CoefficientList , Together,
Cases. New in Version 1; modified in Version 3.
ColorFunction
ColorFunction is an option for various graphics functions which specifies a function to apply
to z values to determine the color to use for a particular x, y region.
ColorFunction is an option for Plot3D, ListPlot3D, DensityPlot, ContourPlot, Raster and related functions.
With the default setting ColorFunctionScaling -> True, the arguments provided for the function specified by
ColorFunction are always scaled to be in the range 0 to 1. With ColorFunctionScaling -> False original
unscaled values are used. The function specified by ColorFunction must return a CMYKColor, GrayLevel, Hue or
RGBColor directive. ColorFunction -> Automatic yields a range of gray levels. ColorFunction -> Hue yields a
range of colors. In three-dimensional graphics, ColorFunction is used only with the option setting
Lighting -> False. See page 517. See also: ColorFunctionScaling , Lighting, ColorOutput. New in
Version 2; modified in Version 4.0.
ColorFunctionScaling
ColorFunctionScaling is an option for various graphics functions which specifies whether
the values provided to a color function should be scaled to lie between 0 and 1.
The default setting for ColorFunctionScaling is True. With ColorFunctionScaling -> False original unscaled
values are fed to the color function. See page 517. See also: ColorFunction. New in Version 4.
ColorOutput
ColorOutput is an option for graphics functions which specifies the type of color output to
produce.
Possible settings are:
Automatic
None
CMYKColor
GrayLevel
RGBColor
f
Mathematica performs color conversions using approximations to typical primary display and printing colors.
page 564. New in Version 2; modified in Version 3.
See
ColumnAlignments ColumnLines
1107
ColumnAlignments
ColumnAlignments is an option for GridBox which specifies how entries in each column
should be aligned.
The following settings can be given:
Center
Left
Right
"."
"c"
{pos , pos , . . . }
centered (default)
left justified (aligned on left edge)
right justified (aligned on right edge)
aligned at decimal points
aligned at the first occurrence of the character c
separate settings for each column in the grid
Lists of settings are used cyclically if there are more columns in the grid than elements in the list. With the
setting ColumnAlignments->"c" a column will be right justified if the character c appears nowhere in it. You can
insert invisible \[AlignmentMarker] characters in the entries in a grid to specify how these entries should be
aligned. See page 449. See also: RowAlignments , ColumnsEqual, TableAlignments, TextAlignment. New in
Version 3.
ColumnForm
ColumnForm[{e , e , ... }] prints as a column with e above e , etc.
ColumnForm[list, horiz] specifies the horizontal alignment of each element.
ColumnForm[list, horiz, vert] also specifies the vertical alignment of the whole column.
Possible horizontal alignments are:
Center
Left
Right
centered
left justified (default case)
right justified
Above
Below
Center
The first argument of ColumnForm can have any head, not necessarily List. ColumnForm acts as a wrapper,
which affects printing, but not evaluation. See pages 416 and 437. See also: TableForm, MatrixForm,
SequenceForm, GridBox. New in Version 1.
ColumnLines
ColumnLines is an option for GridBox which specifies whether lines should be drawn between
adjacent columns.
The default setting is ColumnLines->False . ColumnLines->{v , v
, . . . } specifies whether lines should be
drawn between successive pairs of columns. The vij can be True or False. If there are more columns than entries
in the list, the last element is used repeatedly for remaining pairs of columns. Lines can be drawn around the
outside of a GridBox using FrameBox. See page 446. See also: RowLines, FrameBox, GridLines. New in
Version 3.
ColumnsEqual Compile
1108
ColumnsEqual
ColumnsEqual is an option for GridBox which specifies whether all columns in the grid should
be assigned equal width.
The default setting ColumnsEqual->False determines the width of each column from the widest entry in that
column. ColumnsEqual->True makes all columns the same width, with the width determined by the widest entry
in the whole GridBox. See page 449. See also: ColumnWidths, ColumnAlignments , ColumnSpacings , RowsEqual,
MatrixForm. New in Version 3.
ColumnSpacings
ColumnSpacings is an option for GridBox which specifies the spaces in ems that should be
inserted between adjacent columns.
The default setting is ColumnSpacings->0.8 . ColumnSpacings effectively specifies the minimum distance between
entries in adjacent columns; individual entries will often not fill their columns and will therefore be further apart.
ColumnSpacings->n uses a column spacing equal to n times the current font sizeusually about n times the
width of an M in the current font. ColumnSpacings->{s , s
, . . . } can be used to specify different spacings
between different columns. If there are more columns than entries in this list, then the last element of the list is
used repeatedly for the remaining columns. See page 449. See also: ColumnAlignments , ColumnWidths,
ColumnsEqual, RowSpacings, TableSpacing. New in Version 3.
ColumnWidths
ColumnWidths is an option for GridBox which specifies the widths of columns in ems.
The default setting is ColumnWidths->Automatic , specifying that all columns should be made wide enough to fit
their contents without breaking onto multiple lines. ColumnWidths->n uses column widths equal to n times the
current font sizeusually about n times the width of an M in the current font. ColumnWidths->{w , w , . . . }
can be used to specify different widths for different columns. If there are more columns than entries in this list, then
the last element of the list is used repeatedly for the remaining columns. An explicit setting for ColumnWidths
overrides ColumnsEqual->True . See page 449. See also: ColumnsEqual, ColumnSpacings. New in Version 3.
Compile
Compile[{x , x , ... }, expr] creates a compiled function which evaluates expr assuming
numerical values of the xi .
Compile[{{x , t }, ... }, expr] assumes that xi is of a type which matches ti .
Compile[{{x , t , n }, ... }, expr] assumes that xi is a rank ni array of objects each of a type
which matches ti .
Compile[vars, expr, {{p , pt }, ... }] assumes that subexpressions in expr which match pi are
of types which match pti .
The types handled by Compile are:
_Integer
_Real
_Complex
True | False
machine-size integer
machine-precision approximate real number (default)
machine-precision approximate complex number
logical variable
(continued)
Compile
1109
(continued)
Nested lists given as input to a compiled function must be full arrays of numbers. Compile handles numerical
functions, matrix operations, procedural programming constructs, list manipulation functions, functional
programming constructs, etc. Compile generates a CompiledFunction object. Compiled code does not handle
numerical precision and local variables in the same way as ordinary Mathematica code. If a compiled function
cannot be evaluated with particular arguments using compiled code, ordinary Mathematica code is used instead.
Ordinary Mathematica code can be called from within compiled code. Results obtained from the Mathematica code
are assumed to be approximate real numbers, unless specified otherwise by the third argument of Compile. The
number of times and the order in which objects are evaluated by Compile may be different from ordinary
Mathematica code. Compile has attribute HoldAll, and does not by default do any evaluation before compilation.
You can use Compile[ . . . , Evaluate[expr]] to specify that expr should be evaluated symbolically before
compilation. See page 372. See also: Dispatch, Function, InterpolatingFunction , CForm. New in Version 2;
modified in Version 3.
Compiled
Compiled is an option for various numerical and plotting functions which specifies whether
the expressions they work with should automatically be compiled.
Compiled -> True automatically creates compiled functions. You should set Compiled -> False if you need to
use high-precision numbers. See page 373. New in Version 2.
CompiledFunction
CompiledFunction[args, argregs, nregs, instr, func] represents compiled code for evaluating
a compiled function.
args is a list giving a pattern for the type of each argument to the function. The types are specified as in Compile.
argregs is a list of the registers into which actual argument values should be placed to evaluate the compiled
code. nregs is a list of the numbers of logical, integer, real, complex and tensor registers required in evaluating
the compiled code. instr is a list of actual compiled code instructions. func is a Mathematica pure function to be
used if no result can be obtained from the compiled code for any reason. Compile generates a CompiledFunction
object which can be executed by applying it to appropriate arguments. CompiledFunction objects that are
constructed explicitly can also be executed. Basic consistency checks are done when such objects are first evaluated
by Mathematica. The code in a CompiledFunction object is based on an idealized register machine. See
page 376. See also: InterpolatingFunction . New in Version 2; modified in Version 4.0.
Complement
Complement[eall, e , e , ... ] gives the elements in eall which are not in any of the ei .
The list returned by Complement is sorted into standard order. Example:
Complement[{a,b,c,d,e}, {a,c}, {d}] # b, e . Complement[eall, e , . . . , SameTest->test] applies test to
each pair of elements in eall and the ei to determine whether they should be considered the same. See page 127.
See also: Intersection, Union. New in Version 1; modified in Version 3.
Complex
Complex is the head used for complex numbers.
You can enter a complex number in the form x + I y. _Complex can be used to stand for a complex number in a
pattern. You have to use Re and Im to extract parts of Complex numbers. See page 722. See also: Complexes,
Real, Re, Im. New in Version 1.
Complexes ComposeSeries
1110
Complexes
Complexes represents the domain of complex numbers, as in x Complexes .
x Complexes evaluates immediately only if x is a numeric quantity. Simplify[expr Complexes] can be used
to try to determine whether an expression corresponds to a complex number. The domain of real numbers is
taken to be a subset of the domain of complex numbers. Complexes is output in TraditionalForm as . See
pages 817 and 839. See also: Element, Simplify, NumberQ, NumericQ, Complex, Reals. Related package:
Algebra`Quaternions` . New in Version 4.
ComplexExpand
ComplexExpand[expr] expands expr assuming that all variables are real.
ComplexExpand[expr, {x , x , ... }] expands expr assuming that variables matching any of
the xi are complex.
Example: ComplexExpand[Sin[x + I y]] # Cosh
y Sin
x Cos
x Sinh
y . The variables given in the
second argument of ComplexExpand can be patterns. Example:
ComplexExpand[Sin[x], x] # Cosh
Im
x Sin
Re
x Cos
Re
x Sinh
Im
x . The option
TargetFunctions can be given as a list of functions from the set {Re, Im, Abs, Arg, Conjugate, Sign}.
ComplexExpand will try to give results in terms of functions specified.
ComplexExpand[expr, vars, TargetFunctions -> {Abs, Arg}] converts to polar coordinates. See page 812.
See also: GaussianIntegers , TrigToExp, ExpToTrig, TrigExpand, FunctionExpand. New in Version 2.
ComplexInfinity
ComplexInfinity represents a quantity with infinite magnitude, but undetermined complex
phase.
ComplexInfinity is converted to DirectedInfinity[ ]. In OutputForm, DirectedInfinity[ ] is printed as
ComplexInfinity . See page 743. See also: Infinity, Indeterminate . New in Version 1.
ComplexityFunction
ComplexityFunction is an option for Simplify and FullSimplify which gives a function to
rank the complexity of different forms of an expression.
With the default setting ComplexityFunction->Automatic , forms are ranked primarily according to their
LeafCount, with corrections to treat integers with more digits as more complex.
Simplify[expr, ComplexityFunction->f] applies f to each intermediate expression generated by Simplify,
treating the one which yields the smallest numerical value as simplest. See page 815. See also: Length,
StringLength, TimeConstraint, ExcludedForms, TransformationFunctions . New in Version 3.
ComposeList
ComposeList[{f , f , ... }, x] generates a list of the form {x, f [x], f [f [x]], ... }.
Example: ComposeList[{a, b, c}, x] # x, a
x, b
a
x, c
b
a
x .
NestList, FoldList, NestWhileList. New in Version 2.
See also:
ComposeSeries
ComposeSeries[series , series , ... ] composes several power series.
ComposeSeries[series , series , . . . ] effectively replaces the variable in series by series and so on. Two series can
only meaningfully be composed when the point about which the first series is expanded corresponds to the limiting
value of the second series at its expansion point. See page 887. See also: InverseSeries. New in Version 3.
Composition Context
1111
Composition
Composition[f , f , f
, ... ] represents a composition of the functions f , f , f
, ... .
Composition allows you to build up compositions of functions which can later be applied to specific arguments.
Example: Composition[a, b, c][x] # a
b
c
x . Composition objects containing Identity or
InverseFunction[f] are automatically simplified when possible. Composition has the attributes Flat and
OneIdentity. a @ b @ c gives a[b[c]]. a // b // c gives c[b[a]]. See page 253. See also: Nest, Function.
New in Version 2.
CompoundExpression
expr ; expr ; ... evaluates the expri in turn, giving the last one as the result.
CompoundExpression evaluates its arguments in a sequence corresponding to the control flow. The returned value
can be the result of Return[expr]. The evaluation of the expri can be affected by Return, Throw and Goto.
expr ; expr ; returns value Null. If it is given as input, the resulting output will not be printed. Out[n] will
nevertheless be assigned to be the value of expr . See pages 43 and 1029. See also: Block. New in Version 1.
Condition
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.
Example: The pattern x_ /; x > 0 represents an expression which must be positive. All pattern variables used in
test must also appear in patt. Example: f[x_] := fp[x] /; x > 1 defines a function in the case when x c .
lhs := Module[{vars}, rhs /; test] allows local variables to be shared between test and rhs. You can use the same
construction with Block and With. See pages 265 and 345. See also: If, Switch, Which, PatternTest, Element.
New in Version 1.
Conjugate
Conjugate[z] gives the complex conjugate z of the complex number z.
Mathematical function (see Section A.3.10).
New in Version 1.
Constant
Constant is an attribute which indicates zero derivative of a symbol with respect to all
parameters.
Constant is used by Dt. Functions f [ . . . ] are taken to have zero total derivative if f has attribute Constant.
Mathematical constants such as Pi have attribute Constant. See pages 329 and 854. New in Version 1.
Constants
Constants is an option for Dt which gives a list of objects to be taken as constants.
If f appears in the list of Constants, then both Dt[f] and Dt[f [ . . . ]] are taken to be zero.
also: D. New in Version 1.
See
Context
Context[ ] gives the current context.
Context[symbol] gives the context in which a symbol appears.
The current context is the value of $Context.
Version 1.
New in
Contexts ContourGraphics
1112
Contexts
Contexts[ ] gives a list of all contexts.
Contexts["string"] gives a list of the contexts which match the string.
The string can contain metacharacters such as * and @, as described on page 1044.
also: $Packages, $ContextPath. New in Version 2.
See
Continue
Continue[ ] exits to the nearest enclosing Do, For or While in a procedural program.
Continue[ ] takes effect as soon as it is evaluated, even if it appears inside other functions. The function of
Continue can also be achieved using Throw and Catch. See page 353. See also: Break, Goto. New in Version 1;
modified in Version 3.
ContinuedFraction
ContinuedFraction[x, n] generates a list of the first n terms in the continued fraction
representation of x.
ContinuedFraction[x] generates a list of all terms that can be obtained given the precision
of x.
The continued fraction representation {a , a , a
, . . . } corresponds to the expression a a a
. x can
be either an exact or an inexact number. Example: ContinuedFraction[Pi, 4] # 3, 7, 15, 1 . For exact
numbers, ContinuedFraction[x] can be used if x is rational, or is a quadratic irrational. For quadratic irrationals,
ContinuedFraction[x] returns a result of the form {a , a , . . . , {b , b , . . . }}, corresponding to an infinite
sequence of terms, starting with the ai , and followed by cyclic repetitions of the bi . Since the continued fraction
representation for a rational number has only a limited number of terms, ContinuedFraction[x, n] may yield a
list with less than n elements in this case. For terminating continued fractions, {. . . , k} is always equivalent to
{. . . , k-1, 1}; ContinuedFraction returns the first of these forms. FromContinuedFraction[list] reconstructs a
number from the result of ContinuedFraction . See page 754. Implementation notes: see page 1067. See also:
FromContinuedFraction , IntegerDigits , Rationalize, Khinchin, RealDigits. New in Version 4.
ContourGraphics
ContourGraphics[array] is a representation of a contour plot.
array must be a rectangular array of real numbers, representing z values.
AspectRatio
Axes
AxesLabel
AxesOrigin
AxesStyle
Background
ColorFunction
ColorFunctionScaling
ColorOutput
ContourLines
Contours
ContourShading
ContourStyle
DefaultColor
DisplayFunction
Epilog
1
False
None
Automatic
Automatic
Automatic
Automatic
True
Automatic
True
10
True
Automatic
Automatic
$DisplayFunction
{}
(continued)
ContourGraphics
FormatType
Frame
FrameLabel
FrameStyle
FrameTicks
ImageSize
MeshRange
PlotLabel
PlotRange
PlotRegion
Prolog
RotateLabel
TextStyle
Ticks
1113
(continued)
$FormatType
True
None
Automatic
Automatic
Automatic
Automatic
None
Automatic
Automatic
{}
True
$TextStyle
Automatic
ContourLines
ContourLines is an option for contour plots which specifies whether to draw explicit contour
lines.
ContourLines -> True draws contour lines. ContourLines -> False does not.
ContourStyle, Contours. New in Version 2.
See also:
ContourPlot
ContourPlot[f, {x, xmin, xmax}, {y, ymin, ymax}] generates a contour plot of f as a
function of x and y.
ContourPlot evaluates its arguments in a non-standard way (see page 1046). You should use Evaluate to evaluate
the function to be plotted if this can safely be done before specific numerical values are supplied. ContourPlot
has the same options as ContourGraphics, with the following additions:
Compiled
PlotPoints
True
25
ContourPlot has the default option setting Frame -> True. ContourPlot returns a ContourGraphics object,
with the MeshRange option set. See page 146. See also: DensityPlot. Related packages:
Graphics`ContourPlot3D` , Graphics`ImplicitPlot` , Graphics`PlotField` , Graphics`ComplexMap` . New in
Version 1.
Contours
Contours is an option for ContourGraphics specifying the contours to use.
Contours -> n chooses n equally spaced contours between the minimum and maximum z values.
Contours -> {z , z , . . . } specifies the explicit z values of contours to use. See pages 147 and 519.
Version 2.
New in
ContourShading CopyFile
1114
ContourShading
ContourShading is an option for contour plots which specifies whether the regions between
contour lines should be shaded.
With ContourShading -> False, regions between contour lines are left blank. With ContourShading -> True,
regions are colored based on the setting for the option ColorFunction. The default is to color the regions with
gray levels running from black to white with increasing height. The value given as the argument for the
ColorFunction function is the average of the values of the contour lines bounding a particular region. If
ColorFunctionScaling -> True, it is scaled so as to lie between 0 and 1. See page 519. New in Version 2.
ContourStyle
ContourStyle is an option for contour plots that specifies the style in which contour lines
should be drawn.
ContourStyle -> style specifies that all contour lines are to be generated with the specified graphics directive, or
list of graphics directives. ContourStyle -> {{style }, {style }, . . . } specifies that successive contour lines should
use graphics directives style , . . . . The styles must be enclosed in lists, perhaps of length one. The stylei are used
cyclically. Styles can be specified using graphics directives such as Dashing, Hue and Thickness. See page 519.
See also: PlotStyle. New in Version 2.
ConversionRules
ConversionRules is an option for Cell which can be set to a list of rules specifying how the
contents of the cell are to be converted to external formats.
Typical elements in the list have the form "TeX" -> data. Settings for ConversionRules do not affect the display
of cells in the standard Mathematica notebook front end. ConversionRules can be used to save the original form
of a cell that has been converted from an external format. See page 607. See also: CellTags. New in Version 3.
Copyable
Copyable is an option for Cell which specifies whether a cell can be copied interactively using
the front end.
Even with the setting Copyable->False, the expression corresponding to a cell can still be read into the kernel
using NotebookRead. With Copyable->False set at the notebook level, no cells in the notebook can be copied
interactively in the front end. See page 607. See also: Selectable, ReadProtected. New in Version 3.
CopyDirectory
CopyDirectory["dir ", "dir "] copies the directory dir to dir .
dir must already exist; dir must not. CopyDirectory copies all the files in dir to dir . CopyDirectory sets the
modification dates for dir and for all the files in it to be the same as those for dir . CopyDirectory returns the
full name of the directory it copies to, and $Failed if it cannot complete the copy. See page 641. See also:
RenameDirectory , CreateDirectory , DeleteDirectory . New in Version 2.
CopyFile
CopyFile["file ", "file "] copies file to file .
file must already exist; file must not. CopyFile sets the modification date for file to be the same as for file .
CopyFile returns the full name of the file it copies to, and $Failed if it cannot do the copy. See page 641.
See also: RenameFile, DeleteFile, CopyDirectory. New in Version 2.
Cos Count
1115
Cos
Cos[z] gives the cosine of z.
Mathematical function (see Section A.3.10). The argument of Cos is assumed to be in radians. (Multiply by
Degree to convert from degrees.) Cos is automatically evaluated when its argument is a simple rational multiple
of ; for more complicated rational multiples, FunctionExpand can sometimes be used. See page 761. See also:
ArcCos, Sec, TrigToExp, TrigExpand. New in Version 1.
Cosh
Cosh[z] gives the hyperbolic cosine of z.
Mathematical function (see Section A.3.10). coshz ez ez .
TrigToExp, TrigExpand. New in Version 1.
CoshIntegral
CoshIntegral[z] gives the hyperbolic cosine integral Chiz.
z
Mathematical function (see Section A.3.10). Chiz logz cosht t dt, where is Eulers constant.
CoshIntegral[z] has a branch cut discontinuity in the complex z plane running from to . See page 774.
See also: SinhIntegral. New in Version 3.
CosIntegral
CosIntegral[z] gives the cosine integral function Ciz.
Mathematical function (see Section A.3.10). Ciz z costt dt. CosIntegral[z] has a branch cut
discontinuity in the complex z plane running from to . See page 774. See also: SinIntegral,
ExpIntegralE, ExpIntegralEi, FresnelC. New in Version 2.
Cot
Cot[z] gives the cotangent of z.
Mathematical function (see Section A.3.10). The argument of Cot is assumed to be in radians. (Multiply by
Degree to convert from degrees.) cotz tanz. Cos[z]/Sin[z] is automatically converted to Cot[z].
TrigFactorList[expr] does decomposition. See page 761. See also: ArcCot, TrigToExp, TrigExpand. New in
Version 1.
Coth
Coth[z] gives the hyperbolic cotangent of z.
Mathematical function (see Section A.3.10). Cosh[z]/Sinh[z] is automatically converted to Coth[z].
TrigFactorList[expr] does decomposition. See page 761. See also: ArcCoth, TrigToExp, TrigExpand.
Version 1.
New in
Count
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.
Level specifications are described on page 1041. See page 261.
Position. Related package: Statistics`DataManipulation` .
CreateDirectory Cyclotomic
1116
CreateDirectory
CreateDirectory["dir"] creates a directory.
CreateDirectory creates a subdirectory of your current working directory. The directory created by
CreateDirectory is initially empty. CreateDirectory returns the full name of the directory it creates, and
$Failed if it cannot create the directory. CreateDirectory has attribute Listable. See page 641. See also:
DeleteDirectory , RenameDirectory , CopyDirectory . New in Version 2.
Cross
Cross[a, b] gives the vector cross product of a and b.
If a and b are lists of length 3, corresponding to vectors in three dimensions, then Cross[a, b] is also a list of
length 3. Cross[a, b] can be entered in StandardForm and InputForm as a b, a H cross H b or a \[Cross] b.
Note the difference between \[Cross] and \[Times]. Cross is antisymmetric, so that Cross[b, a] is
-Cross[a, b]. In general, Cross[v , v , . . . , vn ] is a totally antisymmetric product which takes vectors of
length n and yields a vector of length n that is orthogonal to all of the vi . Cross[v , v , . . . ] gives the dual
(Hodge star) of the wedge product of the vi , viewed as one-forms in n dimensions. See page 119. See also: Dot,
Signature, Outer. New in Version 3.
Csc
Csc[z] gives the cosecant of z.
Mathematical function (see Section A.3.10). The argument of Csc is assumed to be in radians. (Multiply by Degree
to convert from degrees.) cscz sinz. 1/Sin[z] is automatically converted to Csc[z]. TrigFactorList[expr]
does decomposition. See page 761. See also: ArcCsc, TrigToExp, TrigExpand. New in Version 1.
Csch
Csch[z] gives the hyperbolic cosecant of z.
Mathematical function (see Section A.3.10). cschz sinhz. 1/Sinh[z] is automatically converted to Csch[z].
TrigFactorList[expr] does decomposition. See page 761. See also: ArcCsch, TrigToExp, TrigExpand. New in
Version 1.
Cuboid
Cuboid[{xmin, ymin, zmin}] is a three-dimensional graphics primitive that represents a unit
cuboid, oriented parallel to the axes.
Cuboid[{xmin, ymin, zmin}, {xmax, ymax, zmax}] specifies a cuboid by giving the
coordinates of opposite corners.
Each face of the cuboid (rectangular parallelepiped) is effectively a Polygon object. You can specify how the faces
and edges of the cuboid should be rendered using the same graphics directives as for polygons. The coordinates
of the corners of the cuboid can be given using Scaled. See page 520. See also: Polygon, Rectangle. Related
package: Graphics`Polyhedra` . New in Version 2.
Cyclotomic
Cyclotomic[n, x] gives the cyclotomic polynomial of order n in x.
The cyclotomic polynomial Cn x of order n is defined to be k x eikn , where the product runs over integers k
less than n that are relatively prime to n. See page 807. See also: Factor, Roots. New in Version 1.
CylindricalDecomposition Date
1117
CylindricalDecomposition
CylindricalDecomposition[ineqs, {x , x , ... }] finds a decomposition of the region
represented by the inequalities ineqs into cylindrical parts whose directions correspond to the
successive xi .
D
D[f, x] gives the partial derivative "f"x.
D[f, {x, n}] gives the multiple derivative "n f"xn .
D[f, x , x , ... ] gives ""x ""x f .
D[f, x] can be input as 8x f . The character 8 is entered as , pd , or \[PartialD]. The variable x is entered as a
subscript. All quantities that do not explicitly depend on the xi are taken to have zero partial derivative.
D[f, x , . . . , NonConstants -> {v , . . . }] specifies that the vi implicitly depend on the xi , so that they do not
have zero partial derivative. The derivatives of built-in mathematical functions are evaluated when possible in
terms of other built-in mathematical functions. Numerical approximations to derivatives can be found using N. D
uses the chain rule to simplify derivatives of unknown functions. D[f, x, y] can be input as 8x,y f . The character
\[InvisibleComma] , entered as , , ,, can be used instead of an ordinary comma. It does not display, but is still
interpreted just like a comma. See page 853. Implementation notes: see page 1070. See also: Dt, Derivative,
Maximize. Related packages: Calculus`VectorAnalysis` , NumericalMath`NLimit` . New in Version 1; modified in
Version 3.
Dashing
Dashing[{r , r , ... }] is a two-dimensional graphics directive which specifies that lines
which follow are to be drawn dashed, with successive segments of lengths r , r , ... (repeated
cyclically). The ri is given as a fraction of the total width of the graph.
Dashing can be used in both two- and three-dimensional graphics. Dashing[{ }] specifies that lines should be
solid. See page 501. See also: AbsoluteDashing , Thickness, GrayLevel, Hue, RGBColor, PlotStyle. New in
Version 1.
Date
Date[ ] gives the current local date and time in the form
{year, month, day, hour, minute, second}.
Date[ ] uses whatever date and time have been set on your computer system. It performs no corrections for time
zones, daylight saving time, etc. Date[z] gives the date in time zone z. This is inferred by knowing your local
date and time, and local time zone. The time zone is given as the number of hours to be added to Greenwich
mean time to obtain local time. All values returned by Date[ ] are integers, except the number of seconds. The
number of seconds is never more accurate than $TimeUnit. You can compare two lists returned by Date using
Order. See page 709. See also: AbsoluteTime, TimeZone, SessionTime, TimeUsed, ToDate, FromDate, FileDate,
$CreationDate. Related package: Miscellaneous`Calendar` . New in Version 2.
DeclarePackage DefaultColor
1118
DeclarePackage
DeclarePackage["context`", {"name ", "name ", ... }] declares that Needs["context`"]
should automatically be executed if a symbol with any of the specified names is ever used.
You can use DeclarePackage to tell Mathematica automatically to load a particular package when any of the
symbols defined in it are used. DeclarePackage creates symbols with the attribute Stub in the specified context.
DeclarePackage prepends context` to $ContextPath. See page 401. See also: Needs, $NewSymbol. New in
Version 2.
Decompose
Decompose[poly, x] decomposes a polynomial, if possible, into a composition of simpler
polynomials.
Decompose gives a list of the polynomials Pi which can be composed as P P x to give the original
polynomial. The set of polynomials Pi is not necessarily unique. Decomposition is an operation which is
independent of polynomial factorization. See page 807. See also: FactorList, Solve. New in Version 1.
Decrement
x-- decreases the value of x by 1, returning the old value of x.
Decrement has attribute HoldFirst.
Version 1.
New in
DedekindEta
DedekindEta[] gives the Dedekind eta modular elliptic function .
Mathematical function (see Section A.3.10). DedekindEta is defined only in the upper half of the complex plane.
It is not defined for real . The argument is the ratio of Weierstrass half-periods $ . DedekindEta satisfies
?
where ? is the discriminant, given in terms of Weierstrass invariants by g
g
. See page 782
for a discussion of argument conventions for elliptic functions. See page 787. See also: ModularLambda,
KleinInvariantJ , EllipticTheta , PartitionsP. New in Version 3.
Default
Default[f] , if defined, gives the default value for arguments of the function f obtained with a
_. pattern object.
Default[f, i] gives the default value to use when _. appears as the ith argument of f.
Default[f, i, n] gives the default value for the ith argument out of a total of n arguments.
_. represents an optional argument to a function, with a default value specified by Default. The necessary
values for Default[f] must always be defined before _. is used as an argument of f. Values defined for
Default[f] are stored in DefaultValues[f] . See page 1050. See also: Options. Related package:
Utilities`FilterOptions` . New in Version 1.
DefaultColor
DefaultColor is an option for graphics functions which specifies the default color to use for
lines, points, etc.
The setting for DefaultColor must be a CMYKColor, GrayLevel, Hue or RGBColor directive. The default setting is
DefaultColor->Automatic , which gives a default color complementary to the background specified. See
page 504. See also: Prolog, Background, FontColor, TextStyle. New in Version 2.
DefaultDuplicateCellStyle Delete
1119
DefaultDuplicateCellStyle
DefaultDuplicateCellStyle is an option for Notebook which specifies the default style to
use for cells created by automatic duplication of other cells in the notebook.
A typical default setting for DefaultDuplicateCellStyle is "Input". DefaultDuplicateCellStyle determines
the style for new cells created from cells with CellEditDuplicate->True or CellEvaluationDuplicate->True .
See page 619. See also: DefaultNewCellStyle . New in Version 3.
DefaultNewCellStyle
DefaultNewCellStyle is an option for Notebook which specifies the default style to use for
new cells created in the notebook.
A typical default setting for DefaultNewCellStyle is "Input".
new cells created interactively in the front end. See page 619.
Version 3.
Definition
Definition[symbol] prints as the definitions given for a symbol.
Definition has attribute HoldAll. Definition[symbol] prints as all values and attributes defined for symbol.
uses Definition. See page 625. See also: FullDefinition , Information. New in Version 1.
?s
Degree
Degree gives the number of radians in one degree. It has a numerical value of
.
You can multiply by Degree to convert from degrees to radians. Example: 30 Degree represents
. Degree
can be entered in StandardForm and InputForm as , , deg , or \[Degree]. Degree is printed in StandardForm
as . See page 765. New in Version 1; modified in Version 3.
Deletable
Deletable is an option for Cell which specifies whether the cell can be deleted interactively
using the front end.
With the setting Deletable->False at the notebook level, you can prevent any cells in any notebook from being
deleted. See pages 448 and 607. See also: Editable, Selectable. New in Version 3.
Delete
Delete[expr, n] deletes the element at position n in expr. If n is negative, the position is
counted from the end.
Delete[expr, {i, j, ... }] deletes the part at position {i, j, ... }.
Delete[expr, {{i , j , ... }, {i , j , ... }, ... }] deletes parts at several positions.
Example: Delete[{a, b, c, d}, 3] # a, b, d . Delete[{a, b, c, d}, {{1}, {3}}] # b, d .
Deleting the head of a particular element in an expression is equivalent to applying FlattenAt to the expression
at that point. Example: Delete[{a, {b}, c}, {2, 0}] # a, b, c . Deleting the head of a whole expression
makes the head be Sequence. Example: Delete[{a, b}, 0] # Sequence
a, b . , Delete works on
SparseArray objects. See pages 125 and 288. See also: Insert, MapAt, ReplacePart, FlattenAt, DeleteCases,
Drop, StringDrop. New in Version 2.
DeleteCases Denominator
1120
DeleteCases
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.
- DeleteCases[expr, pattern, levspec, n] removes the first n parts of expr which match pattern.
Example: DeleteCases[{1, a, 2, b}, _Integer] # a, b . With the option Heads -> True, you can delete
heads with DeleteCases. Deleting the head of a particular element in an expression is equivalent to applying
FlattenAt to the expression at that point. Example:
DeleteCases[{1, f[2, 3], 4}, f, {2}, Heads -> True] # 1, 2, 3, 4 . Level specifications are described
on page 1041. See page 262. See also: Cases, ReplaceAll, Delete. New in Version 2; modified in Version 4.1.
DeleteDirectory
DeleteDirectory["dir"] deletes the specified directory.
DeleteDirectory["dir", DeleteContents -> True] deletes dir and all files and directories that it contains.
DeleteDirectory["dir"] deletes the directory dir only if it contains no files. DeleteDirectory returns Null if
it succeeds in deleting a directory, and $Failed if it fails. See page 641. See also: CreateDirectory ,
DeleteFile. New in Version 2.
DeleteFile
DeleteFile["file"] deletes a file.
DeleteFile[{"file ", "file ", ... }] deletes a list of files.
DeleteFile returns Null if it succeeds in deleting files, and $Failed if it fails.
RenameFile, DeleteDirectory . New in Version 2.
See also:
DelimiterFlashTime
DelimiterFlashTime is an option for cells and notebooks which specifies how long in seconds
a delimiter should flash for when its matching delimiter is entered.
DelimiterFlashTime->0 makes delimiters not flash. A typical default setting is DelimiterFlashTime->0.3 ,
which makes matching delimiters flash for 0.3 seconds. Delimiters include parentheses, brackets and braces, as
well as [[, ]] and (* and *), and paired special characters such as /, 0. If you enter an unpaired closing
delimiter the standard Mathematica front end will beep. You can use the front end menu item Check Balance to
select ranges with balanced delimiters in an expressions. You can set DelimiterFlashTime at the level of a single
cell, a notebook, or the whole front end. See page 613. See also: ShowAutoStyles, SyntaxQ,
ShowCursorTracker . New in Version 3.
Denominator
Denominator[expr] gives the denominator of expr.
Denominator picks out terms which have superficially negative exponents. Numerator picks out all remaining
terms. An exponent is superficially negative if it has a negative number as a factor. The standard
representation of rational expressions as products of powers means that you cannot simply use Part to extract
denominators. Denominator can be used on rational numbers. See page 74. See also: ExpandDenominator ,
Rationals. New in Version 1.
DensityGraphics DensityPlot
1121
DensityGraphics
DensityGraphics[array] is a representation of a density plot.
array must be a rectangular array of real numbers, representing z values.
AspectRatio
Axes
AxesLabel
AxesOrigin
AxesStyle
Background
ColorFunction
ColorFunctionScaling
ColorOutput
DefaultColor
DisplayFunction
Epilog
FormatType
Frame
FrameLabel
FrameStyle
FrameTicks
ImageSize
Mesh
MeshRange
MeshStyle
PlotLabel
PlotRange
PlotRegion
Prolog
RotateLabel
TextStyle
Ticks
1
False
None
Automatic
Automatic
Automatic
Automatic
True
Automatic
Automatic
$DisplayFunction
{}
$FormatType
True
None
Automatic
Automatic
Automatic
True
Automatic
Automatic
None
Automatic
Automatic
{}
True
$TextStyle
Automatic
DensityPlot
DensityPlot[f, {x, xmin, xmax}, {y, ymin, ymax}] makes a density plot of f as a function
of x and y.
DensityPlot evaluates its arguments in a non-standard way (see page 1046). You should use Evaluate to evaluate
the function to be plotted if this can safely be done before specific numerical values are supplied. DensityPlot
has the same options as DensityGraphics, with the following additions:
Compiled
PlotPoints
True
25
DensityPlot has the default option setting Frame -> True. DensityPlot returns a DensityGraphics object,
with the MeshRange option set. See page 146. See also: ContourPlot. New in Version 1.
Depth Dialog
1122
Depth
Depth[expr] gives the maximum number of indices needed to specify any part of expr, plus one.
Raw objects have depth 1. The computation of Depth does not include heads of expressions. , Depth treats
SparseArray objects just like the corresponding ordinary lists. See page 239. See also: ArrayDepth, Level,
LeafCount, Length, Nest. New in Version 1; modified in Version 5.0.
Derivative
f' represents the derivative of a function f of one argument.
Derivative[n , n , ... ][f] is the general form, representing a function obtained from f by
differentiating n times with respect to the first argument, n times with respect to the second
argument, and so on.
f' is equivalent to Derivative[1][f] . f'' evaluates to Derivative[2][f] . You can think of Derivative as a
functional operator which acts on functions to give derivative functions. Derivative is generated when you apply
D to functions whose derivatives Mathematica does not know. Mathematica attempts to convert Derivative[n][f]
and so on to pure functions. Whenever Derivative[n][f] is generated, Mathematica rewrites it as
D[f [#]&, {#, n}]. If Mathematica finds an explicit value for this derivative, it returns this value. Otherwise, it
returns the original Derivative form. Example: Cos' # Sin
#1 & . Derivative[-n][f] represents the nth
indefinite integral of f. Derivative[{n , n , . . . }][f] represents the derivative of f [{x , x , . . . }] taken ni
times with respect to xi . In general, arguments given in lists in f can be handled by using a corresponding list
structure in Derivative. N[f'[x]] will give a numerical approximation to a derivative. See page 856. See also:
D, Dt. New in Version 1; modified in Version 4.0.
Det
Det[m] gives the determinant of the square matrix m.
Det[m, Modulus->n] computes the determinant modulo n. See page 905. Implementation notes: see page 1069.
See also: CharacteristicPolynomial , Minors, RowReduce, MatrixRank, NullSpace, Tr, Signature. New in
Version 1.
DiagonalMatrix
DiagonalMatrix[list] gives a matrix with the elements of list on the leading diagonal, and 0
elsewhere.
See page 896. See also: IdentityMatrix , Tr, KroneckerDelta .
LinearAlgebra`MatrixManipulation` . New in Version 1.
Related package:
Dialog
Dialog[ ] initiates a dialog.
Dialog[expr] initiates a dialog with expr as the current value of %.
Dialog creates a dialog which consists of a sequence of input and output lines. You can exit a dialog using
Return. With the global setting $IgnoreEOF = False, you can also exit a dialog by entering an end-of-file
character. If you exit with Return[expr], then expr is the value returned by the Dialog function. Otherwise, the
value returned is the expression on the last output line in the dialog. Dialog automatically localizes the values of
$Line, $MessageList and $Epilog. Dialog initially sets the local value of $Line to be equal to its global value.
This means that the numbering of input and output lines in the dialog follows the sequence outside the dialog.
When the dialog is exited, however, the numbering reverts to the sequence that would be followed if there had
been no dialog. Any local value assigned to $Epilog is evaluated when the dialog is exited. The main loop
within a dialog uses global variables such as $Pre and $Post. The option DialogSymbols :> {x, y, . . . } sets up
local values for variables within the dialog. DialogSymbols :> {x = x , . . . } defines initial values for the variables.
The option DialogProlog :> expr specifies an expression to evaluate before starting the dialog. Dialog first
localizes variables, then evaluates any expression specified by DialogProlog, then evaluates any argument you have
given for Dialog. See page 707. See also: TraceDialog, Input, $Inspector, ButtonBox. New in Version 2.
DialogProlog DigitQ
1123
DialogProlog
DialogProlog is an option for Dialog which can give an expression to evaluate before the
dialog starts.
You must use a delayed rule of the form DialogProlog :> expr to prevent expr from evaluating prematurely.
Expressions given by DialogProlog are evaluated after symbol values are localized, and before any expression
given as the argument of Dialog is evaluated. See page 708. See also: $Epilog. New in Version 2.
DialogSymbols
DialogSymbols is an option for Dialog which gives a list of symbols whose values should be
localized in the dialog.
DialogSymbols :> {x, y, . . . } specifies that x, y, . . . should have local values for the duration of the dialog.
DialogSymbols :> {x = x , . . . } defines initial values for variables. In addition to any symbols you specify,
Dialog always uses local values for $Epilog, $Line and $MessageList. The DialogSymbols option sets up local
values in a dialog in the same way that a Block enclosing the dialog would. See page 708. New in Version 2.
DigitBlock
DigitBlock is an option for NumberForm and related functions which specifies the maximum
length of blocks of digits between breaks.
The default setting is DigitBlock -> Infinity, which specifies that no breaks should be inserted.
DigitBlock -> n inserts a break every n digits. DigitBlock -> {nleft, nright} inserts a break every nleft digits
to the left of the decimal point, and every nright digits to the right of the decimal point. The setting for
NumberSeparator determines what string should be used at each break. See page 436. New in Version 1.
DigitCount
DigitCount[n, b, d] gives the number of d digits in the base b representation of n.
DigitCount[n, b] gives a list of the numbers of 1, 2, , b , 0 digits in the base b
representation of n.
DigitCount[n] gives a list of the numbers of 1, 2, , 9, 0 digits in the base 10 representation
of n.
DigitCount[n] is equivalent to DigitCount[n, 10, Mod[Range[10],10]] . Integer mathematical function (see
Section A.3.10). See page 755. See also: IntegerDigits, FromDigits, BitAnd, IntegerExponent. New in
Version 4.
DigitQ
DigitQ[string] yields True if all the characters in the string are digits in the range 0
through 9, and yields False otherwise.
See page 413.
New in Version 2.
Dimensions DirectoryName
1124
Dimensions
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.
expr must be a full array, with all the pieces of expr at a particular level having the same length. (The elements of
expr can then be thought of as filling up a hyper-rectangular region.) Each successive level in expr sampled by
Dimensions must have the same head. Example: Dimensions[{{a,b,c},{d,e,f}}] # 2, 3 . , For
SparseArray objects, Dimensions yields the dimensions of the corresponding ordinary lists. See page 900. See
also: ArrayDepth, VectorQ, MatrixQ. New in Version 1; modified in Version 5.0.
DiracDelta
DiracDelta[x] represents the Dirac delta function x.
DiracDelta[x , x , ... ] represents the multidimensional Dirac delta function x x ....
DiracDelta[x] returns 0 for all numeric x other than 0. DiracDelta can be used in integrals, integral transforms
and differential equations. Some transformations are done automatically when DiracDelta appears in a product
of terms. DiracDelta[x , x , . . . ] returns 0 if any of the xi are numeric and not 0. DiracDelta has attribute
Orderless. For exact numeric quantities, DiracDelta internally uses numerical approximations to establish its
result. This process can be affected by the setting of the global variable $MaxExtraPrecision . See page 879. See
also: UnitStep, If, PrincipalValue , Limit, KroneckerDelta. New in Version 4.
DirectedInfinity
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.
You can think of DirectedInfinity[z] as representing a point in the complex plane reached by starting at the
origin and going an infinite distance in the direction of the point z. The following conversions are made:
Infinity
-Infinity
ComplexInfinity
DirectedInfinity[1]
DirectedInfinity[-1]
DirectedInfinity[ ]
Directory
Directory[ ] gives the current working directory.
Directory returns the full name of the directory as a string. See page 636. See also: $Path, SetDirectory,
ResetDirectory , ParentDirectory , $HomeDirectory , DirectoryName, FileNames. New in Version 2.
DirectoryName
DirectoryName["name"] extracts the directory name from the specification for a file.
DirectoryName works differently on different computer systems. DirectoryName["directory"] is normally
equivalent to ParentDirectory["directory"] . DirectoryName["name", n] applies DirectoryName n times to name.
DirectoryName yields output appropriate for use in SetDirectory and ToFileName. If name contains no
directory specification, DirectoryName["name"] returns "". See page 639. See also: $Input, Directory. New
in Version 3.
DirectoryStack Display
1125
DirectoryStack
DirectoryStack[ ] gives the directory stack which represents the sequence of current
directories used.
DirectoryStack[ ] returns a list of full names of directories. Each call to SetDirectory prepends one element
to the directory stack; each call to ResetDirectory drops one. See page 636. New in Version 2.
DiscreteDelta
DiscreteDelta[n , n , ... ] gives the discrete delta function n n , equal to 1 if all the
ni are zero, and 0 otherwise.
DiscreteDelta[0] gives 1; DiscreteDelta[n] gives 0 for other numeric n. DiscreteDelta has attribute
Orderless. See page 882. See also: IdentityMatrix, UnitStep, If, Signature, DiracDelta. New in Version 4.
Disk
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}, {rx , ry }] yields an elliptical disk with semi-axes rx and ry .
Disk[{x, y}, r, { , }] represents a segment of a disk.
Angles are measured in radians counterclockwise from the positive x direction. Disk[{x, y}, {rx , ry }, { , }]
yields an elliptical disk segment obtained by transforming a circular disk segment with the specified starting and
ending angles. Scaled and Offset can be used in the radius specification (see notes for Circle). See page 496.
See also: Circle, Polygon. New in Version 2.
Dispatch
Dispatch[{lhs ->rhs , lhs ->rhs , ... }] generates an optimized dispatch table representation
of a list of rules. The object produced by Dispatch can be used to give the rules in
expr /. rules.
The use of Dispatch will never affect results that are obtained, but may make the application of long lists of rules
much faster. Lists of rules are usually scanned sequentially when you evaluate an expression like expr /. rules.
Rules such as a[1]->a1 and a[2]->a2, which cannot simultaneously apply, need not both be scanned explicitly.
Dispatch generates a dispatch table which uses hash codes to specify which sets of rules need actually be scanned
for a particular input expression. Lists of rules produced by assignments made with = and := are automatically
optimized with dispatch tables when appropriate. See page 302. See also: ReplaceAll, Compile. New in
Version 2.
Display
Display[channel, graphics] writes graphics or sound to the specified output channel in
Mathematica PostScript format.
Display[channel, graphics, "format"] writes graphics or sound in the specified format.
Display[channel, expr, "format"] writes boxes, cells or notebook expressions in the specified
format.
The output channel can be a single file or pipe, or a list of them. The graphics in Display can be Graphics,
Graphics3D, SurfaceGraphics, ContourGraphics , DensityGraphics or GraphicsArray. The graphics can also
include Sound. The expr in Display can be Cell, Notebook or any boxes, as generated by ToBoxes[expr]. Any
of the graphics formats specified for Export can be used. The following options can be given:
CharacterEncoding
ImageOffset
{}
{0, 0}
(continued)
1126
Display
(continued)
ImageResolution
ImageRotated
ImageSize
Automatic
False
Automatic
$DisplayFunction is usually given in terms of Display. If any of the specified files or pipes in channel are not
open, Display uses OpenWrite to open them, then closes these particular files or pipes when it has finished. In
many cases, Display calls the Mathematica notebook front end via MathLink. If the front end is not present, certain
capabilities of Display may not be available. When displaying text, Display may make use of fonts that are
specifically installed for Mathematica. See page 554. See also: Export, Write, Show, DisplayString, HTMLSave.
New in Version 1; modified in Version 3.
DisplayForm
DisplayForm[expr] prints with boxes inside expr shown in explicit two-dimensional or other
form.
In ordinary StandardForm output, boxes such as SubscriptBox are shown literally. In DisplayForm they are shown
as explicit two-dimensional constructs. Example: DisplayForm[SubscriptBox["x", "y"]] # xy . DisplayForm
acts as a wrapper, which affects printing, but not evaluation. See page 445. See also: FullForm,
ToExpression, ToBoxes. New in Version 3.
DisplayFunction
DisplayFunction is an option for graphics and sound functions that specifies the function to
apply to graphics and sound objects in order to display them.
The default setting for DisplayFunction in graphics functions is $DisplayFunction , and in sound functions is
$SoundDisplayFunction . A typical setting is DisplayFunction->Display[channel, #]&. Setting
DisplayFunction->Identity will cause the objects to be returned, but no display to be generated. See pages 134
and 553. See also: Show. New in Version 1.
DisplayString
DisplayString[graphics] generates a string giving graphics or sound in Mathematica PostScript
format.
DisplayString[graphics, "format"] generates a string giving graphics or sound in the
specified format.
DisplayString[expr, "format"] generates a string giving boxes, cells or notebook expressions
in the specified format.
The options and format settings for DisplayString are the same as for Display.
StringToStream . New in Version 3.
See also:
Distribute
Distribute[f [x , x , ... ]] distributes f over Plus appearing in any of the xi .
Distribute[expr, g] distributes over g.
Distribute[expr, g, f] performs the distribution only if the head of expr is f.
Distribute effectively implements the distributive law for operators f and g. Distribute explicitly constructs the
complete result of a distribution; Expand, on the other hand, builds up results iteratively, simplifying at each stage.
Example: Distribute[f[a+b,c+d]] # f
a, c f
a, d f
b, c f
b, d .
Distribute[f[a+b,g[x,y],c], g] # g
f
a b, x, c, f
a b, y, c . Distribute[expr, g, f, gp, fp]
gives gp and fp in place of g and f respectively in the result of the distribution. See page 256. See also: Expand,
Thread, Outer, Inner. New in Version 1.
Divide Dot
1127
Divide
x/y or Divide[x, y] is equivalent to x y^-1.
x/y is converted to x y^-1 on input. Divide[x, y] can be entered in StandardForm and InputForm as x
y,
x H div H y or x \[Divide] y. See page 29. New in Version 1; modified in Version 3.
DivideBy
x /= c divides x by c and returns the new value of x.
DivideBy has the attribute HoldFirst. x /= c is equivalent to x = x/c.
SubtractFrom, Set. New in Version 1.
Divisors
Divisors[n] gives a list of the integers that divide n.
Example: Divisors[12] # 1, 2, 3, 4, 6, 12 . Divisors[n, GaussianIntegers -> True] includes divisors
that are Gaussian integers. See page 750. See also: FactorInteger , EulerPhi. New in Version 1.
DivisorSigma
DivisorSigma[k, n] gives the divisor function k n.
Integer mathematical function (see Section A.3.10). k n is the sum of the kth powers of the divisors of n.
DivisorSigma[k, n, GaussianIntegers -> True] includes divisors that are Gaussian integers. See page 752.
See also: EulerPhi. New in Version 1.
Do
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.
Do uses the standard Mathematica iteration specification. Do evaluates its arguments in a non-standard way (see
page 1046). You can use Return, Break, Continue and Throw inside Do. Unless an explicit Return is used, the
value returned by Do is Null. See page 348. See also: For, While, Table, Nest, NestWhile, Fold. New in
Version 1.
Dot
a.b.c or Dot[a, b, c] gives products of vectors, matrices and tensors.
a.b gives an explicit result when a and b are lists with appropriate dimensions. It contracts the last index in a with
the first index in b. Various applications of Dot:
{a , a } . {b , b }
{a , a } . {{m , m }, {m , m }}
{{m , m }, {m , m }} . {a , a }
{{m , m }, {m , m }} . {{n , n }, {n , n }}
Examples: {a, b} . {c, d} # a c b d . {{a, b}, {c, d}} . {x, y} # a x b y, c x d y . The result
of applying Dot to two tensors Ti i in and Uj j jm is the tensor k Ti i in k Ukj jm . Applying Dot to a rank n
tensor and a rank m tensor gives a rank n m tensor. , Dot can be used on SparseArray objects, returning a
SparseArray object when possible. - When its arguments are not lists or sparse arrays, Dot remains unevaluated.
It has the attribute Flat. See pages 118 and 901. See also: Inner, Cross, Outer, NonCommutativeMultiply ,
Norm. Related package: Calculus`VectorAnalysis` . New in Version 1.
DownValues DSolve
1128
DownValues
DownValues[f] gives a list of transformation rules corresponding to all downvalues defined for
the symbol f.
You can specify the downvalues for f by making an assignment of the form DownValues[f] = list. The list
returned by DownValues has elements of the form HoldPattern[lhs] :> rhs. See page 322. See also: Set,
UpValues. New in Version 2; modified in Version 3.
DragAndDrop
DragAndDrop is an option for Cell which specifies whether to allow drag-and-drop editing on
the contents of the cell.
With DragAndDrop->True , dragging an already-selected region cuts the region from its original location, and pastes
it at the location you move to. DragAndDrop is more often set as a global option in the front end, rather than as
an option for individual cells. See page 615. See also: StructuredSelection . New in Version 3.
Drop
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.
Drop[list, {m, n, s}] gives list with elements m through n in steps of s dropped.
Drop[list, seq , seq , ... ] gives a nested list in which elements specified by seqi have been
dropped at level i in list.
Drop uses the standard sequence specification (see page 1040). Examples: Drop[{a,b,c,d,e}, 2] # c, d, e .
Drop[{a,b,c,d,e}, -3] # a, b . Drop[Range[7], {2, 5, 2}] # 1, 3, 5, 6, 7 . Drop can be used
on an object with any head, not necessarily List. Drop[list, seq , seq ] effectively drops all elements except
those in a submatrix of list. Example: Drop[{{a,b,c},{d,e,f}}, 1, -1] # d, e . , Drop works on
SparseArray objects. See pages 123 and 287. See also: Rest, Most, StringDrop, Take, Cases. Related package:
LinearAlgebra`MatrixManipulation` . New in Version 1; modified in Version 4.
-
DSolve
DSolve[eqn, y, x] solves a differential equation for the function y, with independent
variable x.
DSolve[{eqn , eqn , ... }, {y , y , ... }, x] solves a list of differential equations.
DSolve[eqn, y, {x , x , ... }] solves a partial differential equation.
DSolve[eqn, y[x], x] gives solutions for y[x] rather than for the function y itself. Example:
DSolve[y'[x] == 2 a x, y[x], x] # y
x a x2 C
1 . Differential equations must be stated in terms
of derivatives such as y'[x], obtained with D, not total derivatives obtained with Dt. , The list of equations given
to DSolve can include algebraic ones that do not involve derivatives. - DSolve generates constants of integration
indexed by successive integers. The option GeneratedParameters specifies the function to apply to each index. The
default is GeneratedParameters->C , which yields constants of integration C[1], C[2], . . . .
- GeneratedParameters->(Module[{C}, C]&) guarantees that the constants of integration are unique, even across
different invocations of DSolve. For partial differential equations, DSolve generates arbitrary functions C[n][. . . ].
(continued)
DSolve
1129
(continued)
Boundary conditions can be specified by giving equations such as y'[0] == b. Solutions given by DSolve
sometimes include integrals that cannot be carried out explicitly by Integrate. Dummy variables with local names
are used in such integrals. DSolve sometimes gives implicit solutions in terms of Solve. DSolve can solve linear
ordinary differential equations of any order with constant coefficients. It can solve also many linear equations up to
second order with non-constant coefficients. DSolve includes general procedures that handle a large fraction of the
nonlinear ordinary differential equations whose solutions are given in standard reference books such as Kamke.
DSolve can find general solutions for linear and weakly nonlinear partial differential equations. Truly nonlinear
partial differential equations usually admit no general solutions. , DSolve can handle not only pure differential
equations but also differential-algebraic equations. See page 869. Implementation notes: see page 1071. See
also: NDSolve, Solve, RSolve. Related packages: Calculus`VariationalMethods` , Calculus`VectorAnalysis` .
New in Version 2; modified in Version 5.0.
Dt
Dt[f,
Dt[f]
Dt[f,
Dt[f,
Dt[f, x , . . . , Constants -> {c , . . . }] specifies that the ci are constants, which have zero total derivative.
Symbols with attribute Constant are taken to be constants, with zero total derivative. If an object is specified to
be a constant, then all functions with that object as a head are also taken to be constants. All quantities not
explicitly specified as constants are assumed to depend on the xi . Example: Dt[x y] # y Dt
x x Dt
y .
Dt[x y, Constants -> {x}] # x Dt
y, Constants x . You can specify total derivatives by assigning
values to Dt[f], etc. See page 854. See also: D, Derivative. New in Version 1.
DumpSave
DumpSave["file.mx", symbol] writes definitions associated with a symbol to a file in internal
Mathematica format.
DumpSave["file.mx", "context`"] writes out definitions associated with all symbols in the
specified context.
DumpSave["file.mx", {object , object , ... }] writes out definitions for several symbols or
contexts.
DumpSave["package`", objects] chooses the name of the output file based on the computer
system used.
DumpSave["file"] saves all definitions in the current session.
DumpSave writes out definitions in a binary format that is optimized for input by Mathematica. Each file has a
plain text header identifying its type and contents. Files written by DumpSave can be read by Get. Files written
by DumpSave can only be read on the same type of computer system on which they were written. DumpSave will
not preserve open stream and link objects. Files written by DumpSave conventionally have names that end with
.mx. DumpSave["package`", . . . ] writes a file with a name such as package.mx/$SystemID/package.mx . You can
use DumpSave["file", "s"] to write out the definition for the value of a symbol s itself. DumpSave["file"] will save
the definitions for all symbols in the current session. You can typically read a dump file when you start
Mathematica by using the initfile command-line option. See page 627. See also: Save, LinkWrite. New in
Version 3.
E Eigensystem
1130
E
E is the exponential constant e (base of natural logarithms), with numerical value .
Mathematical constant (see Section A.3.11). E can be entered in StandardForm and InputForm as , , ee , or
\[ExponentialE] . In StandardForm and TraditionalForm, E is printed as . See page 765. Implementation
notes: see page 1067. See also: Exp. New in Version 1; modified in Version 3.
EdgeForm
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.
EdgeForm[ ] draws no edges of polygons. The directives RGBColor, CMYKColor, GrayLevel, Hue and Thickness
can be used in EdgeForm. EdgeForm does not affect the rendering of Line objects. No lines are ever drawn
when an edge is formed by one polygon intersecting another. See page 528. See also: FaceForm, Line. New in
Version 1.
Editable
Editable is an option for boxes, cells and notebooks which specifies whether their contents
can be edited interactively using the front end.
Even with the setting Editable->False, the contents of an object can still be copied as a whole. Editable is an
option for InterpretationBox and TagBox, as well as for StyleBox. Setting Editable->False effectively allows
you to write protect elements of notebooks. See pages 448 and 607. See also: CellEditDuplicate ,
Selectable, Copyable, Protected. New in Version 3.
-
Eigensystem
Eigensystem[m] gives a list {values, vectors} of the eigenvalues and eigenvectors of the
square matrix m.
, Eigensystem[{m, a}] gives the generalized eigenvalues and eigenvectors of m with respect
to a.
, Eigensystem[m, k] gives the eigenvalues and eigenvectors for the first k eigenvalues of m.
Eigensystem finds numerical eigenvalues and eigenvectors if m contains approximate real or complex numbers.
All the non-zero eigenvectors given are independent. If the number of eigenvectors is equal to the number of
non-zero eigenvalues, then corresponding eigenvalues and eigenvectors are given in corresponding positions in their
respective lists. If there are more eigenvalues than independent eigenvectors, then each extra eigenvalue is paired
with a vector of zeros. Eigensystem[m, ZeroTest -> test] applies test to determine whether expressions should
be assumed to be zero. The default setting is ZeroTest -> Automatic. The eigenvalues and eigenvectors satisfy
the matrix equation m.Transpose[vectors] == Transpose[vectors].DiagonalMatrix[values] . , Generalized
eigenvalues and eigenvectors satisfy m.Transpose[vectors] == a.Transpose[vectors].DiagonalMatrix[values] .
{vals, vecs} = Eigensystem[m] can be used to set vals and vecs to be the eigenvalues and eigenvectors
respectively. , Eigensystem[m, spec] is equivalent to Take[Eigensystem[m], spec]. , SparseArray objects can
be used in Eigensystem. See notes for Eigenvalues. See page 910. See also: NullSpace,
JordanDecomposition , SchurDecomposition , SingularValueDecomposition , QRDecomposition. Related package:
LinearAlgebra`Orthogonalization` . New in Version 1; modified in Version 5.0.
Eigenvalues Element
1131
Eigenvalues
Eigenvalues[m] gives a list of the eigenvalues of the square matrix m.
, Eigenvalues[{m, a}] gives the generalized eigenvalues of m with respect to a.
, Eigenvalues[m, k] gives the first k eigenvalues of m.
Eigenvalues finds numerical eigenvalues if m contains approximate real or complex numbers. Repeated
eigenvalues appear with their appropriate multiplicity. An n n matrix gives a list of exactly n eigenvalues, not
necessarily distinct. , If they are numeric, eigenvalues are sorted in order of decreasing absolute value. The
eigenvalues of a matrix m are those for which m . v == v for some non-zero eigenvector v. , The generalized
eigenvalues of m with respect to a are those for which m . v == a . v. , When matrices m and a have a
dimension-d shared null space, then d of their generalized eigenvalues will be Indeterminate. , Ordinary
eigenvalues are always finite; generalized eigenvalues can be infinite. , For numeric eigenvalues,
Eigenvalues[m, k] gives the k that are largest in absolute value. , Eigenvalues[m, -k] gives the k that are
smallest in absolute value. , Eigenvalues[m, spec] is always equivalent to Take[Eigenvalues[m], spec].
, The option settings Cubics->True and Quartics->True can be used to specify that explicit radicals should be
generated for all cubics and quartics. , SparseArray objects can be used in Eigenvalues. See page 910. See
also: SingularValueList , CharacteristicPolynomial , Det, Tr. New in Version 1; modified in Version 5.0.
Eigenvectors
Eigenvectors[m] gives a list of the eigenvectors of the square matrix m.
, Eigenvectors[{m, a}] gives the generalized eigenvectors of m with respect to a.
, Eigenvectors[m, k] gives the first k eigenvectors of m.
Eigenvectors finds numerical eigenvectors if m contains approximate real or complex numbers. Eigenvectors
corresponding to degenerate eigenvalues are chosen to be linearly independent. Eigenvectors are not normalized.
For an n n matrix, Eigenvectors always returns a list of length n. The list contains each of the independent
eigenvectors of the matrix, followed if necessary by an appropriate number of vectors of zeros. , Eigenvectors
with numeric eigenvalues are sorted in order of decreasing absolute value of their eigenvalues.
Eigenvectors[m, ZeroTest -> test] applies test to determine whether expressions should be assumed to be zero.
The default setting is ZeroTest -> Automatic. , Eigenvectors[m, spec] is equivalent to
Take[Eigenvectors[m], spec]. , SparseArray objects can be used in Eigenvectors. See notes for
Eigenvalues. See page 910. See also: NullSpace. Related package: LinearAlgebra`Orthogonalization` .
New in Version 1; modified in Version 5.0.
Element
Element[x, dom] or x dom asserts that x is an element of the domain dom.
Element[{x , x , ... }, dom] asserts that all the xi are elements of dom.
Element[patt, dom] asserts that any expression matching the pattern patt is an element of dom.
x dom can be entered as x H el H dom or x \[Element] dom.
Simplify and related functions. Possible domains are:
Algebraics algebraic numbers
Booleans
True or False
Complexes
complex numbers
Integers
integers
Primes
prime numbers
Rationals
rational numbers
Reals
real numbers
-
(continued)
1132
Element
(continued)
x dom if possible evaluates immediately when x is numeric. Examples: Pi Algebraics # False ;
Pi Reals # True . (x | x | . . . ) dom is equivalent to {x , x , . . . } dom. {x , x , . . . } dom
evaluates to (x | x | . . . ) dom if its truth or falsity cannot immediately be determined. See pages 73
and 816. See also: Simplify, MemberQ, IntegerQ, Assumptions, Condition, PatternTest, Equal, Less. New in
Version 4; modified in Version 5.0.
Eliminate
Eliminate[eqns, vars] eliminates variables between a set of simultaneous equations.
Equations are given in the form lhs == rhs. Simultaneous equations can be combined either in a list or with &&.
A single variable or a list of variables can be specified. Example:
Eliminate[{x == 2 + y, y == z}, y] # 2 z x . Variables can be any expressions. Eliminate works
primarily with linear and polynomial equations. See page 832. See also: Reduce, SolveAlways, Solve,
GroebnerBasis, Exists. New in Version 1.
EllipticE
EllipticE[m] gives the complete elliptic integral Em.
EllipticE[, m] gives the elliptic integral of the second kind E/m.
Mathematical function (see Section A.3.10). For ) ) , E/m m sin d. Em E /m.
See page 782 for a discussion of argument conventions for elliptic integrals. EllipticE[m] has a branch cut
discontinuity in the complex m plane running from to . EllipticE[, m] has a branch cut discontinuity
running along the ray from csc to infinity. See page 783. See also: JacobiZeta, JacobiAmplitude. New in
Version 1.
EllipticExp
EllipticExp[u, {a, b}] is the inverse for EllipticLog . It produces a list {x, y} such that
u == EllipticLog[{x, y}, {a, b}].
EllipticExp gives the generalized exponential associated with the elliptic curve y x
ax bx.
is the basis for computing Weierstrass functions in Mathematica. See page 788. New in Version 1.
EllipticExp
EllipticF
EllipticF[, m] gives the elliptic integral of the first kind F/m.
Mathematical function (see Section A.3.10). For ) ) , F/m m sin d. The complete
elliptic integral associated with EllipticF is EllipticK. EllipticF is the inverse of JacobiAmplitude . If
amu/m then u F/m. EllipticF[, m] has a branch cut discontinuity running along the ray from csc
to infinity. See page 782 for a discussion of argument conventions for elliptic integrals. See page 783. See also:
JacobiZeta, JacobiAmplitude . New in Version 1.
EllipticK
EllipticK[m] gives the complete elliptic integral of the first kind Km.
Mathematical function (see Section A.3.10). EllipticK is given in terms of the incomplete elliptic integral of the
first kind by Km F /m. See page 782 for a discussion of argument conventions for elliptic integrals.
EllipticK[m] has a branch cut discontinuity in the complex m plane running from to . See page 783.
See also: JacobiZeta, EllipticNomeQ . New in Version 1.
EllipticLog Encode
1133
EllipticLog
EllipticLog[{x, y}, {a, b}] gives the generalized logarithm associated with the elliptic
curve y x
ax bx.
EllipticLog[{x, y}, {a, b}] is defined as the value of the integral
square root is specified by giving the value of y such that y
EllipticExp. New in Version 1.
x
t
ax bx.
See also:
EllipticNomeQ
EllipticNomeQ[m] gives the nome q corresponding to the parameter m in an elliptic function.
Mathematical function (see Section A.3.10). EllipticNomeQ is related to EllipticK by
qm expeK mKmf. EllipticNomeQ[m] has a branch cut discontinuity in the complex m plane running
from to . See page 782. See also: InverseEllipticNomeQ . New in Version 3.
EllipticPi
EllipticPi[n, m] gives the complete elliptic integral of the third kind Bn/m.
EllipticPi[n, , m] gives the incomplete elliptic integral Bng /m.
Bn/m Bng /m.
New in Version 1.
EllipticTheta
EllipticTheta[a, u, q] gives the theta function ia u q (a
).
Mathematical function (see Section A.3.10).
nn
n q
n nn sinn u,
i u q q
n q
n
n n
i u q
cosn u, i
u q
See
n q cosnu, i
u q n q cosnu.
page 782 for a discussion of argument conventions for elliptic and related functions. See page 785. See also:
ModularLambda, DedekindEta, KleinInvariantJ. New in Version 1.
q
EllipticThetaPrime
EllipticThetaPrime[a, u, q] gives the derivative with respect to u of the theta function
ia u q (a
).
See notes for EllipticTheta.
New in Version 3.
Encode
Encode["source", "dest"] writes an encoded version of the file source to the file dest.
<<dest decodes the file before reading its contents.
Encode["source", "dest", "key"] produces an encoded file which must be read in using
Get["dest", "key"].
Encoded files contain only printable ASCII characters. They begin with a special sequence which is recognized by
Get. On certain computer systems Encode["source", "dest", MachineID->"ID"] can be used to generate an
encoded file which can be read in only on a computer with a particular $MachineID. No function is provided in
Mathematica to convert encoded files back to their original form. See page 626. See also: ReadProtected,
$MachineID. New in Version 2.
End Epilog
1134
End
End[ ] returns the present context, and reverts to the previous one.
Every call to End must be balanced by an earlier call to Begin. End[ ] resets the value of $Context. End[ ]
returns the present context name as a string of the form "context`". End[ ] does not modify $ContextPath. See
page 398. New in Version 1.
EndOfFile
EndOfFile is a symbol returned by Read when it reaches the end of a file.
Subsequent calls to Read will also give EndOfFile.
New in Version 1.
EndPackage
EndPackage[ ] restores $Context and $ContextPath to their values before the preceding
BeginPackage , and prepends the current context to the list $ContextPath .
Every call to EndPackage must be balanced by an earlier call to BeginPackage. EndPackage is typically used at
the end of a Mathematica package. EndPackage returns Null. EndPackage resets the values of both $Context
and $ContextPath . See page 398. New in Version 1.
EngineeringForm
EngineeringForm[expr] prints with all real numbers in expr given in engineering notation.
EngineeringForm[expr, n] prints with numbers given to n-digit precision.
In engineering notation the exponent is always arranged to be a multiple of 3. EngineeringForm takes the
same options as NumberForm, but uses a different default function for ExponentFunction . You can mix
EngineeringForm and BaseForm. EngineeringForm acts as a wrapper, which affects printing, but not
evaluation. See page 435. See also: ScientificForm, NumberForm. New in Version 1.
Environment
Environment["var"] gives the value of an operating system environment variable.
The values of environment variables are returned by Environment as strings. Environment returns $Failed if it
cannot find a value for the operating system variable you requested. The behavior of Environment depends on
the computer system you are using. See page 716. See also: Run, $CommandLine, $System. New in Version 1.
Epilog
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.
In three-dimensional graphics, two-dimensional graphics primitives can be specified by the Epilog option. The
graphics primitives are rendered in a 0,1 coordinate system. See page 504. See also: Prolog, AxesStyle,
PlotStyle, DisplayFunction . New in Version 2.
Equal EulerE
1135
Equal
lhs == rhs returns True if lhs and rhs are identical.
lhs == rhs is used to represent a symbolic equation, to be manipulated using functions like Solve. lhs == rhs
returns True if lhs and rhs are identical expressions. lhs == rhs returns False if lhs and rhs are determined to be
unequal by comparisons between numbers or other raw data, such as strings. Approximate numbers are
considered equal if they differ in at most their last eight binary digits (roughly their last two decimal digits).
2 == 2. gives True. e == e == e
gives True if all the ei are equal. Equal[e] gives True. For exact
numeric quantities, Equal internally uses numerical approximations to establish inequality. This process can be
affected by the setting of the global variable $MaxExtraPrecision . In StandardForm and InputForm, lhs == rhs
can be input as lhs \[Equal] rhs or lhs rhs. , It can also be input as lhs \[LongEqual] rhs or lhs rhs. See
page 86. See also: SameQ, Unequal, KroneckerDelta , Order, Element. New in Version 1; modified in Version 4.1.
Erf
Erf[z] gives the error function erfz.
Erf[z , z ] gives the generalized error function erfz erfz .
Mathematical function (see Section A.3.10).
erfz
z t
e dt.
Erf[z , z ] is given by
z t
e dt.
z
discontinuities. See page 775. See also: InverseErf, Erfc, Erfi, ExpIntegralE , ExpIntegralEi, FresnelC,
FresnelS. Related package: Statistics`NormalDistribution` . New in Version 1.
Erfc
Erfc[z] gives the complementary error function erfcz.
Erfc[z] is given by erfcz erfz.
Version 2.
New in
Erfi
Erfi[z] gives the imaginary error function erfizi.
See notes for Erf.
New in Version 3.
ErrorBox
ErrorBox[boxes] represents boxes that cannot be interpreted in input or output.
ErrorBox[boxes] typically displays as the raw form of boxes together with underlining that indicates parts that
cannot be interpreted. See page 447. See also: TagBox, InterpretationBox , ToExpression. New in Version 3.
EulerE
EulerE[n] gives the Euler number En .
EulerE[n, x] gives the Euler polynomial En x.
Mathematical function (see Section A.3.10). The Euler polynomials satisfy the generating function relation
n
ext et
The Euler numbers are given by En n En . See page 757. See also:
n En xt nd.
BernoulliB. New in Version 1.
EulerGamma Evaluator
1136
EulerGamma
EulerGamma is Eulers constant , with numerical value .
Mathematical constant (see Section A.3.11). See page 765. Implementation notes: see page 1067.
PolyGamma, StieltjesGamma , HarmonicNumber . New in Version 1.
See also:
EulerPhi
EulerPhi[n] gives the Euler totient function n.
Integer mathematical function (see Section A.3.10). n gives the number of positive integers less than or equal to
n which are relatively prime to n. See page 752. See also: FactorInteger , Divisors, MoebiusMu,
MultiplicativeOrder , CarmichaelLambda , PowerMod. New in Version 1.
Evaluatable
Evaluatable is an option for Cell which specifies whether a cell should be used as input to
be evaluated by the Mathematica kernel.
With Evaluatable->True , typing SHIFT-RETURN in the front end when the cell is selected will cause the contents of
the cell to be sent to the Mathematica kernel for evaluation. Evaluatable is more often set for styles of cells than
for individual cells. See page 608. See also: Evaluator, InitializationCell , CellEvaluationDuplicate . New
in Version 3.
Evaluate
Evaluate[expr] causes expr to be evaluated even if it appears as the argument of a function
whose attributes specify that it should be held unevaluated.
Example: Hold[Evaluate[1 + 1]] # Hold
2 . You can use Evaluate to override HoldFirst, etc. attributes of
built-in functions. Evaluate only overrides HoldFirst, etc. attributes when it appears directly as the head of the
function argument that would otherwise be held. See page 337. See also: ReleaseHold. New in Version 2.
,
EvaluationMonitor
EvaluationMonitor is an option for various numerical computation functions that gives an
expression to evaluate whenever functions derived from the input are evaluated numerically.
The option setting is normally given as EvaluationMonitor :> expr. The :> is used instead of -> to avoid expr
being immediately evaluated. Whenever expr is evaluated, all variables in the numerical computation are assigned
their current values. Block[{var = val , . . . }, expr] is effectively used. See page 977. See also: StepMonitor,
Sow, Print, Trace. New in Version 5.0.
EvaluationNotebook
EvaluationNotebook[ ] gives the notebook in which this function is being evaluated.
EvaluationNotebook returns a NotebookObject. See page 579.
ButtonNotebook , Notebooks, SelectionMove. New in Version 3.
Evaluator
Evaluator is an option for Cell which gives the name of the kernel to use to evaluate the
contents of a cell.
The default setting is typically Evaluator->"Local" . Evaluator is more often set at a global level or at the level
of whole notebooks than at the level of individual cells. See page 608. See also: InitializationCell . New in
Version 3.
EvenQ Expand
1137
EvenQ
EvenQ[expr] gives True if expr is an even integer, and False otherwise.
EvenQ[expr] returns False unless expr is manifestly an even integer (i.e., has head Integer, and is even). You
can use EvenQ[x] ^= True to override the normal operation of EvenQ, and effectively define x to be an even
integer. See pages 267 and 723. See also: IntegerQ, OddQ, TrueQ. New in Version 1.
ExcludedForms
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 .
The default setting for ExcludedForms is { }. A setting such as Gamma[_] will cause FullSimplify to treat
gamma functions as elementary objects which should not be transformed. See page 814. See also:
TimeConstraint, ComplexityFunction , Simplify, TrigFactor. New in Version 3.
,
Exists
Exists[x, expr] represents the statement that there exists a value of x for which expr is True.
Exists[x, cond, expr] states that there exists an x satisfying the condition cond for which expr
is True.
Exists[{x , x , ... }, expr] states that there exist values for all the xi for which expr is True.
Exists[x, expr] can be entered as ]x expr . The character ] can be entered as , ex , or \[Exists]. The variable x is
given as a subscript. Exists[x, cond, expr] can be entered as ]x,cond expr . In StandardForm, Exists[x, expr]
is output as ]x expr . Exists[x, cond, expr] is output as ]x,cond expr . Exists can be used in such functions as
Reduce, Resolve and FullSimplify. The condition cond is often used to specify the domain of a variable, as in
x Integers. Exists[x, cond, expr] is equivalent to Exists[x, cond && expr]. Exists[{x , x , . . . }, . . . ] is
equivalent to ]x1 ]x2 . The value of x in Exists[x, expr] is taken to be localized, as in Block. See page 847.
See also: ForAll, FindInstance, Resolve, Reduce, Element, Eliminate. New in Version 5.0.
Exit
Exit[ ] terminates a Mathematica kernel session.
Exit is a synonym for Quit. Exit terminates the kernel session even if called from within Dialog. On most
computer systems, Exit[n] can be used to pass the integer exit code n to the operating system. See pages 706
and 1057. See also: Return, $IgnoreEOF. New in Version 1.
Exp
Exp[z] is the exponential function.
Mathematical function (see Section A.3.10).
ExpToTrig. New in Version 1.
Expand
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.
Expand works only on positive integer powers. Expand applies only to the top level in expr.
Expand[expr, Modulus->p] expands expr reducing the result modulo p. See page 797. See also: Distribute,
Apart, Series, Factor, LogicalExpand, TrigExpand, PowerExpand, ExpandAll. New in Version 1; modified in
Version 3.
ExpandAll Exponent
1138
ExpandAll
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.
ExpandAll[expr] effectively maps Expand and ExpandDenominator onto every part of expr.
in Version 1.
New
ExpandDenominator
ExpandDenominator[expr] expands out products and powers that appear as denominators in
expr.
ExpandDenominator works only on negative integer powers. ExpandDenominator applies only to the top level in
expr. See page 801. See also: Expand, ExpandNumerator, ExpandAll, Together. New in Version 1.
ExpandNumerator
ExpandNumerator[expr] expands out products and powers that appear in the numerator of
expr.
ExpandNumerator works on terms that have positive integer exponents. ExpandNumerator applies only to the top
level in expr. See page 801. See also: Expand, ExpandDenominator , ExpandAll. New in Version 1.
ExpIntegralE
ExpIntegralE[n, z] gives the exponential integral function En z.
Mathematical function (see Section A.3.10). En z ezt tn dt. ExpIntegralE[n, z] has a branch cut
discontinuity in the complex z plane running from to . See page 774. See also: ExpIntegralEi, Erf,
LogIntegral, SinIntegral, CosIntegral. New in Version 1.
ExpIntegralEi
ExpIntegralEi[z] gives the exponential integral function Eiz.
Mathematical function (see Section A.3.10).
Eiz z et t dt, where the principal value of the integral is taken.
ExpIntegralEi[z] has a branch cut discontinuity in the complex z plane running from to .
See also: ExpIntegralE, Erf, LogIntegral, SinIntegral, CosIntegral. New in Version 1.
Exponent
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.
Example: Exponent[x^2 + a x^3, x] # 3 . The default taken for h is Max. Example:
Exponent[x^2 + a x^3, x, List] # 2, 3 . form can be a product of terms. Exponent works whether or
not expr is explicitly given in expanded form. , Exponent[0, x] is -Infinity. See page 799. See also:
Coefficient, Cases, IntegerExponent . New in Version 1; modified in Version 3.
ExponentFunction Export
1139
ExponentFunction
ExponentFunction is an option for NumberForm and related functions which determines the
exponent to use in printing approximate real numbers.
Functions like NumberForm first find the exponent that would make exactly one digit appear to the left of the
decimal point when the number is printed in scientific notation. Then they take this exponent and apply the
function specified by ExponentFunction to it. If the value obtained from this function is an integer, it is used as
the exponent of the number. If it is Null, then the number is printed without scientific notation. The argument
provided for the function specified by ExponentFunction is always an integer. In NumberForm, the default setting
for ExponentFunction never modifies the exponent, but returns Null for machine numbers with exponents between
and 5, and for high-precision numbers where insignificant zeros would have to be inserted if the number were
not printed in scientific notation. In ScientificForm , the default setting for ExponentFunction never returns
Null. In EngineeringForm, the default setting for ExponentFunction returns an exponent that is a multiple of 3.
In AccountingForm, the default setting for ExponentFunction always returns Null. See page 436. See also:
NumberFormat. New in Version 2.
-
Export
Export["file.ext", expr] exports data to a file, converting it to a format corresponding to the
file extension ext.
Export["file", expr, "format"] exports data to a file, converting it to the specified format.
Export can handle numerical and textual data, graphics, sounds, material from notebooks, and general expressions
in various formats. - The following basic formats are supported for numerical and textual data:
"CSV"
"Lines"
"List"
"Table"
"Text"
"TSV"
"UnicodeText"
"Words"
In "CSV", "List" and "Table" format, numbers are written in C or Fortran-like E notation when necessary.
In "CSV" format, columns are separated by commas, unless other settings are specified using
ConversionOptions . In "Table" format, columns are separated by spaces. Export["file.txt", expr] uses
"Text" format. Export["file.dat", expr] uses "Table" format. - The following additional formats are also
supported for numerical and textual data:
-
"FITS"
"HDF"
"MAT"
"MTX"
All graphics formats in Export can handle any type of 2D or 3D Mathematica graphics. They can also handle
Notebook and Cell objects. In some formats, lists of frames for animated graphics can be given. The following
options can be given when exporting graphics:
ImageResolution
ImageRotated
ImageSize
Automatic
False
Automatic
1140
Export
-
(continued)
The following graphics formats are independent of the setting for ImageResolution :
"EPS"
"MPS"
"PDF"
"PICT"
"SVG"
"WMF"
-
"BMP"
"DICOM"
"EPSI"
"EPSTIFF"
"GIF"
"JPEG"
"MGF"
"PBM"
"PGM"
"PNG"
"PNM"
"PPM"
"TIFF"
"XBitmap"
-
"DXF"
"STL"
"AIFF"
"AU"
"SND"
"WAV"
Notebook and Cell objects, as well as any box expression obtained from ToBoxes, can be exported in the
following formats:
"HTML"
"NB"
"TeX"
"XHTML+MathML"
These formats generate markup material which maintains much of the document structure that exists within
Mathematica. With HTML and TEX formats, Export operates like HTMLSave and TeXSave. , The following XML
formats are supported:
"ExpressionML"
"MathML"
"NotebookML"
"SVG"
"XML"
(continued)
Export
1141
(continued)
With format "MathML", box expressions are exported in terms of MathML presentation elements. Other
expressions are if possible exported in TraditionalForm format. - With format "XML", notebook or cell
expressions, and notebook objects, are exported as NotebookML. SymbolicXML expressions are exported as general
XML. Other expressions are exported as ExpressionML. , Arbitrary Mathematica expressions can be exported in the
following formats:
-
"Dump"
"Expression"
"ExpressionML"
ByteOrdering
CharacterEncoding
ConversionOptions
$ByteOrdering
Automatic
{}
Possible formats accepted by Export are given in the list $ExportFormats . Export["!prog", expr, "format"]
exports data to a pipe. See pages 207, 567 and 642. See also: Import, ExportString, $ExportFormats , Display,
Write, Put, TeXSave, HTMLSave, MathMLForm, DumpSave. New in Version 4; modified in Version 5.0.
-
ExportString
ExportString[expr, "format"] generates a string corresponding to expr exported in the
specified format.
Many graphics, sound and binary formats yield strings containing non-printable characters. See notes for Export.
See page 567. See also: ImportString, DisplayString . New in Version 4; modified in Version 5.0.
Expression
Expression is a symbol that represents an ordinary Mathematica expression in Read and
related functions.
See page 646.
New in Version 1.
ExpToTrig
ExpToTrig[expr] converts exponentials in expr to trigonometric functions.
ExpToTrig generates both circular and hyperbolic functions. ExpToTrig tries when possible to give results that do
not involve explicit complex numbers. See page 812. See also: TrigToExp, TrigReduce, ComplexExpand . New
in Version 3.
-
ExtendedGCD
-
ExtendedGCD[n , n , ... ] gives the extended greatest common divisor of the integers ni .
Integer mathematical function (see Section A.3.10). - ExtendedGCD[n , n , . . . ] returns a list {g, {r , r , . . . }}
where g is GCD[n , n , . . . ] and g r n r n . See page 752. See also: GCD. Related package:
Algebra`PolynomialExtendedGCD` . New in Version 1; modified in Version 4.2.
Extension FaceGrids
1142
Extension
Extension is an option for Factor, PolynomialGCD and related functions which specifies what
algebraic numbers to allow in the coefficients of resulting polynomials.
With the setting Extension->{a , a , . . . } any rational combination of the ai can appear. The ai must be
exact numbers. They can involve I, nth roots, and Root objects. The ai can be viewed as generators for the
algebraic number field in which the coefficients are assumed to lie. With the default setting Extension->None all
coefficients are required to be rational numbers, and any algebraic numbers that appear in input polynomials are
treated like independent variables. Extension->Automatic includes any algebraic numbers from the input
polynomials in the coefficient field. Extension->{a , a , . . . } includes both the ai and any algebraic numbers
from the input polynomials in the coefficient field. GaussianIntegers->True is equivalent to Extension->I.
See page 809. See also: Modulus, Algebraics. New in Version 3.
Extract
Extract[expr, list] extracts the part of expr at the position specified by list.
Extract[expr, {list , list , ... }] extracts a list of parts of expr.
Extract[expr, ... , h] extracts parts of expr, wrapping each of them with head h before
evaluation.
Extract[expr, {i, j, . . . }] is equivalent to Part[expr, i, j, . . . ]. The position specifications used by Extract
have the same form as those returned by Position, and used in functions such as MapAt and ReplacePart. You
can use Extract[expr, . . . , Hold] to extract parts without evaluation. - If expr is a SparseArray object,
Extract[expr, . . . ] extracts parts in the corresponding ordinary array. See page 286. See also: Part, Take,
PadLeft. New in Version 3.
FaceForm
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.
The graphics specifications gf and gb must be CMYKColor, GrayLevel, Hue or RGBColor directives, or SurfaceColor
objects. Specifications given outside of FaceForm will apply both to the front and back faces of polygons. The
front face of a polygon is defined to be the one for which the corners as you specify them are in counterclockwise
order (right-hand rule). See page 529. See also: EdgeForm. New in Version 1.
FaceGrids
FaceGrids is an option for three-dimensional graphics functions that specifies grid lines to
draw on the faces of the bounding box.
The following settings can be given for FaceGrids:
None
All
{face , face , . . . }
{{face , {xgrid , ygrid }}, . . . }
Faces are specified as {dirx , diry , dirz }, where two of the diri must be 0, and the third one must be +1 or -1.
Example: the x-y face with smallest z value is specified as {0, 0, -1}. For each face, specifications
{xgridi , ygridi } can be given to determine the arrangement of grid lines. These specifications have the form
described in the notes for GridLines. See page 553. See also: Ticks. New in Version 2.
Factor FactorList
1143
Factor
Factor[poly] factors a polynomial over the integers.
Factor[poly, Modulus->p] factors a polynomial modulo a prime p.
Factor[poly, Extension->{a , a , ... }] factors a polynomial allowing coefficients that are
rational combinations of the algebraic numbers ai .
Factor applies only to the top level in an expression. You may have to use Map, or apply Factor again, to reach
other levels. Factor[poly, GaussianIntegers->True] factors allowing Gaussian integer coefficients. If any
coefficients in poly are complex numbers, factoring is done allowing Gaussian integer coefficients. The exponents
of variables need not be positive integers. Factor can deal with exponents that are linear combinations of symbolic
expressions. When given a rational expression, Factor effectively first calls Together, then factors numerator and
denominator. With the default setting Extension->None, Factor[poly] will treat algebraic number coefficients in
poly like independent variables. Factor[poly, Extension->Automatic] will extend the domain of coefficients to
include any algebraic numbers that appear in poly. See page 797. Implementation notes: see page 1069. See
also: FactorList, FactorTerms, FactorSquareFree , Solve, Expand, Simplify, FactorInteger, TrigFactor. New
in Version 1; modified in Version 3.
Factorial
n! gives the factorial of n.
Mathematical function (see Section A.3.10). For non-integer n, the numerical value of n! is given by Gamma[1 + n].
See page 757. Implementation notes: see page 1067. See also: Gamma, Binomial. New in Version 1.
Factorial2
n!! gives the double factorial of n.
Mathematical function (see Section A.3.10). ndd nn n
. ndd is a product of even numbers for n even,
and odd numbers for n odd. See page 757. See also: Gamma. New in Version 1.
-
FactorInteger
FactorInteger[n] gives a list of the prime factors of the integer n, together with their
exponents.
Example: FactorInteger[2434500] # 2, 2, 3, 2, 5, 3, 541, 1 . For negative numbers, the unit
{-1, 1} is included in the list of factors. FactorInteger also works on rational numbers. The prime factors of
the denominator are given with negative exponents. FactorInteger[n, GaussianIntegers->True] factors over
Gaussian integers. , FactorInteger[m + I m] automatically works over the Gaussian integers. When necessary,
a unit of the form {-1, 1}, {I, 1} or {-I, 1} is included in the list of factors.
FactorInteger[n, FactorComplete->False] does fast but not necessarily complete factorization, and extracts
only factors that are easy to find. See page 750. Implementation notes: see page 1067. See also:
IntegerExponent, Prime, PrimeQ, Divisors. Related package: NumberTheory`FactorIntegerECM` . New in
Version 1; modified in Version 5.0.
FactorList
FactorList[poly] gives a list of the factors of a polynomial, together with their exponents.
The first element of the list is always the overall numerical factor. It is {1, 1} if there is no overall numerical
factor. Example: FactorList[3 (1+x)^2 (1-x)] # 3, 1, 1 x, 1, 1 x, 2 .
FactorList[poly, Modulus->p] factors modulo a prime p. FactorList[poly, GaussianIntegers->True] allows
Gaussian integer coefficients. FactorList[poly, Extension->{a , a , . . . }] allows coefficients that are arbitrary
rational combinations of the ai . See page 806. See also: FactorTermsList, TrigFactorList, CoefficientList,
Factor. New in Version 1; modified in Version 3.
FactorSquareFree Fibonacci
1144
FactorSquareFree
FactorSquareFree[poly] pulls out any multiple factors in a polynomial.
FactorSquareFree[poly, Modulus->p] pulls out multiple factors modulo a prime p.
FactorSquareFree[poly, Extension->Automatic] extends the coefficient field to include algebraic numbers that
appear in the coefficients of poly. See page 806. New in Version 1; modified in Version 3. See also:
FactorSquareFreeList .
FactorSquareFreeList
FactorSquareFreeList[poly] gives a list of square-free factors of a polynomial, together with
their exponents.
See page 806.
New in Version 1.
FactorTerms
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.
FactorTerms[poly, {x , x , ... }] pulls out any overall factor in poly that does not depend on
any of the xi .
Example: FactorTerms[3 - 3x^2] # 3 1 x2 .
respect to x. See notes for Factor. See page 797.
FactorTermsList
FactorTermsList[poly, {x , x , ... }] 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 .
See notes for FactorTerms.
New in Version 1.
False
False is the symbol for the Boolean value false.
See page 85.
New in Version 1.
Fibonacci
Fibonacci[n] gives the Fibonacci number Fn .
Fibonacci[n, x] gives the Fibonacci polynomial Fn x.
Integer mathematical function (see Section A.3.10). The Fn satisfy the recurrence relation Fn Fn Fn with
F F . For any complex value of n the Fn are given by the general formula Fn n n , where is
the golden ratio. The Fibonacci polynomial Fn x is the coefficient of tn in the expansion of t xt t . The
Fibonacci polynomials satisfy the recurrence relation Fn x xFn x Fn x. FullSimplify and
FunctionExpand include transformation rules for combinations of Fibonacci numbers with symbolic arguments
when the arguments are specified to be integers using n Integers. See page 757. Implementation notes: see
page 1067. See also: GoldenRatio. New in Version 3.
FileByteCount Find
1145
FileByteCount
FileByteCount["file"] gives the number of bytes in a file.
If a particular file is moved from one computer system to another, the number of bytes in the file as reported by
FileByteCount may change. See page 641. See also: StringLength, FileType. Related package:
Utilities`BinaryFiles` . New in Version 2.
FileDate
FileDate["file"] gives the date and time at which a file was last modified.
FileDate returns the date and time in the format used by Date.
FromDate. New in Version 2.
FileNames
FileNames[ ] lists all files in the current working directory.
FileNames["form"] lists all files in the current working directory whose names match the
string pattern form.
FileNames[{"form ", "form ", ... }] lists all files whose names match any of the formi .
FileNames[forms, {"dir ", "dir ", ... }] lists files with names matching forms in any of the
directories diri .
FileNames[forms, dirs, n] includes files that are in subdirectories up to n levels down.
The string pattern "form" can contain the metacharacters specified on page 1044. FileNames["*"] is equivalent to
FileNames[ ]. FileNames[forms, dirs, Infinity] looks for files in all subdirectories of the dirs. The list of files
returned by FileNames is sorted in the order generated by the function Sort. FileNames[forms, dirs, n] includes
names of directories only if they appear exactly at level n. The forms can include relative or absolute directory
specifications, in addition to names of files. Setting the option IgnoreCase -> True makes FileNames treat lowerand upper-case letters in file names as equivalent. On operating systems such as MS-DOS, FileNames always
treats lower- and upper-case letters in file names as equivalent. See page 638. See also: Directory, FileType,
Get. Related package: Utilities`Package` . New in Version 2; modified in Version 4.0.
FileType
FileType["file"] gives the type of a file, typically File, Directory or None.
FileType returns None if the file specified does not exist.
New in Version 2.
Find
Find[stream, "text"] finds the first line in an input stream that contains the specified string.
Find[stream, {"text ", "text ", ... }] finds the first line that contains any of the specified
strings.
Find breaks the input stream into records, delimited by record separators, and scans each record for the strings you
specify. Find returns as a string the first record which contains the specified text. If Find does not find any
record which contains the specified text before it reaches the end of the file, it returns EndOfFile.
(continued)
1146
Find
(continued)
AnchoredSearch
IgnoreCase
RecordSeparators
WordSearch
WordSeparators
False
False
{"\n"}
False
{" ", "\t"}
whether to require that the text searched for be at the beginning of a record
whether to treat lower- and upper-case as equivalent
separators for records
whether to require that the text searched for appear as a word
separators for words
The first argument to Find can be InputStream["name", n], or simply "name" if there is only one open input
stream with the specified name. You can open a file or pipe to get an InputStream object using OpenRead.
Find does not close streams after it finishes reading from them. See page 652. See also: Read, Skip,
StreamPosition , StringToStream , NotebookFind. New in Version 2.
,
FindFit
FindFit[data, expr, pars, vars] finds numerical values of the parameters pars that make expr
give a best fit to data as a function of vars.
The data can have the form {{x , y , ... , f }, {x , y , ... , f }, ... }, where the number of
coordinates x, y, ... is equal to the number of variables in the list vars.
The data can also be of the form {f , f , ... }, with a single coordinate assumed to take values
1, 2, ... .
FindFit returns a list of replacements for par , par , . . . . The expression expr must yield a numerical value when
pars and vars are all numerical. The expression expr can depend either linearly or nonlinearly on the pari . In the
linear case, FindFit finds a globally optimal fit. In the nonlinear case, it finds in general only a locally optimal
fit. FindFit[data, expr, {{par , p }, {par , p }, . . . }, vars] starts the search for a fit with
{par -> p , par -> p , . . . }. FindFit by default finds a least-squares fit. The option NormFunction -> f
specifies that the norm f[residual] should be minimized. The following options can be given:
AccuracyGoal
EvaluationMonitor
MaxIterations
Method
NormFunction
PrecisionGoal
StepMonitor
WorkingPrecision
Automatic
None
100
Automatic
Norm
Automatic
None
MachinePrecision
The default settings for AccuracyGoal and PrecisionGoal are WorkingPrecision/2 . The settings for
AccuracyGoal and PrecisionGoal specify the number of digits to seek in both the values of the parameters
returned, and the value of the NormFunction. FindFit continues until either of the goals specified by
AccuracyGoal or PrecisionGoal is achieved. Possible settings for Method are as for FindMinimum. See
page 929. Implementation notes: see page 1069. See also: FindMinimum, Fit, NMinimize, Interpolation.
Related packages: Statistics`NonlinearFit` , Statistics`LinearRegression` . New in Version 5.0.
FindInstance FindMinimum
1147
FindInstance
FindInstance[expr, vars] finds an instance of vars that makes the statement expr be True.
FindInstance[expr, vars, dom] finds an instance over the domain dom. Common choices of
dom are Complexes , Reals, Integers and Booleans.
FindInstance[expr, vars, dom, n] finds n instances.
FindInstance[expr, {x , x , . . . }] gives results in the same form as Solve: {{x -> val , x -> val , . . . }} if an
instance exists, and {} if it does not. expr can contain equations, inequalities, domain specifications and
quantifiers, in the same form as in Reduce. With exact symbolic input, FindInstance gives exact results. Even
if two inputs define the same mathematical set, FindInstance may still pick different instances to return. The
instances returned by FindInstance typically correspond to special or interesting points in the set.
FindInstance[expr, vars] assumes by default that quantities appearing algebraically in inequalities are real, while
all other quantities are complex. FindInstance[expr, vars, Integers] finds solutions to Diophantine equations.
FindInstance[expr, vars, Booleans] solves Boolean satisfiability for expr. FindInstance[expr, vars, Reals]
assumes that not only vars but also all function values in expr are real. FindInstance[expr && vars Reals, vars]
assumes only that the vars are real. FindInstance may be able to find instances even if Reduce cannot give a
complete reduction. Every time you run FindInstance with a given input, it will return the same output.
Different settings for the option RandomSeed -> n may yield different collections of instances. See pages 838
and 844. See also: Solve, Reduce, FindRoot, Minimize, Random. New in Version 5.0.
FindList
FindList["file", "text"] gives a list of lines in the file that contain the specified string.
FindList["file", {"text ", "text ", ... }] gives a list of all lines that contain any of the
specified strings.
FindList[{"file ", ... }, ... ] gives a list of lines containing the specified strings in any of the
filei .
FindList[files, text, n] includes only the first n lines found.
FindList returns {} if it fails to find any record which contains the specified text. If FindList opens a file or
pipe, it closes it again when it has finished. See notes for Find. See page 650. See also: ReadList. New in
Version 2.
,
FindMaximum
FindMaximum[f, {x, x }] searches for a local maximum in f, starting from the point x = x .
FindMaximum[f, {{x, x }, {y, y }, ... }] searches for a local maximum in a function of
several variables.
FindMaximum returns a list of the form {fmax , {x->xmax }}, where fmax is the maximum value of f found, and xmax is
the value of x for which it is found. See notes for FindMinimum. See page 107. See also: FindMinimum,
NMaximize, Maximize, FindFit, LinearProgramming , D. Related package: Statistics`NonlinearFit` . New in
Version 5.0.
FindMinimum
FindMinimum[f, {x, x }] searches for a local minimum in f, starting from the point x=x .
, FindMinimum[f, {{x, x }, {y, y }, ... }] searches for a local minimum in a function of
several variables.
(continued)
1148
FindMinimum
(continued)
FindMinimum returns a list of the form {fmin , {x->xmin }}, where fmin is the minimum value of f found, and xmin
is the value of x for which it is found. , If the starting point for a variable is given as a list, the values of the
variable are taken to be lists with the same dimensions. FindMinimum has attribute HoldAll.
- FindMinimum[f, {x, x , x }] searches for a local minimum in f using x and x as the first two values of x,
avoiding the use of derivatives. FindMinimum[f, {x, x , xmin , xmax }] searches for a local minimum, stopping the
search if x ever gets outside the range xmin to xmax . The results found by FindMinimum may correspond only to
local, but not global, minima. - The following options can be given:
AccuracyGoal
Compiled
EvaluationMonitor
Gradient
MaxIterations
Method
PrecisionGoal
StepMonitor
WorkingPrecision
Automatic
True
None
Automatic
100
Automatic
Automatic
None
MachinePrecision
The default settings for AccuracyGoal and PrecisionGoal are WorkingPrecision/2 . , The settings for
AccuracyGoal and PrecisionGoal specify the number of digits to seek in both the value of the position of the
minimum, and the value of the function at the minimum. FindMinimum continues until either of the goals
specified by AccuracyGoal or PrecisionGoal is achieved. - Possible settings for Method include
"ConjugateGradient" , "Gradient", "LevenbergMarquardt" , "Newton" and "QuasiNewton", with the default being
Automatic. See page 973. Implementation notes: see page 1068. See also: FindMaximum, NMinimize, Minimize,
FindFit, LinearProgramming , D, CholeskyDecomposition . New in Version 1; modified in Version 5.0.
-
FindRoot
FindRoot[lhs==rhs, {x, x }] searches for a numerical solution to the equation lhs==rhs,
starting with x=x .
FindRoot[{eqn , eqn , ... }, {{x, x }, {y, y }, ... }] searches for a numerical solution to
the simultaneous equations eqni .
- If the starting point for a variable is given as a list, the values of the variable are taken to be lists with the
same dimensions. FindRoot returns a list of replacements for x, y, . . . , in the same form as obtained from Solve.
FindRoot has attribute HoldAll. - FindRoot[lhs==rhs, {x, x , x }] searches for a solution using x and x as
the first two values of x, avoiding the use of derivatives. FindRoot[lhs==rhs, {x, xstart, xmin, xmax}] searches
for a solution, stopping the search if x ever gets outside the range xmin to xmax. If you specify only one starting
value of x, FindRoot searches for a solution using Newton methods. If you specify two starting values, FindRoot
uses a variant of the secant method. If all equations and starting values are real, then FindRoot will search only
for real roots. If any are complex, it will also search for complex roots. You can always tell FindRoot to search
for complex roots by adding 0. I to the starting value. , FindRoot[expr, . . . ] will search for a root of the
equation expr==0. - The following options can be given:
AccuracyGoal
Compiled
EvaluationMonitor
Jacobian
MaxIterations
PrecisionGoal
StepMonitor
WorkingPrecision
Automatic
True
None
Automatic
100
Automatic
None
MachinePrecision
(continued)
FindRoot
1149
(continued)
The default settings for AccuracyGoal and PrecisionGoal are WorkingPrecision/2 . , The setting for
AccuracyGoal specifies the number of digits of accuracy to seek both in the value of the position of the root, and
the value of the function at the root. , The setting for PrecisionGoal specifies the number of digits of precision
to seek in the value of the position of the root. , FindRoot continues until either of the goals specified by
AccuracyGoal or PrecisionGoal is achieved. If FindRoot does not succeed in finding a solution to the accuracy
you specify within MaxIterations steps, it returns the most recent approximation to a solution that it found. You
can then apply FindRoot again, with this approximation as a starting point. See page 960. Implementation
notes: see page 1068. See also: NSolve, Solve, FindMinimum, FindInstance. Related package:
NumericalMath`InterpolateRoot` . New in Version 1; modified in Version 5.0.
-
First
First[expr] gives the first element in expr.
First[expr] is equivalent to expr[[1]].
Version 1.
New in
Fit
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.
The data can have the form {{x , y , ... , f }, {x , y , ... , f }, ... }, where the number of
coordinates x, y, ... is equal to the number of variables in the list vars.
The data can also be of the form {f , f , ... }, with a single coordinate assumed to take values
1, 2, ... .
The argument funs can be any list of functions that depend only on the objects vars.
Fit[{f , f , . . . }, {1, x, x^2}, x] gives a quadratic fit to a sequence of values fi . The result is of the form
a + a x + a x^2, where the ai are real numbers. The successive values of x needed to obtain the fi are assumed
to be 1, 2, . . . . Fit[{{x , f }, {x , f }, . . . }, {1, x, x^2}, x] does a quadratic fit, assuming a sequence of x
values xi . Fit[{{x , y , f }, . . . }, {1, x, y}, {x, y}] finds a fit of the form a + a x + a y. Fit always
finds the linear combination of the functions in the list funs that minimizes the sum of the squares of deviations
from the values fi . Exact numbers given as input to Fit are converted to approximate numbers with machine
precision. See page 926. Implementation notes: see page 1069. See also: FindFit, Interpolation,
InterpolatingPolynomial , Solve, PseudoInverse , QRDecomposition , FindMinimum. Related packages:
Statistics`LinearRegression` . New in Version 1.
FixedPoint
FixedPoint[f, expr] starts with expr, then applies f repeatedly until the result no longer
changes.
FixedPoint[f, expr, n] stops after at most n steps. FixedPoint always returns the last result it gets. You can
use Throw to exit from FixedPoint before it is finished. FixedPoint[f, expr] applies SameQ to successive pairs of
results to determine whether a fixed point has been reached. NestWhile[f, expr, comp, 2] uses a general
comparison function. See page 241. See also: FixedPointList, NestWhile, Nest, ReplaceRepeated . New in
Version 1; modified in Version 3.
FixedPointList Floor
1150
FixedPointList
FixedPointList[f, expr] generates a list giving the results of applying f repeatedly, starting
with expr, until the results no longer change.
See notes for FixedPoint. FixedPointList[f, expr] gives expr as the first element of the list it produces.
last two elements in the list produced by FixedPointList are always the same. See page 241. See also:
NestWhileList, NestList, ComposeList. New in Version 2.
The
Flat
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.
Flat corresponds to the mathematical property of associativity. For a symbol f with attribute Flat,
f [f [a, b], f [c]] is automatically reduced to f [a, b, c]. Functions like Plus, Times and Dot are Flat. For a
Flat function f, the variables x and y in the pattern f [x_, y_] can correspond to any sequence of arguments.
The Flat attribute must be assigned before defining any values for a Flat function. See page 329. See also:
Orderless, OneIdentity. New in Version 1.
Flatten
Flatten[list] flattens out nested lists.
Flatten[list, n] flattens to level n.
Flatten[list, n, h] flattens subexpressions with head h.
Example: Flatten[{a,{b,c},{d}}] # a, b, c, d . Flatten unravels lists, effectively just deleting inner
braces. Flatten[list, n] effectively flattens the top level in list n times. Flatten[f [e, . . . ]] flattens out
subexpressions with head f. , Flatten flattens out levels in SparseArray objects just as in the corresponding
ordinary arrays. See pages 130 and 255. See also: Partition, FlattenAt. New in Version 1.
FlattenAt
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.
FlattenAt[expr, {i, j, ... }] flattens out the part of expr at position {i, j, ... }.
FlattenAt[expr, {{i , j , ... }, {i , j , ... }, ... }] flattens out parts of expr at several
positions.
Example: FlattenAt[{a, {b, c}, {d, e}}, 2] # a, b, c, d, e .
Flatten, Sequence, SlotSequence. New in Version 2.
Floor
Floor[x] gives the greatest integer less than or equal to x.
Mathematical function (see Section A.3.10). Examples: Floor[2.4] # 2 ; Floor[2.6] # 2 ;
Floor[-2.4] # 3 ; Floor[-2.6] # 3 . Floor[x] can be entered in StandardForm and InputForm as D x E,
H lf H x H rf H or \[LeftFloor] x \[RightFloor]. Floor[x] returns an integer when x is any numeric quantity,
whether or not it is an explicit number. Example: Floor[Pi^2] # 9 . For exact numeric quantities, Floor
internally uses numerical approximations to establish its result. This process can be affected by the setting of the
global variable $MaxExtraPrecision . See page 745. Implementation notes: see page 1067. See also: Ceiling,
Round, IntegerPart, Chop. New in Version 1; modified in Version 3.
Fold FontSlant
1151
Fold
Fold[f, x, list] gives the last element of FoldList[f, x, list].
Example: Fold[f, x, {a, b, c}] # f
f
f
x, a, b, c . You can use Throw to exit from Fold before it is
finished. See notes for FoldList. See page 243. See also: Nest. New in Version 2; modified in Version 3.
FoldList
FoldList[f, x, {a, b, ... }] gives {x, f [x, a], f [f [x, a], b], ... }.
Example: FoldList[f, x, {a, b, c}] # x, f
x, a, f
f
x, a, b, f
f
f
x, a, b, c .
FoldList[Plus, 0, list] generates cumulative sums of the elements in list. Example:
FoldList[Plus, 0, {a, b, c}] # 0, a, a b, a b c . With a length n list, FoldList generates a list of
length n . The head of list in FoldList[f, x, list] need not be List. See page 243. See also: Fold,
NestList, ComposeList, Partition, MapIndexed. New in Version 2.
FontColor
FontColor is an option for Cell, StyleBox and StyleForm which specifies the default color in
which to render text.
The setting for FontColor must be a CMYKColor, GrayLevel, Hue or RGBColor directive.
See also: Background, DefaultColor, FontWeight. New in Version 3.
FontFamily
FontFamily is an option for Cell, StyleBox and StyleForm which specifies the font family in
which text should be rendered.
The default is FontFamily->"Courier" . Other common choices are "Times" and "Helvetica". Mathematica will
combine settings for FontFamily, FontWeight, FontSlant, FontTracking and sometimes FontSize to construct a
complete name for the font you want. It will then use this name, together with any settings you have specified for
FontPostScriptName and FontNativeName to try to locate an appropriate font on your particular computer system.
When generating PostScript output on a printer or otherwise, settings you give for FontPostScriptName are
typically used in preference to other font specifications. Mathematica will try making replacements for the font
family name that you specify with the option FontSubstitutions . Mathematica by default uses heuristics such as
translating "Helvetica" to "Geneva" for appropriate computer systems. See pages 444 and 612. See also:
StyleForm, TextStyle. New in Version 3.
FontSize
FontSize is an option for Cell, StyleBox and StyleForm which specifies the default size in
printers points of the font in which to render text.
The size of a font is typically taken to be the distance from the top of the highest character to the bottom of the
of an inch. Fonts with the same nominal point size may
lowest character. A printers point is approximately
not look the same size to the eye. See pages 444 and 612. See also: FontWeight, FontTracking, ScriptMinSize,
ScriptSizeMultipliers . New in Version 3.
FontSlant
FontSlant is an option for Cell, StyleBox and StyleForm which specifies how slanted the
characters should be in text in the cell.
Typical settings are "Plain", "Italic" and "Oblique". With the "Oblique" setting, each character typically has
the same basic form as with "Plain", but is slanted. With the "Italic" setting, the basic form is different. See
notes for FontFamily. See pages 444 and 612. See also: AutoItalicWords , SingleLetterItalics . New in
Version 3.
FontSubstitutions ForAll
1152
FontSubstitutions
FontSubstitutions is an option for Cell, StyleBox and StyleForm which gives a list of
substitutions to try for font family names.
A typical setting is {"Geneva" -> "Helvetica"}. FontSubstitutions is used only for FontFamily settings, and
not for FontWeight, FontSlant and so on. See page 612. See also: FontFamily. New in Version 3.
FontTracking
FontTracking is an option for Cell, StyleBox and StyleForm which specifies how condensed
or expanded you want the font in which text is rendered to be.
Typical settings are "Condensed" and "Expanded". The default is "Plain". For some fonts and on some computer
systems, additional settings are supported, such as "Narrow", "Compressed", "SemiCondensed" , "Extended" and
"Wide". See notes for FontFamily. See page 612. New in Version 3.
FontWeight
FontWeight is an option for Cell, StyleBox and StyleForm which specifies how heavy the
characters in a font should be.
Typical settings are "Plain" and "Bold". For some fonts and on some computer systems, additional settings are
supported, such as "Thin", "Light", "Medium", "SemiBold", "Heavy", "Black" and "Fat". See notes for
FontFamily. See pages 444 and 612. New in Version 3.
For
For[start, test, incr, body] executes start, then repeatedly evaluates body and incr until test
fails to give True.
For evaluates its arguments in a non-standard way. For[start, test, incr] does the loop with a null body. The
sequence of evaluation is test, body, incr. The For exits as soon as test fails. If Break[ ] is generated in the
evaluation of body, the For loop exits. Continue[ ] exits the evaluation of body, and continues the loop by
evaluating incr. Unless Return[expr] or Throw[expr] is generated, the final value returned by For is Null.
Example: For[tot=0; i=0, i < 3, i++, tot += f[i]]. Note that the roles of semicolon and comma are reversed
relative to the C programming language. See page 352. See also: Do, While, Throw, NestWhile. New in
Version 1.
,
ForAll
ForAll[x, expr] represents the statement that expr is True for all values of x.
ForAll[x, cond, expr] states that expr is True for all x satisfying the condition cond.
ForAll[{x , x , ... }, expr] states that expr is True for all values of all the xi .
ForAll[x, expr] can be entered as \x expr . The character \ can be entered as , fa , or \[ForAll]. The variable x is
given as a subscript. ForAll[x, cond, expr] can be entered as \x,cond expr . In StandardForm, ForAll[x, expr]
is output as \x expr . ForAll[x, cond, expr] is output as \x,cond expr . ForAll can be used in such functions as
Reduce, Resolve and FullSimplify. The condition cond is often used to specify the domain of a variable, as in
x Integers. ForAll[x, cond, expr] is equivalent to ForAll[x, Implies[cond, expr]].
ForAll[{x , x , . . . }, . . . ] is equivalent to \x1 \x2 . The value of x in ForAll[x, expr] is taken to be
localized, as in Block. See page 847. See also: Exists, Resolve, Reduce, Element, Blank, SolveAlways. New
in Version 5.0.
Format FortranForm
1153
Format
Format[expr] prints as the formatted form of expr.
Assigning values to Format[expr] defines print forms for expressions.
Format[expr, form] gives a format for the specified form of output.
-
CForm
FortranForm
InputForm
MathMLForm
OutputForm
StandardForm
TeXForm
TraditionalForm
You can add your own forms for formatted output. Example: Format[s] := rhs defines a symbol s to print like
rhs. Format[f [ . . . ]] := rhs defines a function f to print like rhs. Definitions for Format are stored in the
FormatValues of a symbol. If you specify a new output format for an expression by giving a definition for
Format, there is no guarantee that Mathematica will be able to interpret this output format if it is used as input.
Definitions given for Format are used before those given for MakeBoxes. See page 473. See also: ToString,
ToBoxes, MakeBoxes, MakeExpression . New in Version 1; modified in Version 4.1.
FormatType
FormatType is an option for output streams, graphics and functions such as Text which
specifies the default format type to use when outputting expressions.
Standard values for FormatType are given in the notes for Format. SetOptions[stream, FormatType -> type]
resets the format type for an open stream. For graphics functions the default option setting is
FormatType :> $FormatType. For graphics functions box-based format types such as StandardForm and
TraditionalForm can be used only when a notebook front end is present. See pages 556 and 634. See also:
TextStyle, LanguageCategory. New in Version 1; modified in Version 3.
FormBox
FormBox[boxes, form] displays as boxes but specifies that rules associated with form should be
used to interpret boxes on input.
In InputForm and StandardForm \(form\`input\) yields FormBox[input, form]. \(\`input\) yields
FormBox[input, RawForm]. See page 447. See also: TagBox, InterpretationBox , ToExpression,
MakeExpression. New in Version 3.
FortranForm
FortranForm[expr] prints as a Fortran language version of expr.
Standard arithmetic functions and certain control structures are translated. FortranForm acts as a wrapper,
which affects printing, but not evaluation. The width of output lines must be set explicitly by giving the option
PageWidth -> n for the relevant output stream. SetOptions[$Output, PageWidth -> 72] uses a line width of 72
characters for standard Mathematica output. No declarations are generated. See pages 213 and 425. See also:
CForm, Compile. New in Version 1.
Fourier FourierSinTransform
1154
Fourier
Fourier[list] finds the discrete Fourier transform of a list of complex numbers.
The discrete Fourier transform vs of a list ur of length n is by default defined to be
n
Note
that the zero frequency term appears at position 1 in the resulting list. Other definitions are used in some
scientific and technical fields. Different choices of definitions can be specified using the option
FourierParameters . With the setting FourierParameters -> {a, b} the discrete Fourier transform computed by
Fourier is a
nr ur eibrsn . Some common choices for {a, b} are {0, 1} (default), {-1, 1} (data
n
analysis), {1, -1} (signal processing). The setting b effectively corresponds to conjugating both input and
output lists. To ensure a unique inverse discrete Fourier transform, /b/ must be relatively prime to n. The list of
data supplied to Fourier need not have a length equal to a power of two. The list given in Fourier[list] can be
nested to represent an array of data in any number of dimensions. The array of data must be rectangular. If the
elements of list are exact numbers, Fourier begins by applying N to them. , Fourier can be used on
SparseArray objects. See page 935. Implementation notes: see page 1069. See also: InverseFourier ,
FourierTransform , Fit. New in Version 1; modified in Version 4.
FourierCosTransform
FourierCosTransform[expr, t, ] gives the symbolic Fourier cosine transform of expr.
FourierCosTransform[expr, {t , t , ... }, { , , ... }] gives the multidimensional
Fourier cosine transform of expr.
!
The Fourier cosine transform of a function ft is by default defined to be ft cost dt. Other definitions
are used in some scientific and technical fields. Different choices of definitions can be specified using the option
FourierParameters . With
"the setting FourierParameters->{a, b} the Fourier cosine transform computed by
/b/
FourierCosTransform is
See notes for FourierTransform . See page 878. See also:
a ft cosbt dt.
New in Version 4.
FourierSinTransform
FourierSinTransform[expr, t, ] gives the symbolic Fourier sine transform of expr.
FourierSinTransform[expr, {t , t , ... }, { , , ... }] gives the multidimensional
Fourier sine transform of expr.
!
The Fourier sine transform of a function ft is by default defined to be ft sint dt. Other definitions are
used in some scientific and technical fields. Different choices of definitions can be specified using the option
FourierParameters . With"the setting FourierParameters->{a, b} the Fourier sine transform computed by
/b/
FourierSinTransform is
See notes for FourierTransform. See page 878. See also:
a ft sinbt dt.
New in Version 4.
FourierTransform Frame
1155
FourierTransform
FourierTransform[expr, t, ] gives the symbolic Fourier transform of expr.
FourierTransform[expr, {t , t , ... }, { , , ... }] gives the multidimensional Fourier
transform of expr.
The Fourier transform of a function ft is by default defined to be
in some scientific and technical fields. Different choices of definitions can be specified using the option
FourierParameters . "
With the setting FourierParameters->{a, b} the Fourier transform computed by
/b/
ibt dt.
FourierTransform is
Some common choices for {a, b} are {0, 1} (default; modern
a ft e
physics), {1, -1} (pure mathematics; systems engineering), {-1, 1} (classical physics), {0, -2 Pi} (signal
processing). Assumptions and other options to Integrate can also be given in FourierTransform.
FourierTransform[expr, t, ] yields an expression depending on the continuous variable that represents the
symbolic Fourier transform of expr with respect to the continuous variable t. Fourier[list] takes a finite list of
numbers as input, and yields as output a list representing the discrete Fourier transform of the input. In
TraditionalForm, FourierTransform is output using . See page 876. See also: FourierSinTransform ,
FourierCosTransform , Fourier, InverseFourierTransform , LaplaceTransform , Integrate. New in Version 4.
FractionalPart
FractionalPart[x] gives the fractional part of x.
Mathematical function (see Section A.3.10). FractionalPart[x] in effect takes all digits to the right of the
decimal point and drops the others. Examples: FractionalPart[2.4] # 0.4 ; FractionalPart[2.6] # 0.6 ;
FractionalPart[-2.4] # 0.4 ; FractionalPart[-2.6] # 0.6 . FractionalPart[x] + IntegerPart[x] is
always exactly x. FractionalPart[x] yields a result when x is any numeric quantity, whether or not it is an
explicit number. Example: FractionalPart[Pi^2] # 9 2.
For exact numeric quantities, FractionalPart
internally uses numerical approximations to establish its result. This process can be affected by the setting of the
global variable $MaxExtraPrecision . See page 745. See also: IntegerPart, Mod. New in Version 3.
FractionBox
FractionBox[x, y] represents xy in input and output.
Inside \( . . . \) FractionBox[x, y] can be input as x \/ y. In a notebook a FractionBox can be created using
/ . moves out of the fraction. In StandardForm and InputForm, FractionBox[x, y] is interpreted on
input as x/y. The axis of FractionBox[x, y] is taken to go through the fraction line. The baseline lies below the
axis by the distance between the axis and the bottom of characters such as ( in the current font. The width of
the fraction line can be given in x-heights as the setting for the SpanLineThickness option in StyleBox. If
FractionBox[x, y] does not fit on a single line, it is output as x / y. In StandardForm, explicit FractionBox
objects are output literally. You can use DisplayForm to see the display form of such objects. See page 445. See
also: OverscriptBox, GridBox. New in Version 3.
Frame
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. See pages 511 and 514. See also: Boxed. New in Version 2.
FrameBox FreeQ
1156
FrameBox
FrameBox[box] displays with a frame drawn around box.
In StandardForm and InputForm, FrameBox is by default ignored, so that FrameBox[box] is interpreted just as box
would be. In StandardForm, explicit FrameBox objects are output literally. You can use DisplayForm to see the
display form of such objects. See page 446. See also: StyleBox, CellFrame, ColumnLines, RowLines. New in
Version 3.
FrameLabel
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. Any expression can
be specified as a label. It will be given in OutputForm. Arbitrary strings of text can be given as "text". Labels for
the vertical edges of the frame are by default written vertically. RotateLabel -> False specifies that they should
be horizontal. See page 514. See also: AxesLabel, PlotLabel. New in Version 2.
FrameStyle
FrameStyle is an option for two-dimensional graphics functions that specifies how the edges
of a frame should be rendered.
FrameStyle -> style specifies that all edges of the frame are to be generated with the specified graphics directive,
or list of graphics directives. FrameStyle -> {{xmstyle}, {ymstyle}, . . . } specifies that different edges of the
frame should be generated with different styles. The edges are ordered clockwise starting from the bottom edge. All
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 frame edges is specified by the option DefaultColor. See
page 514. See also: Prolog, Epilog, AxesStyle. New in Version 2.
FrameTicks
FrameTicks is an option for two-dimensional graphics functions that specifies tick marks for
the edges of a frame.
The following settings can be given for FrameTicks:
None
Automatic
{xmticks, ymticks, . . . }
When tick mark specifications are given separately for each edge, the edges are ordered clockwise starting from
the bottom of the frame. With the Automatic setting, tick marks are usually placed at points whose coordinates
have the minimum number of digits in their decimal representation. For each edge, tick marks can be specified as
described in the notes for Ticks. See page 514. See also: Ticks, GridLines, FaceGrids. New in Version 2.
FreeQ
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.
form can be a pattern. Example: FreeQ[f[x^2] + y^2, x^_] # False . FreeQ looks at the heads of raw
expressions, testing whether those heads match form. See page 268. See also: MemberQ, Count. New in
Version 1.
FresnelC FromDate
1157
FresnelC
FresnelC[z] gives the Fresnel integral Cz.
z
Mathematical function (see Section A.3.10). FresnelC[z] is given by cos t dt. FresnelC[z] is an entire
function of z with no branch cut discontinuities. See page 775. See also: Erf, CosIntegral. New in Version 3.
FresnelS
FresnelS[z] gives the Fresnel integral Sz.
z
Mathematical function (see Section A.3.10). FresnelS[z] is given by sin t dt. FresnelS[z] is an entire
function of z with no branch cut discontinuities. See page 775. See also: Erf, SinIntegral. New in Version 3.
FromCharacterCode
FromCharacterCode[n] gives a string consisting of the character with integer code n.
FromCharacterCode[{n , n , ... }] gives a string consisting of the sequence of characters
with codes ni .
FromCharacterCode[{{n , n , ... }, {n , ... }, ... }] gives a list of strings.
FromCharacterCode[ ... , "encoding"] uses the specified character encoding.
The integer n must lie between 0 and 65535, as returned by ToCharacterCode. For n between 0 and 127,
FromCharacterCode returns ASCII characters. For n between 129 and 255, it returns ISO Latin-1 characters. For
other n it returns characters specified by the standard Mathematica encoding based on Unicode.
InputForm[FromCharacterCode[n]] gives the full name assigned to a special character with character code n.
Whether a particular character generated by FromCharacterCode can be rendered on your output device will
depend on what fonts and drivers you are using. Encodings supported in FromCharacterCode[ . . . , "encoding"]
are listed in the notes for $CharacterEncoding . See page 417. See also: ToCharacterCode , CharacterRange ,
$CharacterEncoding . Related package: Utilities`BinaryFiles` . New in Version 2; modified in Version 4.
FromContinuedFraction
FromContinuedFraction[list] reconstructs a number from the list of its continued fraction
terms.
FromContinuedFraction[{a , a , a
, . . . }] returns a a a
. The ai can be symbolic.
FromContinuedFraction[{a , a , . . . , {b , b , . . . }}] returns the exact number whose continued fraction terms
start with the ai , then consist of cyclic repetitions of the bi . FromContinuedFraction acts as the inverse of
ContinuedFraction . See page 754. Implementation notes: see page 1067. See also: ContinuedFraction ,
Rationalize, FromDigits, Fold. New in Version 4.
FromDate
FromDate[date] converts a date of the form {y, m, d, h, m, s} to an absolute number of
seconds since the beginning of January 1, 1900.
FromDate converts between the forms returned by Date and AbsoluteTime. FromDate assumes that both the date
and the absolute time are to be given in the same time zone. See page 710. See also: ToDate. Related
package: Miscellaneous`Calendar` . New in Version 2.
FromDigits FullGraphics
1158
FromDigits
FromDigits[list] constructs an integer from the list of its decimal digits.
FromDigits[list, b] takes the digits to be given in base b.
Example: FromDigits[{3,7,4}] # 374 . FromDigits is effectively the inverse of IntegerDigits.
FromDigits[{list, n}, b] takes n to be an exponent, while FromDigits[{{list, {rep}}, n}, b] takes rep to be
repeated, so that FromDigits can also be used as the inverse of RealDigits. Since IntegerDigits[n] discards
the sign of n, FromDigits[IntegerDigits[n]] is Abs[n] not just n. The digits in list and the base b need not be
positive integers, and can be any expression. If Indeterminate appears in list, it is assumed to signify unknown
digits beyond the precision of an approximate real number. See page 725. See also: IntegerDigits,
RealDigits, FromContinuedFraction , NumberForm, DigitCount. New in Version 3; modified in Version 4.0.
FrontEndExecute
FrontEndExecute[expr] sends expr to be executed by the Mathematica front end.
FrontEndExecute[expr] sends expr to $FrontEnd via MathLink using LinkWrite. The standard Mathematica front
end can handle only specific notebook manipulation commands such as NotebookApply , NotebookLocate and
SelectedNotebook . It uses the versions of these commands in the FrontEnd` context.
FrontEndExecute[FrontEndToken["name"]] executes named commands in the front end, typically corresponding
to menu items. See page 594. See also: LinkWrite, ButtonEvaluator . New in Version 3.
FullDefinition
FullDefinition[symbol] prints as the definitions given for symbol, and all symbols on which
these depend.
FullDefinition has attribute HoldAll. FullDefinition[symbol] recursively prints as all definitions for the
symbol, and for the symbols that appear in these definitions, unless those symbols have the attribute Protected.
FullDefinition does not show rules associated with symbols that have attribute ReadProtected. See page 625.
See also: Definition, Save, Information. New in Version 1.
-
FullForm
FullForm[expr] prints as the full form of expr, with no special syntax.
Example: FullForm[a + b^2] # Plus
a, Power
b, 2 . FullForm acts as a wrapper, which affects printing,
but not evaluation. , FullForm always effectively uses "PrintableASCII" as the setting for $CharacterEncoding .
See page 424. See also: InputForm, TreeForm. New in Version 1; modified in Version 5.0.
FullGraphics
FullGraphics[g] takes a graphics object, and generates a new one in which objects specified
by graphics options are given as explicit lists of graphics primitives.
FullGraphics generates explicit graphics primitives for objects specified by options such as Axes, Ticks, etc.
page 490. See also: AbsoluteOptions . New in Version 2.
See
FullSimplify FunctionExpand
1159
FullSimplify
FullSimplify[expr] tries a wide range of transformations on expr involving elementary and
special functions, and returns the simplest form it finds.
FullSimplify[expr, assum] does simplification using assumptions.
FullSimplify will always yield at least as simple a form as Simplify, but may take substantially longer.
following options can be given:
Assumptions
ComplexityFunction
ExcludedForms
$Assumptions
Automatic
{ }
TimeConstraint
TransformationFunctions
Infinity
Automatic
The
FullSimplify uses RootReduce on expressions that involve Root objects. FullSimplify does transformations
on most kinds of special functions. , You can specify default assumptions for FullSimplify using Assuming.
See notes for Simplify. See pages 68 and 813. Implementation notes: see page 1070. See also: Simplify,
Factor, Expand, PowerExpand, ComplexExpand, TrigExpand, Element, FunctionExpand, Assuming. New in
Version 3; modified in Version 5.0.
Function
Function[body] or body& is a pure function. The formal parameters are # (or #1), #2, etc.
Function[x, body] is a pure function with a single formal parameter x.
Function[{x , x , ... }, body] is a pure function with a list of formal parameters.
Example: (# + 1)&[x] # 1 x . Map[(# + 1)&, {x, y, z}] # 1 x, 1 y, 1 z . When Function[body]
or body& is applied to a set of arguments, # (or #1) is replaced by the first argument, #2 by the second, and so on.
#0 is replaced by the function itself. If there are more arguments supplied than #i in the function, the remaining
arguments are ignored. ## stands for the sequence of all arguments supplied. ##n stands for arguments from
number n on. f[##, ##2]& [x, y, z] # f
x, y, z, y, z . Function is analogous to in LISP or formal
logic. Function has attribute HoldAll. The function body is evaluated only after the formal parameters have been
replaced by arguments. The named formal parameters xi in Function[{x , . . . }, body] are treated as local, and
are renamed xi $ when necessary to avoid confusion with actual arguments supplied to the function. Function is
treated as a scoping construct (see Section A.3.8). Function[params, body, {attr , attr , . . . }] represents a pure
function that is to be treated as having attributes attri for the purpose of evaluation. See page 248. See also:
Apply, CompiledFunction . New in Version 1.
-
FunctionExpand
FunctionExpand[expr] tries to expand out special and certain other functions in expr, when
possible reducing compound arguments to simpler ones.
FunctionExpand[expr, assum] expands using assumptions.
FunctionExpand uses a large collection of rules. FunctionExpand applies to certain trigonometric functions as
well as special functions. FunctionExpand is automatically called by FullSimplify. Assumptions in
FunctionExpand can be specified as in Simplify. Example: FunctionExpand[expr, x Reals] performs
expansion assuming that x is real. , FunctionExpand has the option Assumptions, specifying default assumptions
to be appended to assum. , The default setting for the Assumptions option is $Assumptions. , You can specify
default assumptions for FunctionExpand using Assuming. See page 792. Implementation notes: see page 1070.
See also: TrigExpand, TrigToExp, ComplexExpand, FullSimplify. New in Version 3; modified in Version 5.0.
FunctionInterpolation GaussianIntegers
1160
FunctionInterpolation
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.
You can use FunctionInterpolation to generate a single InterpolatingFunction object from an expression
containing several such objects. The option InterpolationPrecision specifies the precision of values to be
returned by the InterpolatingFunction generated. See notes for Interpolation. See page 935. See also:
ListInterpolation , InterpolatingPolynomial , Table. New in Version 3.
Gamma
Gamma[z] is the Euler gamma function z.
Gamma[a, z] is the incomplete gamma function a z.
Gamma[a, z , z ] is the generalized incomplete gamma function a z a z .
Mathematical function (see Section A.3.10).
gamma function satisfies a z
z
a t
z t e dt.
The incomplete
integral z ta et dt. Note that the arguments in the incomplete form of Gamma are arranged differently from
those in the incomplete form of Beta. Gamma[z] has no branch cut discontinuities. Gamma[a, z] has a branch
cut discontinuity in the complex z plane running from to . FullSimplify and FunctionExpand include
transformation rules for Gamma. See page 770. Implementation notes: see page 1068. See also: Factorial,
LogGamma, GammaRegularized , InverseGammaRegularized , PolyGamma, RiemannSiegelTheta . New in Version 1.
GammaRegularized
GammaRegularized[a, z] is the regularized incomplete gamma function Qa z.
Mathematical function (see Section A.3.10). In non-singular cases, Qa z a za.
GammaRegularized[a, z , z ] is the generalized regularized incomplete gamma function, defined in non-singular
cases as Gamma[a, z , z ]/Gamma[a]. Note that the arguments in GammaRegularized are arranged differently from
those in BetaRegularized . See page 770. See also: InverseGammaRegularized . New in Version 2.
GaussianIntegers
GaussianIntegers is an option for FactorInteger , PrimeQ, Factor and related functions
which specifies whether factorization should be done over Gaussian integers.
With GaussianIntegers -> False, factorization is done over the ordinary ring of integers . With
GaussianIntegers -> True, factorization is done over the ring of integers with i adjoined eif. Example:
FactorInteger[13, GaussianIntegers -> True] # , 1, 2 3 , 1, 3 2 , 1 . The Gaussian
primes used when GaussianIntegers -> True are chosen to have both real and imaginary parts positive. The
first entry in the list given by FactorInteger with GaussianIntegers -> True may be -1 or -I. See page 751.
See also: Extension, ComplexExpand. New in Version 2.
GCD GeneratedParameters
1161
GCD
GCD[n , n , ... ] gives the greatest common divisor of the integers ni .
Integer mathematical function (see Section A.3.10). GCD[n , . . . ] gives the integer factors common to all the ni .
GCD also works with rational numbers; GCD[r , r , . . . ] gives the greatest rational number r for which all the
ri /r are integers. GCD has attributes Flat and Orderless. See page 749. See also: PolynomialGCD, Rational,
LCM, ExtendedGCD. New in Version 1.
GegenbauerC
GegenbauerC[n, m, x] gives the Gegenbauer polynomial Cm
n x.
GegenbauerC[n, x] gives the renormalized form limm# Cm
n xm.
Mathematical function (see Section A.3.10). Explicit polynomials are given for integer n and for any m. Cm
n x
satisfies the differential equation x y$$ m xy$ nn my . The Gegenbauer polynomials are
orthogonal on the interval with weight function x m , corresponding to integration over a unit
hypersphere. GegenbauerC[n, 0, x] is always zero. GegenbauerC[n, m, z] has a branch cut discontinuity in
the complex z plane running from to . See page 766. See also: LegendreP, ChebyshevT, ChebyshevU.
New in Version 1.
General
General is a symbol to which general system messages are attached.
When you refer to a message with name s::tag in On or Off, the text of the message is obtained from
General::tag if no specific message named s::tag exists. See page 480. New in Version 1.
GenerateConditions
GenerateConditions is an option for Integrate that specifies whether explicit conditions on
parameters should be generated in the results of definite integrals.
The default setting is GenerateConditions->Automatic , which is equivalent to a setting of True for
one-dimensional integrals. See page 867. See also: Assumptions. New in Version 3.
GeneratedCell
GeneratedCell is an option for Cell which indicates whether the cell was generated from the
kernel.
Cells created interactively using only operations in the front end have GeneratedCell->False . The setting for
GeneratedCell is used to determine which cells should be considered as Mathematica output. See page 608. See
also: CellAutoOverwrite . New in Version 3.
,
GeneratedParameters
GeneratedParameters is an option which specifies how parameters generated to represent the
results of various symbolic operations should be named.
The typical default setting is GeneratedParameters->C . The setting GeneratedParameters->f specifies that
successive generated parameters should be named f[1], f[2], . . . . In typical cases, the f[i] are used to
parameterize families of solutions to equations. The f[i] usually correspond to free parameters, but are also
sometimes used to represent arbitrary functions. The f[i] have indices that start at 1 for each invocation of a
particular symbolic operation. GeneratedParameters->(Module[{C}, C]&) guarantees that parameters are unique,
even across different invocations of a function. GeneratedParameters is an option to such functions as DSolve,
RSolve and Reduce. See page 841. See also: C, Unique, Module. New in Version 5.0.
Get Graphics
1162
Get
<<name reads in a file, evaluating each expression in it, and returning the last one.
On systems with graphical interfaces, there will usually be graphical tools for reading in files. If name is the name
of a Mathematica context, ending with a ` context mark character, then Get will process this name to find the file to
read. If name is the name of a file, any .m extension must be included explicitly. Get can read .mx files of
Mathematica definitions written by DumpSave. <<"name" is equivalent to <<name. The double quotes can be omitted
if the name is of the form specified on page 1033. If a file with name file.mx is found to be a directory, Get will
look for a file with a name like file.mx/$SystemID/file.mx . If the file found by <<name is a directory, Mathematica
will try to load the file init.m in that directory. Get by default successively searches for files in the directories
specified by the elements of $Path. Get[name, Path->{"dir ", "dir ", . . . }] successively searches for files in
each of the diri . Syntax errors in Mathematica input files are reported in the standard form:
filename: line: syntax error in expr. Get continues attempting to read a file even after a syntax error has been
detected. However, if an error is detected, $Context and $ContextPath are reset to the values they had when Get
was called. During the execution of Get, the global variable $Input is set to the name of the file being read.
Get["file", "key"] reads a file which has been encoded using Encode["source", "file", "key"]. See page 623.
See also: Read, Install, RunThrough, Put, Splice, FileNames, ToFileName, ToExpression, NotebookGet. New
in Version 1; modified in Version 3.
Glaisher
Glaisher is Glaishers constant with numerical value
.
Mathematical constant (see Section A.3.11). Glaishers constant A satisfies logA
Riemann zeta function. See page 765. See also: Zeta. New in Version 4.
GoldenRatio
GoldenRatio is the golden ratio , with numerical value
.
Mathematical constant (see Section A.3.11).
New in Version 1.
Goto
Goto[tag] scans for Label[tag], and transfers control to that point.
Goto first scans any compound expression in which it appears directly, then scans compound expressions which
enclose this one. See pages 353 and 354. See also: Throw, Switch, Which. New in Version 1; modified in
Version 3.
Graphics
Graphics[primitives, options] represents a two-dimensional graphical image.
Graphics is displayed using Show.
Circle[{x, y}, r]
Disk[{x, y}, r]
Line[{{x , y }, . . . }]
Point[{x, y}]
Polygon[{{x , y }, . . . }]
PostScript["string"]
Raster[array]
RasterArray[garray]
Rectangle[{xmin, ymin}, {xmax, ymax}]
Text[expr, {x, y}]
circle
filled disk
line
point
filled polygon
PostScript code to include verbatim
array of gray levels
array of colored cells
filled rectangle
text
(continued)
Graphics
1163
(continued)
AbsoluteDashing[{w , . . . }]
AbsolutePointSize[d]
AbsoluteThickness[w]
CMYKColor[c, m, y, k]
Dashing[{w , . . . }]
GrayLevel[i]
Hue[h]
PointSize[d]
RGBColor[r, g, b]
Thickness[w]
The following
AspectRatio
Axes
AxesLabel
AxesOrigin
AxesStyle
Background
ColorOutput
DefaultColor
DisplayFunction
Epilog
FormatType
Frame
FrameLabel
FrameStyle
FrameTicks
GridLines
ImageSize
PlotLabel
PlotRange
PlotRegion
Prolog
RotateLabel
TextStyle
Ticks
1/GoldenRatio
False
None
Automatic
Automatic
Automatic
Automatic
Automatic
$DisplayFunction
{}
$FormatType
False
None
Automatic
Automatic
None
Automatic
None
Automatic
Automatic
{}
True
$TextStyle
Automatic
Nested lists of graphics primitives can be given. Specifications such as GrayLevel remain in effect only until the
end of the list which contains them. Graphics[Graphics3D[ . . . ]] generates an ordinary 2D graphics object
corresponding to 3D graphics. The same works for SurfaceGraphics, ContourGraphics and DensityGraphics.
The standard print form for Graphics[ . . . ] is -Graphics-. InputForm prints the explicit list of primitives. See
page 487. See also: Plot, ListPlot, ParametricPlot . Related package: Graphics`Graphics` . New in
Version 1.
Graphics3D Graphics3D
1164
Graphics3D
Graphics3D[primitives, options] represents a three-dimensional graphical image.
Graphics3D is displayed using Show.
Cuboid[{xmin, ymin, zmin}, . . . ]
Line[{{x , y , z }, . . . }]
Point[{x, y, z}]
Polygon[{{x , y , z }, . . . }]
Text[expr, {x, y, z}]
AbsoluteDashing[{w , . . . }]
AbsolutePointSize[d]
AbsoluteThickness[w]
CMYKColor[c, m, y, k]
Dashing[{w , . . . }]
EdgeForm[spec]
FaceForm[spec]
GrayLevel[i]
Hue[h]
PointSize[d]
RGBColor[r, g, b]
SurfaceColor[spec]
Thickness[w]
The following
AmbientLight
AspectRatio
Axes
AxesEdge
AxesLabel
AxesStyle
Background
Boxed
BoxRatios
BoxStyle
ColorOutput
DefaultColor
DisplayFunction
Epilog
FaceGrids
FormatType
ImageSize
Lighting
LightSources
PlotLabel
PlotRange
PlotRegion
PolygonIntersections
Prolog
GrayLevel[0]
Automatic
False
Automatic
None
Automatic
Automatic
True
Automatic
Automatic
Automatic
Automatic
$DisplayFunction
{}
None
$FormatType
Automatic
True
(see below)
None
Automatic
Automatic
True
{}
Graphics3D
1165
(continued)
RenderAll
Shading
SphericalRegion
TextStyle
Ticks
ViewCenter
ViewPoint
ViewVertical
True
True
False
$TextStyle
Automatic
Automatic
{1.3, -2.4, 2.}
{0, 0, 1}
Nested lists of graphics primitives can be given. Specifications such as GrayLevel remain in effect only until the
end of the list which contains them. The standard print form for Graphics3D[ . . . ] is -Graphics3D-. InputForm
prints the explicit list of primitives. The default light sources used are
{{{1,0,1}, RGBColor[1,0,0]}, {{1,1,1}, RGBColor[0,1,0]}, {{0,1,1}, RGBColor[0,0,1]}} .
Graphics3D[SurfaceGraphics[ . . . ]] can be used to convert a SurfaceGraphics object into Graphics3D
representation. Graphics[SurfaceGraphics[ . . . ]] generates a representation in terms of ordinary 2D graphics
primitives. See page 487. See also: Plot3D, SurfaceGraphics , ParametricPlot3D . Related packages:
Graphics`Graphics3D` , Graphics`Shapes`, Graphics`Polyhedra` . New in Version 1.
GraphicsArray
GraphicsArray[{g , g , ... }] represents a row of graphics objects.
GraphicsArray[{{g , g , ... }, ... }] represents a two-dimensional array of graphics
objects.
You can display a GraphicsArray object using Show. GraphicsArray sets up identical rectangular display areas
for each of the graphics objects it contains. GraphicsArray takes the same options as Graphics, with the defaults
for Ticks and FrameTicks changed to None. GraphicsArray takes the additional option GraphicsSpacing, which
specifies the spacing between the rectangular areas containing each graphics object. The default setting is
GraphicsSpacing -> 0.1. The options DisplayFunction, ColorOutput and CharacterEncoding are ignored for
graphics objects given inside GraphicsArray. See pages 139 and 487. See also: Rectangle, RasterArray,
TableForm, GridBox. New in Version 2.
GraphicsSpacing
GraphicsSpacing is an option for GraphicsArray which specifies the spacing between
elements in the array.
GraphicsSpacing -> 0 inserts no horizontal or vertical spacing, so that all adjacent rectangular areas in the array
are shown abutting. GraphicsSpacing -> {h, v} specifies horizontal and vertical spacing to use.
GraphicsSpacing -> s is equivalent to GraphicsSpacing -> {s, s}. The spacing is given in scaled coordinates,
relative to each rectangular area in the array. Example: a horizontal spacing of 0.1 yields an array in which the
rectangular areas are separated horizontally by distances equal to 0.1 of their widths. See page 141. See also:
TableSpacing. New in Version 2.
GrayLevel
GrayLevel[level] is a graphics directive which specifies the gray-level intensity with which
graphical objects that follow should be displayed.
The gray level must be a number between 0 and 1. 0 represents black; 1 represents white. On display devices
with no native gray-level capability, dither patterns are typically used, as generated by the PostScript interpreter.
See page 499. See also: RGBColor, Hue, Raster. New in Version 1.
Greater GridBox
1166
Greater
x > y yields True if x is determined to be greater than y.
x > x > x
yields True if the xi form a strictly decreasing sequence.
Greater gives True or False when its arguments are real numbers. Greater does some simplification when its
arguments are not numbers. For exact numeric quantities, Greater internally uses numerical approximations to
establish numerical ordering. This process can be affected by the setting of the global variable $MaxExtraPrecision .
See page 86. See also: GreaterEqual, Less, Positive, Element. New in Version 1; modified in Version 3.
GreaterEqual
x >= y or x y yields True if x is determined to be greater than or equal to y.
x x x
yields True if the xi form a non-increasing sequence.
x y can be entered as x H >= H y or x \[GreaterEqual] y. GreaterEqual gives True or False when its
arguments are real numbers. GreaterEqual does some simplification when its arguments are not numbers. For
exact numeric quantities, GreaterEqual internally uses numerical approximations to establish numerical ordering.
This process can be affected by the setting of the global variable $MaxExtraPrecision . In StandardForm,
GreaterEqual is printed using . x y, entered as x H >/ H y or x \[GreaterSlantEqual] y, can be used on
input as an alternative to x y. See page 86. See also: Greater, LessEqual, Element. New in Version 1;
modified in Version 3.
-
GridBaseline
GridBaseline is an option for GridBox which specifies where the baseline of the grid
represented by the GridBox should be assumed to be.
GridBaseline determines how a GridBox will be positioned vertically with respect to other boxes, say in a RowBox.
GridBaseline->pos specifies that position pos in the GridBox should be assumed to be the baseline of the
GridBox and should therefore be aligned with baselines of other boxes. Possible settings are:
Axis
Baseline
Bottom
Center
Top
A setting of {pos, {i, j}} specifies that the position pos in the i, j element of the GridBox should be assumed to
be the baseline for the whole GridBox. See page 449. See also: RowAlignments , AdjustmentBox, CellBaseline.
New in Version 3; modified in Version 5.0.
GridBox
GridBox[{{box , box , ... }, {box , box , ... }, ... }] represents a two-dimensional grid
of boxes or strings in input and output.
In a notebook, columns of a GridBox can be added using , and rows using J (CONTROL-RETURN). ,
or a menu item can be used to start building a GridBox. You can use tab to move from one entry in a GridBox
to the next. moves out of the whole GridBox. In StandardForm and InputForm, GridBox[list] is
interpreted as list. You can place parentheses around a GridBox to make it look more like a matrix, but these are
by default ignored when the GridBox is interpreted.
(continued)
GridBox
1167
(continued)
ColumnAlignments
ColumnLines
ColumnsEqual
ColumnSpacings
ColumnWidths
GridBaseline
GridDefaultElement
RowAlignments
RowLines
RowMinHeight
RowsEqual
RowSpacings
Center
False
False
0.8
Automatic
Axis
"\[Placeholder]"
Baseline
False
1.0
False
1.0
GridBox is a low-level construct that works only for two-dimensional arrays; TableForm and MatrixForm are
higher-level constructs that can also be used for higher-dimensional arrays. In StandardForm , explicit GridBox
objects are output literally. You can use DisplayForm to see the display form of such objects. See page 445. See
also: TableForm, MatrixForm, RowBox, OverscriptBox, UnderscriptBox, AdjustmentBox. New in Version 3.
GridDefaultElement
GridDefaultElement is an option for GridBox which specifies what to insert when a new
element is created interactively in a GridBox.
The default setting for GridDefaultElement is "\[Placeholder]" or "". When creating palettes,
GridDefaultElement is typically set to ButtonBox[""] . The setting for GridDefaultElement is used to
determine the contents of new columns or rows created with , or J (CONTROL-RETURN). See page 449.
New in Version 3.
GridLines
GridLines is an option for two-dimensional graphics functions that specifies grid lines.
The following settings can be given for GridLines:
None
Automatic
{xgrid, ygrid}
With the Automatic setting, grid lines are usually placed at points whose coordinates have the minimum number
of digits in their decimal representation. For each direction, the following grid line options can be given:
None
Automatic
{x , x , . . . }
{{x , style }, . . . }
func
Grid line styles can involve graphics directives such as RGBColor and Thickness. Grid lines are by default
colored light blue. The grid line function func[xmin, xmax] may return any other grid line option.
AbsoluteOptions gives the explicit form of GridLines specifications when Automatic settings are used. See
pages 511 and 515. See also: Ticks, FrameTicks, FaceGrids, ColumnLines, RowLines. New in Version 2.
GroebnerBasis Head
1168
GroebnerBasis
GroebnerBasis[{poly , poly , ... }, {x , x , ... }] gives a list of polynomials that form a
Grobner
basis in
which the yi have been eliminated.
The set of polynomials in a Grobner
basis have the same collection of roots as the original polynomials. For
polynomials in one variable, GroebnerBasis reduces to PolynomialGCD. For linear functions in any number of
variables, GroebnerBasis is equivalent to Gaussian elimination. The Grobner
MonomialOrder
CoefficientDomain
Modulus
Lexicographic
Automatic
0
GroupPageBreakWithin
GroupPageBreakWithin is an option for Cell which specifies whether a page break should be
allowed within the group of cells if the notebook that contains the group is printed.
See page 609.
New in Version 3.
HarmonicNumber
HarmonicNumber[n] gives the nth harmonic number Hn .
HarmonicNumber[n, r] gives the harmonic number Hnr of order r.
Mathematical function (see Section A.3.10). The harmonic numbers are given by Hnr ni ir with Hn Hn .
See page 757. See also: EulerGamma, PolyGamma, Zeta, Log. New in Version 4.
Head
Head[expr] gives the head of expr.
Examples: Head[f[x]] # f ; Head[a + b] # Plus ; Head[4] # Integer ; Head[x] # Symbol .
page 231. New in Version 1.
See
Heads HoldAllComplete
1169
Heads
Heads is an option for functions which use level specifications that specifies whether heads of
expressions should be included.
Heads -> True treats heads just like other elements of expressions for the purpose of levels. Heads -> False
never includes heads as part of any level of an expression. Most functions which use level specifications have the
default setting Heads -> False. One exception is Position, for which the default is Heads -> True. See
page 238. See also: Level. New in Version 2.
HermiteH
HermiteH[n, x] gives the Hermite polynomial Hn x.
Mathematical function (see Section A.3.10). Explicit polynomials are given for non-negative integers n. The
Hermite polynomials satisfy the differential equation y$$ xy$ ny . They are orthogonal polynomials with
weight function ex in the interval . HermiteH[n, x] is an entire function of x with no branch cut
discontinuities. See page 766. See also: LaguerreL. New in Version 1.
HiddenSurface
HiddenSurface is an option for SurfaceGraphics which specifies whether hidden surfaces are
to be eliminated.
HiddenSurface -> True eliminates hidden surfaces.
New in Version 1.
Hold
Hold[expr] maintains expr in an unevaluated form.
Hold has attribute HoldAll, and performs no operation on its arguments. Example: Hold[1+1] # Hold
1 1 .
Hold is removed by ReleaseHold. Hold[e , e , . . . ] maintains a sequence of unevaluated expressions to which
a function can be applied using Apply. Even though expr itself is not evaluated, Hold[expr] may still evaluate if
expr is of the form f [args], and upvalues for f have been defined. See page 338. See also: HoldPattern,
HoldForm, HoldComplete , Unevaluated, HoldAll, Symbol. New in Version 1.
HoldAll
HoldAll is an attribute which specifies that all arguments to a function are to be maintained in
an unevaluated form.
You can use Evaluate to evaluate the arguments of a HoldAll function in a controlled way. Even when a
function has attribute HoldAll, Sequence objects that appear in its arguments are still by default flattened,
Unevaluated wrappers are stripped, and upvalues associated with the arguments are used. See pages 329
and 336. See also: Unevaluated, Hold, NHoldAll, HoldAllComplete, SequenceHold, Extract. New in Version 1.
HoldAllComplete
HoldAllComplete is an attribute which specifies that all arguments to a function are not to be
modified or looked at in any way in the process of evaluation.
By setting the attribute HoldAllComplete you can effectively shield the arguments of a function from all aspects of
the standard Mathematica evaluation process. HoldAllComplete not only prevents arguments from being evaluated,
but also prevents Sequence objects from being flattened, Unevaluated wrappers from being stripped, and upvalues
associated with arguments from being used. Evaluate cannot be used to override HoldAllComplete . See
pages 329 and 340. See also: HoldComplete , HoldAll, SequenceHold, Extract. New in Version 3.
HoldComplete HoldRest
1170
HoldComplete
HoldComplete[expr] shields expr completely from the standard Mathematica evaluation process,
preventing even upvalues associated with expr from being used.
HoldComplete has attribute HoldAllComplete , and performs no operations on its arguments. HoldComplete is
removed by ReleaseHold. HoldComplete can be inserted as a wrapper by such functions as ToExpression and
ReplacePart. HoldComplete is generated by default by MakeExpression . See pages 339 and 1048. See also:
Hold, HoldPattern, HoldForm, Unevaluated, HoldAllComplete , Symbol. New in Version 3.
HoldFirst
HoldFirst is an attribute which specifies that the first argument to a function is to be
maintained in an unevaluated form.
See pages 329 and 336.
New in Version 1.
HoldForm
HoldForm[expr] prints as the expression expr, with expr maintained in an unevaluated form.
HoldForm allows you to see the output form of an expression without evaluating the expression. HoldForm has
attribute HoldAll. HoldForm is removed by ReleaseHold. See pages 338 and 434. See also: ToString,
WriteString. New in Version 1.
HoldPattern
HoldPattern[expr] is equivalent to expr for pattern matching, but maintains expr in an
unevaluated form.
HoldPattern has attribute HoldAll. The left-hand sides of rules are usually evaluated, as are parts of the
left-hand sides of assignments. You can use HoldPattern to stop any part from being evaluated. Example:
expr /. HoldPattern[Integrate[y_, x_]] -> rhs transforms any subexpression of the form Integrate[y_, x_] in
expr. Without the HoldPattern, the Integrate[y_, x_] in the rule would immediately be evaluated to give x_ y_,
and the replacement would not work. Example: f[HoldPattern[Integrate[y_, x_]]] := value can be used to
make an assignment for expressions of the form f[Integrate[y_, x_]]. Without HoldPattern, the Integrate
function would be evaluated at the time of assignment. See page 340. See also: Hold, Verbatim. New in
Version 3.
HoldRest
HoldRest is an attribute which specifies that all but the first argument to a function are to be
maintained in an unevaluated form.
See pages 329 and 336.
New in Version 1.
HTMLSave Hypergeometric1F1
1171
HTMLSave
HTMLSave["file.html"] saves an HTML version of the currently selected notebook in the front
end.
HTMLSave["file.html", "source.nb"] saves an HTML version of the notebook from the file
source.nb.
HTMLSave["file.html", notebook] saves an HTML version of the notebook corresponding to the
specified notebook object.
HTMLSave has options for specifying such features as how to include formulas, whether to make links for closed
cell groups, and what correspondence to set up between notebook styles and HTML tags. HTMLSave normally
saves graphics in separate image files. , HTMLSave generates CSS style sheets to mimic notebook styles.
HTMLSave can often be accessed from an item in the Save As Special menu in the notebook front end. , The
output from HTMLSave is compliant with XHTML 1.0. See page 211. See also: Export, MathMLForm, TeXSave,
Display. New in Version 3; modified in Version 5.0.
Hue
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.
The parameters h, s and b must all be between 0 and 1. Values of s and b outside this range are clipped. Values of
h outside this range are treated cyclically. As h varies from 0 to 1, the color corresponding to Hue[h] runs
through red, yellow, green, cyan, blue, magenta, and back to red again. Hue[h] is equivalent to Hue[h, 1, 1].
On monochrome displays, a gray level based on the brightness value is used. See page 499. See also:
RGBColor, GrayLevel, CMYKColor. Related package: Graphics`Colors` . New in Version 2.
Hypergeometric0F1
Hypergeometric0F1[a, z] is the confluent hypergeometric function F g ag z.
k
Mathematical function (see Section A.3.10). The F function has the series expansion F g ag z
k ak z kd .
See page 778. See also: Pochhammer, Hypergeometric1F1 , HypergeometricPFQ ,
Hypergeometric0F1Regularized . New in Version 1.
Hypergeometric0F1Regularized
Hypergeometric0F1Regularized[a, z] is the regularized confluent hypergeometric function
F ag za.
Mathematical function (see Section A.3.10). Hypergeometric0F1Regularized[a, z] is finite for all finite values of
a and z. See notes for Hypergeometric0F1 . See page 778. New in Version 3.
Hypergeometric1F1
Hypergeometric1F1[a, b, z] is the Kummer confluent hypergeometric function F ag bg z.
Mathematical function (see Section A.3.10). The F function has the series expansion
k
See page 778. See also: HypergeometricU , Hypergeometric2F1 ,
F ag bg z k ak bk z kd .
HypergeometricPFQ , Hypergeometric1F1Regularized . New in Version 1.
1172
Hypergeometric1F1Regularized HypergeometricU
Hypergeometric1F1Regularized
Hypergeometric1F1Regularized[a, b, z] is the regularized confluent hypergeometric
function F ag bg zb.
Mathematical function (see Section A.3.10). Hypergeometric1F1Regularized[a, b, z] is finite for all finite values
of a, b and z. See notes for Hypergeometric1F1 . See page 779. New in Version 3.
Hypergeometric2F1
Hypergeometric2F1[a, b, c, z] is the hypergeometric function F a bg cg z.
Mathematical function (see Section A.3.10). The F function has the series expansion
k
Hypergeometric2F1[a, b, c, z] has a branch cut discontinuity in the
F a bg cg z k ak bk ck z kd .
complex z plane running from to . FullSimplify and FunctionExpand include transformation rules for
Hypergeometric2F1 . See page 780. See also: AppellF1, Hypergeometric1F1 , HypergeometricPFQ ,
Hypergeometric2F1Regularized . New in Version 1.
Hypergeometric2F1Regularized
Hypergeometric2F1Regularized[a, b, c, z] is the regularized hypergeometric function
F a bg cg zc.
Mathematical function (see Section A.3.10). Hypergeometric2F1Regularized[a, b, c, z] is finite for all finite
values of a, b, c and z so long as /z/ ) . See notes for Hypergeometric2F1 . See page 780. New in Version 3.
HypergeometricPFQ
HypergeometricPFQ[{a , ... , ap }, {b , ... , bq }, z] is the generalized hypergeometric
function p Fq ag bg z.
k
Mathematical function (see Section A.3.10). p Fq ag bg z has series expansion
k a k ap k b k bq k z kd .
Hypergeometric0F1 , Hypergeometric1F1 , and Hypergeometric2F1 are special cases of HypergeometricPFQ . In
many special cases, HypergeometricPFQ is automatically converted to other functions. For p q ,
HypergeometricPFQ[alist, blist, z] has a branch cut discontinuity in the complex z plane running from to .
FullSimplify and FunctionExpand include transformation rules for HypergeometricPFQ . See page 780. See
also: MeijerG, Hypergeometric0F1 , Hypergeometric1F1 , Hypergeometric2F1 , AppellF1,
HypergeometricPFQRegularized . New in Version 3.
HypergeometricPFQRegularized
HypergeometricPFQRegularized[{a , ... , ap }, {b , ... , bq }, z] is the regularized
generalized hypergeometric function p Fq ag bg zb bq .
Mathematical function (see Section A.3.10). HypergeometricPFQRegularized is finite for all finite values of its
arguments so long as p * q. See notes for HypergeometricPFQ . See page 780. New in Version 3.
HypergeometricU
HypergeometricU[a, b, z] is the confluent hypergeometric function Ua b z.
Mathematical function (see Section A.3.10). The function Ua b z has the integral representation
Ua b z a ezt ta tba dt. HypergeometricU[a, b, z] has a branch cut discontinuity in the
complex z plane running from to . See page 778. See also: Hypergeometric1F1 , Hypergeometric0F1 .
New in Version 1.
Hyphenation Im
1173
Hyphenation
Hyphenation is an option for Cell which specifies whether to allow hyphenation for words of
text.
The choice of hyphenation points is based when possible on dictionaries and algorithms for the language in which
the text is specified to be written. See page 609. See also: TextJustification , LanguageCategory . New in
Version 4.
I
I represents the imaginary unit
.
Numbers containing I are converted to the type Complex. I can be entered in StandardForm and InputForm as ,
, ii , or \[ImaginaryI]. , , jj , and \[ImaginaryJ] can also be used. In StandardForm and TraditionalForm,
I is output as . See page 765. See also: Re, Im, ComplexExpand, GaussianIntegers . New in Version 1; modified
in Version 3.
Identity
Identity[expr] gives expr (the identity operation).
See page 253.
New in Version 1.
IdentityMatrix
IdentityMatrix[n] gives the n n identity matrix.
See page 896. See also: DiagonalMatrix, KroneckerDelta, Table.
LinearAlgebra`MatrixManipulation` . New in Version 1.
Related package:
If
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.
If evaluates only the argument determined by the value of the condition. If[condition, t, f] is left unevaluated
if condition evaluates to neither True nor False. If[condition, t] gives Null if condition evaluates to False. See
page 345. See also: Switch, Which, Condition, DiracDelta. New in Version 1.
IgnoreCase
IgnoreCase is an option for string manipulation and searching functions which specifies
whether lower- and upper-case letters should be treated as equivalent.
With the default setting IgnoreCase -> False, lower- and upper-case letters are treated as totally different. With
the setting IgnoreCase -> True, lower- and upper-case letters are treated as equivalent. IgnoreCase is an option
for StringPosition , StringReplace, StringMatchQ, Find and FindList. IgnoreCase in no way affects the
parsing of Mathematica expressions. See page 410. See also: ToUpperCase, ToLowerCase, SpellingCorrection .
New in Version 2.
Im
Im[z] gives the imaginary part of the complex number z.
Im[expr] is left unevaluated if expr is not a numeric quantity.
ComplexExpand. New in Version 1.
ImageMargins Implies
1174
ImageMargins
ImageMargins is an option for Cell which specifies the absolute margins in printers points to
leave around graphics in a cell.
Possible settings are:
dist
{{left, right}, {bottom, top}}
ImageMargins represent space to be left inside whatever CellMargins are specified for a particular cell.
page 616. See also: ImageSize, CellMargins. New in Version 3.
See
ImageResolution
ImageResolution is an option for Export and Display which specifies at what resolution
bitmap images should be rendered.
ImageResolution->r specifies that a bitmap should be rendered at a resolution of r dpi. ImageResolution is
relevant only for bitmap graphics formats such as "TIFF", and not for resolution-independent formats such as
"EPS". The default setting ImageResolution->Automatic typically uses a resolution of 72 dpi for bitmap graphics
formats. See page 569. See also: ImageSize. New in Version 3.
ImageRotated
ImageRotated is an option for Export and Display which specifies whether images should be
rotated into landscape mode.
The default setting for ImageRotated is False.
Version 3.
New in
ImageSize
ImageSize is an option for Export, Display and other graphics functions, as well as for Cell,
which specifies the absolute size of an image to render.
ImageSize->x specifies that the image should have a width of x printers points. ImageSize->72 xi specifies that
the image should have a width of xi inches. ImageSize->{x, y} specifies that the image should be rendered
within a region x printers points wide by y printers points high. The image will fill the region only if its aspect
ratio is exactly y/x. In Display and other graphics functions, the default setting for ImageSize is Automatic.
This specifies that when output is sent to the front end, the front end should determine the size of the image.
When output is sent elsewhere, the effective default is 288, corresponding to 4 inches. In the front end, the
typical default setting for ImageSize is also 288, corresponding to 4 inches. See page 616. See also:
ImageResolution , ImageMargins, AspectRatioFixed . New in Version 3.
Implies
Implies[p, q] represents the logical implication p n q.
Implies[p, q] is equivalent to !p || q. Implies[p, q] can be input in StandardForm and InputForm as p q.
The character can be entered as , => , or \[Implies]. See page 834. See also: LogicalExpand, If. New in
Version 1; modified in Version 3.
Import Import
1175
Import
Import["file.ext"] imports data from a file, assuming that it is in the format indicated by the
file extension ext, and converts it to a Mathematica expression.
Import["file", "format"] imports data in the specified format from a file.
Import attempts to give a Mathematica expression whose meaning is as close as possible to the data in the external
file. Import can handle numerical and textual data, graphics, sounds, material from notebooks, and general
expressions in various formats. - The following basic formats are supported for textual and tabular data:
"CSV"
"Lines"
"List"
"Table"
"Text"
"TSV"
"UnicodeText"
"Words"
"Text" and "UnicodeText" return single Mathematica strings. "Lines" and "Words" return lists of Mathematica
strings. "List" returns a list of Mathematica numbers or strings. - "Table", "CSV" and "TSV" return a list of lists
of Mathematica numbers or strings. - In "List", "Table", "CSV" and "TSV" formats, numbers can be read in C or
Fortran-like E notation. Numbers without explicit decimal points are returned as exact integers. In "Table"
format, columns can be separated by spaces or tabs. In "Words" format, words can be separated by any form of
white space. - In "CSV" format, columns are taken to be separated by commas, unless other settings are specified
using ConversionOptions . Import["file.txt"] uses "Text" format. Import["file.dat"] uses "Table" format.
Import["file.csv"] uses "CSV" format. - The following additional formats are also supported for numerical data:
"FITS"
"HarwellBoeing"
"HDF"
"MAT"
"MTX"
"SDTS"
"MPS"
Two-dimensional graphics formats are imported as Graphics objects; sound formats are imported as Sound
objects. Animated graphics are imported as lists of Graphics objects. The following formats yield expressions of
the form Graphics[data, opts]:
"EPS"
"EPSI"
"EPSTIFF"
"MPS"
-
Encapsulated PostScript
Encapsulated PostScript
Encapsulated PostScript
Mathematica abbreviated
(.eps)
with image preview (.epsi)
with TIFF preview
PostScript (.mps)
"BMP"
"DICOM"
"GIF"
"JPEG"
"MGF"
"PBM"
"PGM"
(continued)
1176
Import
(continued)
"PNG"
"PNM"
"PPM"
"TIFF"
"XBitmap"
Imported raster data normally consists of integers; ColorFunction is often used to specify a color map.
following formats return objects of the form Graphics3D[data, opts]:
"DXF"
"STL"
The
"AIFF"
"AU"
"SND"
"WAV"
The following gives a notebook expression Notebook[. . . ] from a Mathematica notebook file:
"NB" Mathematica notebook format (.nb)
,
"ExpressionML"
"MathML"
"NotebookML"
"SymbolicXML"
"XML"
arbitrary expression
mathematical expression or boxes (.mml)
notebook expression (.nbml)
SymbolicXML expression
determined by content (.xml)
With format "MathML", MathML presentation elements are if possible imported as mathematical expressions
using TraditionalForm interpretation rules. Otherwise, they are imported as box expressions. - With format
"SymbolicXML", XML data of any document type is imported as a SymbolicXML expression. - With format "XML",
Import will recognize MathML, NotebookML, and ExpressionML and interpret them accordingly. Other XML will
be imported as SymbolicXML. , The following formats can be used for general expressions:
-
"Dump"
"Expression"
"ExpressionML"
ByteOrdering
CharacterEncoding
ConversionOptions
Path
$ByteOrdering
Automatic
{}
$Path
Possible formats accepted by Import are given in the list $ImportFormats. Import["!prog", "format"] imports
data from a pipe. See pages 207, 570 and 642. See also: Export, ImportString, $ImportFormats, ReadList.
New in Version 4; modified in Version 5.0.
-
ImportString
ImportString["data", "format"] imports data in the specified format from a string.
See notes for Import.
In Infix
1177
In
In[n] is a global object that is assigned to have a delayed value of the nth input line.
Typing In[n] causes the nth input line to be re-evaluated. In[ ] gives the last input line. In[-k] gives the
input k lines back. See pages 48 and 702. See also: InString, Out, $Line, $HistoryLength. New in Version 1.
Increment
x++ increases the value of x by 1, returning the old value of x.
Increment has attribute HoldFirst.
New in Version 1.
Indeterminate
Indeterminate is a symbol that represents a numerical quantity whose magnitude cannot be
determined.
Computations like 0/0 generate Indeterminate. A message is produced whenever an operation first yields
Indeterminate as a result. See page 742. See also: DirectedInfinity , Check. New in Version 1.
Infinity
Infinity or is a symbol that represents a positive infinite quantity.
can be entered as \[Infinity] or , inf ,. In StandardForm, Infinity is printed as . Infinity is converted
to DirectedInfinity[1] . Certain arithmetic operations work with Infinity. Example: 1/Infinity # 0 .
NumberQ[Infinity] yields False. See pages 743 and 765. See also: ComplexInfinity , Indeterminate . New
in Version 1; modified in Version 3.
Infix
Infix[f [e , e , ... ]] prints with f [e , e , ... ] given in default infix form:
e M f M e M f M e
... .
Infix[expr, h] prints with arguments separated by h: e h e h e
... .
Infix[expr, h, precedence, grouping] can be used to specify how the output form should be parenthesized.
Precedence levels are specified by integers. In OutputForm, some precedence levels are:
x . y . z 210
x y z
150
x + y + z 140
x == y
130
x = y
60
Possible grouping (associativity) specifications are:
NonAssociative
None
Left
Right
See page 474.
New in Version 1.
Information InputAliases
1178
Information
Information[symbol] prints information about a symbol.
Information[symbol] prints the same information as the input escape ??symbol would give. Information has
attribute HoldAll.
See pages 58 and 1038. See also: Definition, Names, ValueQ, DownValues, UpValues. New
in Version 1.
InitializationCell
InitializationCell is an option for Cell which specifies whether the cell should
automatically be sent for evaluation by the Mathematica kernel when the notebook that contains
it is opened.
See page 608.
New in Version 3.
Inner
Inner[f, list , list , g] is a generalization of Dot in which f plays the role of multiplication
and g of addition.
Example: Inner[f,{a,b},{x,y},g] # g
f
a, x, f
b, y .
Inner[f,{{a,b},{c,d}},{x,y},g] # g
f
a, x, f
b, y, g
f
c, x, f
d, y . Like Dot, Inner
effectively contracts the last index of the first tensor with the first index of the second tensor. Applying Inner to a
rank r tensor and a rank s tensor gives a rank r s tensor. Inner[f, list , list ] uses Plus for g.
Inner[f, list , list , g, n] contracts index n of the first tensor with the first index of the second tensor. The
heads of list and list must be the same, but need not necessarily be List. See page 917. See also: Outer,
Thread, MapThread, ListCorrelate. New in Version 1.
Input
Input[ ] interactively reads in one Mathematica expression.
Input["prompt"] requests input, using the specified string as a prompt.
Input returns the expression it read. The operation of Input may vary from one computer system to another.
When a Mathematica front end is used, Input may work through a dialog box. When no front end is used, Input
reads from standard input. If the standard input is a file, then Input returns EndOfFile if you try to read past
the end of the file. On most systems, Input[ ] uses ? as a prompt. When Input is evaluated, Mathematica
stops until the input has been read. See page 478. See also: InputString, Read, Get, Dialog, ButtonBox. New
in Version 1.
InputAliases
InputAliases is an option for cells and notebooks which specifies additional HnameH aliases to
be allowed on input.
The setting InputAliases->{"name "->expr , . . . } specifies that the Hnamei H should be replaced on input by the
corresponding expri . The expri should be strings or box expressions. See page 613. See also:
InputAutoReplacements , $PreRead, Set. New in Version 4.
InputAutoReplacements InputString
1179
InputAutoReplacements
InputAutoReplacements is an option for cells and notebooks which specifies strings of
characters that should be replaced immediately on input.
The default setting of InputAutoReplacements for Input styles typically includes such rules as "->" -> "". In
expression input, automatic replacements can be performed only on strings of characters that correspond to
complete input tokens. In textual input, automatic replacements can be performed on strings of alphanumeric
characters delimited by spaces or other punctuation characters. When material is copied from a notebook to the
clipboard, replacements specified by ExportAutoReplacements are by default performed. Typically these
replacements include ones that reverse the action of the replacements in InputAutoReplacements . When material
is pasted from the clipboard into a notebook, replacements specified by ImportAutoReplacements are by default
performed. Typically these replacements are a subset of those given in InputAutoReplacements . See page 613.
See also: InputAliases, $PreRead, Set. New in Version 4.
InputForm
InputForm[expr] prints as a version of expr suitable for input to Mathematica.
Example: InputForm[x^2 + 1/a] # a^ 1 x^2 . InputForm always produces one-dimensional output,
suitable to be typed as lines of Mathematica input. InputForm acts as a wrapper, which affects printing, but not
evaluation. Put (>>) produces InputForm by default. Short[InputForm[expr]] can be used, but may generate
skeleton objects which cannot be given as Mathematica input. The option NumberMarks can be used to specify
whether ` marks should be used to indicate type, precision or accuracy of approximate numbers. See page 424.
See also: OutputForm, FullForm, StandardForm. New in Version 1; modified in Version 3.
InputNotebook
InputNotebook[ ] gives the current notebook into which keyboard input in the front end will
be directed.
InputNotebook returns a NotebookObject . If there is no current input notebook, InputNotebook[ ] will return
$Failed. The current input notebook is the notebook to which textual commands in the front end are normally
directed. A palette window can be a currently selected notebook but cannot normally be an input notebook. See
page 579. See also: Notebooks, SelectedNotebook , EvaluationNotebook , ButtonNotebook . New in Version 3.
InputStream
InputStream["name", n] is an object that represents an input stream for functions such as
Read and Find.
OpenRead returns an InputStream object. The serial number n is unique across all streams, regardless of their
name. StringToStream returns an object of the form InputStream[String, n]. See page 631. See also:
$Input, Streams, OutputStream. New in Version 2.
InputString
InputString[ ] interactively reads in a character string.
InputString["prompt"] requests input, using the specified string as a prompt.
See notes for Input.
New in Version 1.
Insert Integer
1180
Insert
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.
Insert[expr, elem, {{i , j , ... }, {i , j , ... }, ... }] inserts elem at several positions.
Examples: Insert[{a, b, c}, x, 2] # a, x, b, c .
Insert[{a, b, c}, x, {{1}, {-1}}] # x, a, b, c, x .
Insert[{{a, b}, {c, d}}, x, {2, 1}] # a, b, x, c, d . list can have any head, not necessarily
List. , Insert works on SparseArray objects by effectively inserting into the corresponding ordinary lists. See
pages 125 and 288. See also: Prepend, Append, StringInsert, Take, Drop, Delete, ReplacePart, FlattenAt,
Position, Sequence. New in Version 1.
Install
Install["name"] starts a MathLink-compatible external program and installs Mathematica
definitions to call functions in it.
The Mathematica definitions set up by Install are typically specified in the MathLink template file used to create
the source code for the external program. Install["prog"] will launch the specified program, then connect to it
via MathLink. If prog is a directory, Install["prog"] will try to execute prog/$SystemID/prog.
Install["name`"] searches all directories on $Path for a file or directory called name.exe. Install[link] will
take an existing LinkObject and set up what is needed to call functions in the program corresponding to that
LinkObject. Install returns a LinkObject representing the MathLink connection it is using.
LinkPatterns[link] gives a list of the patterns defined when the specified link was set up. You can remove
these definitions, and terminate the execution of the external program by calling Uninstall[link] .
Install[LinkConnect["port"]] will install an external program that has created a link on the specified port. You
can use this to call external programs that have been started in a debugger or on a remote computer system. If
you call Install["command"] multiple times with the same command, the later calls will overwrite definitions set
up by earlier ones, unless the definitions depend on the values of global variables which have changed. Install
sets up definitions which send CallPacket objects to the external program whenever functions in it are called, and
waits for results to be returned in ReturnPacket objects. The external program can send EvaluatePacket objects
back to Mathematica to request evaluations while the program is running. See page 659. See also: Get, Run,
RunThrough, LinkLaunch, Uninstall, $CurrentLink. New in Version 2; modified in Version 3.
InString
InString[n] is a global object that is assigned to be the text of the nth input line.
InString[n] gives the string that Mathematica read for the nth input line. The string includes all intermediate
newlines in the input, but not the newline at the end. The value of InString[n] is assigned after the input is
verified to be syntactically correct, and after any function given as the value of $PreRead has been applied.
InString[ ] gives the text of the last input line. InString[-k] gives the text of the input k lines back. See
pages 48 and 702. See also: In, $SyntaxHandler. New in Version 2.
Integer
Integer is the head used for integers.
_Integer can be used to stand for an integer in a pattern. Integers can be of any length. You can enter an
integer in base b using b^^digits. The base must be less than 36. The letters are used in sequence to stand for digits
10 through 35. See page 722. See also: IntegerDigits, BaseForm, IntegerQ, Integers. New in Version 1.
IntegerDigits Integers
1181
IntegerDigits
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.
Examples: IntegerDigits[5810] # 5, 8, 1, 0 ; IntegerDigits[5810, 16] # 1, 6, 11, 2 .
IntegerDigits[n] discards the sign of n. If len is less than the number of digits in n then the len least
significant digits are returned. , IntegerDigits[0] gives {0}. FromDigits can be used as the inverse of
IntegerDigits. See page 725. Implementation notes: see page 1067. See also: DigitCount, RealDigits,
BaseForm, NumberForm, FromDigits, IntegerExponent , IntegerPart, ContinuedFraction . New in Version 2;
modified in Version 3.
IntegerExponent
IntegerExponent[n, b] gives the highest power of b that divides n.
IntegerExponent[n] is equivalent to IntegerExponent[n, 10]. IntegerExponent[n, b] gives the number of
trailing zeros in the digits of n in base b. See page 749. See also: IntegerDigits, FactorInteger ,
MantissaExponent, DigitCount, Exponent. New in Version 4.
IntegerPart
IntegerPart[x] gives the integer part of x.
Mathematical function (see Section A.3.10). IntegerPart[x] in effect takes all digits to the left of the decimal
point and drops the others. Examples: IntegerPart[2.4] # 2 ; IntegerPart[2.6] # 2 ;
IntegerPart[-2.4] # 2 ; IntegerPart[-2.6] # 2 . IntegerPart[x] + FractionalPart[x] is always
exactly x. IntegerPart[x] returns an integer when x is any numeric quantity, whether or not it is an explicit
number. Example: IntegerPart[Pi^2] # 9 . For exact numeric quantities, IntegerPart internally uses
numerical approximations to establish its result. This process can be affected by the setting of the global variable
$MaxExtraPrecision . See page 745. See also: FractionalPart, Round, Floor, Ceiling, Chop. New in
Version 3.
IntegerQ
IntegerQ[expr] gives True if expr is an integer, and False otherwise.
IntegerQ[expr] returns False unless expr is manifestly an integer (i.e., has head Integer).
Simplify[expr Integers] can be used to try to determine whether an expression is mathematically equal to an
integer. See pages 267 and 723. See also: EvenQ, OddQ, NumberQ, TrueQ, Element. New in Version 1.
Integers
Integers represents the domain of integers, as in x Integers.
x Integers evaluates immediately only if x is a numeric quantity. Simplify[expr Integers] can be used to
try to determine whether an expression is an integer. IntegerQ[expr] tests only whether expr is manifestly an
integer (i.e., has head Integer). Integers is output in TraditionalForm as . See pages 73, 817 and 839. See
also: Element, Simplify, IntegerQ, Reals, Primes, Algebraics. New in Version 4.
Integrate InterpolatingFunction
1182
Integrate
Integrate[f, x] gives the indefinite integral f dx.
xmax
Integrate[f, {x, xmin, xmax}] gives the definite integral xmin f dx.
Integrate[f, {x, xmin, xmax}, {y, ymin, ymax}] gives the multiple integral
xmax
ymax
xmin dx ymin dy f .
Integrate[f, x] can be entered as f 7 x. can be entered as , int , or \[Integral]. 7 is not an ordinary d; it
is entered as , dd , or \[DifferentialD] . Integrate[f, {x, xmin, xmax}] can be entered with xmin as a
subscript and xmax as a superscript to . Multiple integrals use a variant of the standard iterator notation. The
first variable given corresponds to the outermost integral, and is done last. Integrate can evaluate integrals of
rational functions. It can also evaluate integrals that involve exponential, logarithmic, trigonometric and inverse
trigonometric functions, so long as the result comes out in terms of the same set of functions. Integrate can
give results in terms of many special functions. Integrate carries out some simplifications on integrals it cannot
explicitly do. You can get a numerical result by applying N to a definite integral. You can assign values to
patterns involving Integrate to give results for new classes of integrals. The integration variable can be any
expression. However, Integrate uses only its literal form. The object dxn , for example, is not converted to
nxn dx. For indefinite integrals, Integrate tries to find results that are correct for almost all values of
parameters. For definite integrals, the following options can be given:
Assumptions
GenerateConditions
PrincipalValue
$Assumptions
Automatic
False
Integrate can evaluate essentially all indefinite integrals and most definite integrals listed in standard books of
tables. In StandardForm , Integrate[f, x] is output as f 7 x. See page 859. Implementation notes: see
page 1070. See also: NIntegrate, DSolve, Sum, LaplaceTransform , FourierTransform . New in Version 1;
modified in Version 5.0.
InterpolatingFunction
InterpolatingFunction[domain, table] represents an approximate function whose values are
found by interpolation.
InterpolatingFunction works like Function. InterpolatingFunction[ . . . ][x] finds the value of an
approximate function with a particular argument x. In standard output format, only the domain element of an
InterpolatingFunction object is printed explicitly. The remaining elements are indicated by <>. domain specifies
the domain of the data from which the InterpolatingFunction was constructed. If you supply arguments
outside of the domain, a warning is generated, and then an extrapolated value is returned.
InterpolatingFunction objects that take any number of real arguments may be constructed. You can take
derivatives of InterpolatingFunction objects using D and Derivative. NDSolve returns its results in terms of
InterpolatingFunction objects. See page 930. Implementation notes: see page 1069. See also: Interpolation,
CompiledFunction , FunctionInterpolation . Related package: NumericalMath`SplineFit` . New in Version 2;
modified in Version 3.
InterpolatingPolynomial InterpretationBox
1183
InterpolatingPolynomial
InterpolatingPolynomial[data, var] gives a polynomial in the variable var which provides
an exact fit to a list of data.
The data can have the forms {{x , f }, {x , f }, ... } or {f , f , ... }, where in the second
case, the xi are taken to have values 1, 2, ... .
The fi can be replaced by {fi , dfi , ddfi , ... }, specifying derivatives at the points xi .
With a list of data of length n, InterpolatingPolynomial gives a polynomial of degree n .
2
Example:
Interpolation
Interpolation[data] constructs an InterpolatingFunction object which represents an
approximate function that interpolates the data.
The data can have the forms {{x , f }, {x , f }, ... } or {f , f , ... }, where in the second
case, the xi are taken to have values 1, 2, ... .
Data can be given in the form {{x , {f , df , ddf , . . . }}, . . . } to specify derivatives as well as values of the
function at the points xi . You can specify different numbers of derivatives at different points. Function values and
derivatives may be real or complex numbers, or arbitrary symbolic expressions. The xi must be real numbers.
Multidimensional data can be given in the form {{x , y , . . . , f }, . . . }. Derivatives in this case can be given
by replacing f and so on by {f , {dxf , dyf , . . . }}. Interpolation works by fitting polynomial curves between
successive data points. The degree of the polynomial curves is specified by the option InterpolationOrder .
The default setting is InterpolationOrder -> 3. You can do linear interpolation by using the setting
InterpolationOrder -> 1. Interpolation[data] generates an InterpolatingFunction object which returns
values with the same precision as those in data. See page 931. See also: ListInterpolation ,
FunctionInterpolation , InterpolatingPolynomial , Fit, Quantile. Related packages:
NumericalMath`SplineFit` , NumericalMath`PolynomialFit` , NumericalMath`Approximations` ,
DiscreteMath`ComputationalGeometry` . New in Version 2; modified in Version 3.
InterpretationBox
InterpretationBox[boxes, expr] displays as boxes but is interpreted on input as expr.
InterpretationBox provides a way to store hidden information in Mathematica output. InterpretationBox is
generated sometimes in StandardForm output, and often in TraditionalForm output. The following options can
be given:
AutoDelete
DeletionWarning
Editable
Selectable
False
False
False
True
whether
whether
whether
whether
to
to
to
to
If you modify the displayed form of InterpretationBox[boxes, expr] only boxes will be modified, and there is
no guarantee that correct correspondence with expr will be maintained. InterpretationBox has attribute
HoldComplete. See page 447. See also: TagBox, FormBox, ToExpression, ButtonBox. New in Version 3.
Interrupt IntervalUnion
1184
Interrupt
Interrupt[ ] generates an interrupt.
You can call Interrupt anywhere within a computation. It has the same effect as an interactive interrupt at that
point. See page 371. See also: Abort, TimeConstrained , MemoryConstrained , Throw, $Inspector,
LinkInterrupt. New in Version 2.
Intersection
Intersection[list , list , ... ] gives a sorted list of the elements common to all the listi .
If the listi are considered as sets, Intersection gives their intersection. Intersection[list , list , . . . ] can be
input in StandardForm and InputForm as list list . . . . The character can be entered as , inter , or
\[Intersection] . The listi must have the same head, but it need not be List.
Intersection[list , . . . , SameTest->test] applies test to each pair of elements in the listi to determine whether
they should be considered the same. Intersection[a, b] can be entered in StandardForm and InputForm as
a b or a \[Intersection] b. See page 127. See also: Union, Complement. New in Version 1; modified in
Version 3.
Interval
Interval[{min, max}] represents the range of values between min and max.
Interval[{min , max }, {min , max }, ... ] represents the union of the ranges min to max ,
min to max , ....
You can perform arithmetic and other operations on Interval objects. Example:
Interval[{1, 6}] + Interval[{0, 2}] # Interval
1, 8 . Min[interval] and Max[interval] give the end
points of an interval. For approximate machine- or arbitrary-precision numbers x, Interval[x] yields an interval
reflecting the uncertainty in x. In operations on intervals that involve approximate numbers, Mathematica always
rounds lower limits down and upper limits up. Interval can be generated by functions such as Limit.
Relational operators such as Equal and Less yield explicit True or False results whenever they are given disjoint
intervals. See page 894. See also: Range. New in Version 3.
IntervalIntersection
IntervalIntersection[interval , interval , ... ] gives the interval representing all points
common to each of the intervali .
See page 741.
New in Version 3.
IntervalMemberQ
IntervalMemberQ[interval, x] gives True if the number x lies within the specified interval,
and False otherwise.
IntervalMemberQ[interval , interval ] gives True if interval is completely contained within
interval .
IntervalMemberQ has attribute Listable.
New in Version 3.
IntervalUnion
IntervalUnion[interval , interval , ... ] gives the interval representing the set of all points in
any of the intervali .
See page 741.
New in Version 3.
Inverse InverseErfc
1185
Inverse
Inverse[m] gives the inverse of a square matrix m.
Inverse works on both symbolic and numerical matrices. For matrices with approximate real or complex
numbers, the inverse is generated to the maximum possible precision given the input. A warning is given for
ill-conditioned matrices. Inverse[m, Modulus->n] evaluates the inverse modulo n.
Inverse[m, ZeroTest -> test] evaluates test[ m[[i, j]] ] to determine whether matrix elements are zero. The
default setting is ZeroTest -> (# == 0 &). A Method option can also be given. Possible settings are as for
LinearSolve. See page 903. Implementation notes: see page 1069. See also: PseudoInverse, LinearSolve,
RowReduce, NullSpace, LinearSolveFunction . Related package: LinearAlgebra`Tridiagonal` . New in
Version 1; modified in Version 3.
InverseBetaRegularized
InverseBetaRegularized[s, a, b] gives the inverse of the regularized incomplete beta
function.
Mathematical function (see Section A.3.10). With the regularized incomplete beta function defined by
Iz a b hz a bha b, InverseBetaRegularized[s, a, b] is the solution for z in s Iz a b.
InverseBetaRegularized[z , s, a, b] gives the inverse of BetaRegularized[z , z, a, b]. Note that the
arguments of InverseBetaRegularized are arranged differently than in InverseGammaRegularized . See
page 770. See also: InverseGammaRegularized , InverseErf. New in Version 3.
InverseEllipticNomeQ
InverseEllipticNomeQ[q] gives the parameter m corresponding to the nome q in an elliptic
function.
Mathematical function (see Section A.3.10). InverseEllipticNomeQ[q] yields the unique value of the parameter m
which makes EllipticNomeQ[m] equal to q. The nome q must always satisfy /q/ ) . See page 782. See also:
EllipticNomeQ. New in Version 3.
InverseErf
InverseErf[s] gives the inverse error function obtained as the solution for z in s erfz.
Mathematical function (see Section A.3.10). Explicit numerical values are given only for real values of s between
and . InverseErf[z , s] gives the inverse of the generalized error function Erf[z , z]. See page 775.
See also: Erf, InverseGammaRegularized , InverseBetaRegularized . New in Version 3.
InverseErfc
InverseErfc[s] gives the inverse complementary error function obtained as the solution for z
in s erfcz.
Mathematical function (see Section A.3.10). Explicit numerical values are given only for real values of s between 0
and 2. See page 775. See also: Erfc, InverseGammaRegularized , InverseBetaRegularized . New in Version 3.
1186
InverseFourier InverseFourierSinTransform
InverseFourier
InverseFourier[list] finds the discrete inverse Fourier transform of a list of complex
numbers.
The inverse Fourier transform ur of a list vs of length n is defined to be
n
zero frequency term must appear at position 1 in the input list. Other definitions are used in some scientific and
technical fields. Different choices of definitions can be specified using the option FourierParameters . With the
setting FourierParameters -> {a, b} the discrete Fourier transform computed by Fourier is
ns vs eibrsn . Some common choices for {a, b} are {0, 1} (default), {-1, 1} (data analysis),
na
{1, -1} (signal processing). The setting b effectively corresponds to reversing both input and output lists.
To ensure a unique discrete Fourier transform, /b/ must be relatively prime to n. The list of data need not have
a length equal to a power of two. The list given in InverseFourier[list] can be nested to represent an array of
data in any number of dimensions. The array of data must be rectangular. If the elements of list are exact
numbers, InverseFourier begins by applying N to them. See page 935. See also: Fourier,
InverseFourierTransform . New in Version 1; modified in Version 4.
InverseFourierCosTransform
InverseFourierCosTransform[expr, , t] gives the symbolic inverse Fourier cosine
transform of expr.
InverseFourierCosTransform[expr, { , , ... }, {t , t , ... }] gives the
multidimensional inverse Fourier cosine transform of expr.
!
The inverse Fourier cosine transform of a function F is by default defined as F cost d. Other
definitions are used in some scientific and technical fields. Different choices of definitions can be specified using
the option FourierParameters . With the setting FourierParameters->{a, b} the inverse Fourier transform
"
/b/
See notes for
computed by InverseFourierCosTransform is
a F cosbt d.
InverseFourierSinTransform
InverseFourierSinTransform[expr, , t] gives the symbolic inverse Fourier sine transform
of expr.
InverseFourierSinTransform[expr, { , , ... }, {t , t , ... }] gives the
multidimensional inverse Fourier sine transform of expr.
!
The inverse Fourier sine transform of a function F is by default defined as F sint d. Other
definitions are used in some scientific and technical fields. Different choices of definitions can be specified using
the option FourierParameters . With the setting FourierParameters->{a, b} the inverse Fourier transform
"
/b/
computed by InverseFourierSinTransform is
See notes for
a F sinbt d.
InverseFourierTransform InverseFunctions
1187
InverseFourierTransform
InverseFourierTransform[expr, , t] gives the symbolic inverse Fourier transform of expr.
InverseFourierTransform[expr, { , , ... }, {t , t , ... }] gives the multidimensional
inverse Fourier transform of expr.
The inverse Fourier transform of a function F is by default defined as
F eit d.
Other definitions
are used in some scientific and technical fields. Different choices of definitions can be specified using the option
FourierParameters . With the
" setting FourierParameters->{a, b} the inverse Fourier transform computed by
/b/
ibt d.
InverseFourierTransform is
Some common choices for {a, b} are {0, 1} (default;
a F e
modern physics), {1, -1} (pure mathematics; systems engineering), {-1, 1} (classical physics), {0, -2 Pi} (signal
processing). Assumptions and other options to Integrate can also be given in InverseFourierTransform .
InverseFourierTransform[expr, , t] yields an expression depending on the continuous variable t that
represents the symbolic inverse Fourier transform of expr with respect to the continuous variable .
InverseFourier[list] takes a finite list of numbers as input, and yields as output a list representing the discrete
inverse Fourier transform of the input. In TraditionalForm , InverseFourierTransform is output using .
See page 876. See also: InverseFourierSinTransform , InverseFourierCosTransform , InverseFourier ,
FourierTransform, InverseLaplaceTransform , Integrate. New in Version 4.
InverseFunction
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.
For a function with several arguments, InverseFunction[f, n, tot] represents the inverse
with respect to the nth argument when there are tot arguments in all.
In OutputForm and StandardForm , InverseFunction[f] is printed as f . As discussed in Section 3.2.7, many
mathematical functions do not have unique inverses. In such cases, InverseFunction[f] can represent only one of
the possible inverses for f. Example: InverseFunction[Sin] # ArcSin . InverseFunction is generated by
Solve when the option InverseFunctions is set to Automatic or True. See pages 253 and 825. See also:
Solve, InverseSeries, Composition, Derivative. New in Version 2.
InverseFunctions
InverseFunctions is an option for Solve and related functions which specifies whether
inverse functions should be used.
Settings for InverseFunctions are:
True
Automatic
False
Example: Solve[f[x] == a, x, InverseFunctions->True] # x f1
a . Inverse functions provide a
way to get some, but not in general all, solutions to equations that involve functions which are more complicated
than polynomials. Solve[Sin[x] == a, x, InverseFunctions->True] # x ArcSin
a gives a single
solution in terms of ArcSin. In fact, there is an infinite number of solutions to the equation, differing by arbitrary
multiples of . Solve gives only one of these solutions. When there are several simultaneous equations to be
solved in terms of inverse functions, Solve may fail to find any solutions, even when one exists. When inverse
functions are allowed, Solve solves for f [expr] first, then applies InverseFunction[f] to the result, equates it to
expr, and continues trying to solve for the remainder of the variables. See page 824. See also: FindRoot. New
in Version 2.
1188
InverseGammaRegularized InverseWeierstrassP
InverseGammaRegularized
InverseGammaRegularized[a, s] gives the inverse of the regularized incomplete gamma
function.
Mathematical function (see Section A.3.10). With the regularized incomplete gamma function defined by
Qa z a za, InverseGammaRegularized[a, s] is the solution for z in s Qa z.
InverseGammaRegularized[a, z , s] gives the inverse of GammaRegularized[a, z , z]. Note that the
arguments of InverseGammaRegularized are arranged differently than in InverseBetaRegularized . See
page 770. See also: InverseBetaRegularized , InverseErf. New in Version 3.
The inverse
InverseLaplaceTransform
InverseLaplaceTransform[expr, s, t] gives the inverse Laplace transform of expr.
InverseLaplaceTransform[expr, {s , s , ... }, {t , t , ... }] gives the multidimensional
inverse Laplace transform of expr.
i
st
The inverse Laplace transform of a function Fs is defined to be i
i Fse ds, where is an arbitrary positive
constant chosen so that the contour of integration lies to the right of all singularities in Fs. Assumptions and
other options to Integrate can also be given in InverseLaplaceTransform . In TraditionalForm ,
InverseLaplaceTransform is output using . See page 875. See also: LaplaceTransform ,
InverseFourierTransform , InverseZTransform , Integrate. New in Version 4.
InverseSeries
InverseSeries[s, x] takes the series s generated by Series, and gives a series for the inverse
of the function represented by s.
InverseSeries performs reversion of series. Given a series sy, InverseSeries[s, x] gives a series for y such
that sy x. InverseSeries can be applied to any SeriesData object with the appropriate structure, whether or
not it has been generated by Series. See page 887. See also: Solve, InverseFunction. New in Version 1.
InverseWeierstrassP
InverseWeierstrassP[p, {g , g
}] gives a value of u for which the Weierstrass function
jug g g
is equal to p.
Mathematical function (see Section A.3.10). The value of u returned always lies in the fundamental period
parallelogram defined by the complex half-periods and $ . InverseWeierstrassP[{p, q}, {g , g
}] finds the
unique value of u for which p jug g g
and q j$ ug g g
. For such a value to exist, p and q must be related
by q
p
g p g
. See page 782 for a discussion of argument conventions for elliptic functions. See
page 785. See also: WeierstrassP, WeierstrassPPrime , WeierstrassHalfPeriods . New in Version 3.
InverseZTransform JacobiZeta
1189
InverseZTransform
InverseZTransform[expr, z, n] gives the inverse Z transform of expr.
The inverse Z transform of a function Fz is defined to be the contour integral
See also: ZTransform, InverseLaplaceTransform . New in Version 4.
i
n dz.
) Fzz
JacobiAmplitude
JacobiAmplitude[u, m] gives the amplitude amu/m for Jacobi elliptic functions.
Mathematical function (see Section A.3.10). JacobiAmplitude[u, m] converts from the argument u for an elliptic
function to the amplitude . JacobiAmplitude is the inverse of the elliptic integral of the first kind. If u F/m,
then amu/m. See page 785. New in Version 1.
JacobiP
JacobiP[n, a, b, x] gives the Jacobi polynomial Pab
n x.
Mathematical function (see Section A.3.10). Explicit polynomials are given when possible. Pnab x satisfies the
differential equation x y$$ b a a b xy$ nn a b y . The Jacobi polynomials are orthogonal
with weight function xa xb . JacobiP[n, a, b, z] has a branch cut discontinuity in the complex z plane
running from to . See page 766. See also: LegendreP, ChebyshevT, ChebyshevU, GegenbauerC. New in
Version 1.
JacobiSymbol
JacobiSymbol[n, m] gives the Jacobi symbol mn .
Integer mathematical function (see Section A.3.10). For prime m, the Jacobi symbol reduces to the Legendre
symbol. The Legendre symbol is equal to M depending on whether n is a quadratic residue modulo m. See
page 752. See also: FactorInteger , MoebiusMu. New in Version 1.
JacobiZeta
JacobiZeta[, m] gives the Jacobi zeta function Z/m.
Mathematical function (see Section A.3.10). The Jacobi zeta function is given in terms of elliptic integrals by
Z/m E/m EmF/mKm. Argument conventions for elliptic integrals are discussed on page 782. See
page 783. See also: EllipticE, EllipticF, EllipticK. New in Version 2.
Join Label
1190
Join
Join[list , list , ... ] concatenates lists together. Join can be used on any set of expressions
that have the same head.
Join works on SparseArray objects by effectively concatenating the corresponding ordinary lists.
page 126. See also: Union, StringJoin, Append, Prepend, PadLeft. New in Version 1.
See
JordanDecomposition
JordanDecomposition[m] yields the Jordan decomposition of a square matrix m. The result is
a list {s, j} where s is a similarity matrix and j is the Jordan canonical form of m.
The original matrix m is equal to s . j . Inverse[s]. The matrix m can be either numerical or symbolic.
page 915. See also: Eigensystem, SingularValueDecomposition , QRDecomposition , SchurDecomposition ,
MatrixExp. New in Version 3.
See
Khinchin
Khinchin is Khinchins constant, with numerical value
.
Mathematical constant (see Section A.3.11). Khinchins constant (sometimes called Khintchines constant) is given
log s
. See page 765. See also: ContinuedFraction . New in Version 4.
by
s ss
KleinInvariantJ
KleinInvariantJ[] gives the Klein invariant modular elliptic function J.
Mathematical function (see Section A.3.10). The argument is the ratio of Weierstrass half-periods $ .
KleinInvariantJ is given in terms of Weierstrass invariants by g
g
g
. J is invariant under any
combination of the modular transformations # and # . See page 782 for a discussion of argument
conventions for elliptic functions. See page 787. See also: ModularLambda, DedekindEta,
WeierstrassInvariants , EllipticTheta . New in Version 3.
KroneckerDelta
KroneckerDelta[n , n , ... ] gives the Kronecker delta n n , equal to 1 if all the ni are
equal, and 0 otherwise.
KroneckerDelta[0] gives 1; KroneckerDelta[n] gives 0 for other numeric n. KroneckerDelta has attribute
Orderless. See page 749. See also: DiscreteDelta , IdentityMatrix , Equal, UnitStep, If, Signature,
DiracDelta. New in Version 4.
Label
Label[tag] represents a point in a compound expression to which control can be transferred
using Goto.
Label must appear as an explicit element of a CompoundExpression object.
page 354. See also: Catch. New in Version 1.
See
LaguerreL LatticeReduce
1191
LaguerreL
LaguerreL[n, x] gives the Laguerre polynomial Ln x.
LaguerreL[n, a, x] gives the generalized Laguerre polynomial Lan x.
Mathematical function (see Section A.3.10). Explicit polynomials are given when possible. Ln x Ln x. The
Laguerre polynomials are orthogonal with weight function xa ex . They satisfy the differential equation
xy$$ a xy$ ny . LaguerreL[n, x] is an entire function of x with no branch cut discontinuities. See
page 766. See also: HermiteH. New in Version 1.
LanguageCategory
LanguageCategory is an option for Cell which determines in what category of language the
contents of the cell should be assumed to be for purposes of spell checking and hyphenation.
Possible settings for LanguageCategory are:
"Formula"
"Mathematica"
"NaturalLanguage"
None
mathematical formula
Mathematica input
human natural language
do no spell checking or hyphenation
LanguageCategory is normally set to "NaturalLanguage" for text cells, and to "Mathematica" for input and
output cells. LanguageCategory is more often set at the level of styles than at the level of individual cells. See
page 613. See also: $Language, Hyphenation, FormatType. New in Version 4.
LaplaceTransform
LaplaceTransform[expr, t, s] gives the Laplace transform of expr.
LaplaceTransform[expr, {t , t , ... }, {s , s , ... }] gives the multidimensional Laplace
transform of expr.
The Laplace transform of a function ft is defined to be ftest dt. The lower limit of the integral is effectively
taken to be , so that the Laplace transform of the Dirac delta function t is equal to 1. Assumptions and
other options to Integrate can also be given in LaplaceTransform . In TraditionalForm , LaplaceTransform is
output using . See page 875. See also: InverseLaplaceTransform , FourierTransform , ZTransform,
Integrate. New in Version 4.
Last
Last[expr] gives the last element in expr.
Last[expr] is equivalent to expr[[-1]].
New in Version 1.
LatticeReduce
LatticeReduce[{v , v , ... }] gives a reduced basis for the set of vectors vi .
The elements of the vi can be integers, Gaussian integers, or Gaussian rational numbers. See page 752.
Implementation notes: see page 1067. See also: Rationalize, ContinuedFraction . Related package:
NumberTheory`Recognize` . New in Version 1.
LCM Length
1192
LCM
LCM[n , n , ... ] gives the least common multiple of the integers ni .
Integer mathematical function (see Section A.3.10). LCM also works with rational numbers; LCM[r , r , . . . ] gives
the least rational number r for which all the r/ri are integers. LCM has attributes Flat and Orderless. See
page 749. See also: GCD, PolynomialLCM. New in Version 1.
LeafCount
LeafCount[expr] gives the total number of indivisible subexpressions in expr.
LeafCount gives a measure of the total size of an expression. LeafCount counts the number of subexpressions
in expr which correspond to leaves on the expression tree. Example: LeafCount[1 + a + b^2] # 6 .
LeafCount is based on FullForm representation of expressions. Numbers with heads Rational and Complex are
treated as composite objects, just as in FullForm. See page 714. See also: ByteCount, Length, Depth, AtomQ.
New in Version 1.
-
LegendreP
LegendreP[n, x] gives the Legendre polynomial Pn x.
LegendreP[n, m, x] gives the associated Legendre polynomial Pm
n x.
Mathematical function (see Section A.3.10). Explicit formulas are given for integer n and m. The Legendre
polynomials satisfy the differential equation x d ydx xdydx nn y . The Legendre polynomials
are orthogonal with unit weight function. The associated Legendre polynomials are defined by
m
m dm dxm P x.
Pm
For arbitrary complex values of n, m and z, LegendreP[n, z] and
n
n x x
LegendreP[n, m, z] give Legendre functions of the first kind. LegendreP[n, m, a, z] gives Legendre functions
of type a. The default is type 1. - The symbolic form of type 1 involves z m , of type 2 involves
zm zm and of type 3 involves zm zm. Type 1 is defined only for z within the unit circle
in the complex plane. Type 2 represents an analytic continuation of type 1 outside the unit circle. Type 2
functions have branch cuts from to and from to in the complex z plane. Type 3 functions have a
single branch cut from to . - LegendreP[n, m, a, z] is defined to be
Hypergeometric2F1Regularized[-n,n+1,1-m,(1-z)/2] multiplied by zm zm for type 2 and by
zm zm for type 3. See pages 766 and 777. See also: SphericalHarmonicY . New in Version 1;
modified in Version 5.0.
LegendreQ
LegendreQ[n, z] gives the Legendre function of the second kind Qn z.
LegendreQ[n, m, z] gives the associated Legendre function of the second kind Qm
n z.
Mathematical function (see Section A.3.10). For integer n and m, explicit formulas are generated. The Legendre
functions satisfy the differential equation z y$$ zy$ enn m z fy . LegendreQ[n, m, a, z]
gives Legendre functions of type a. The default is type 1. LegendreQ of types 1, 2 and 3 are defined in terms of
LegendreP of these types, and have the same branch cut structure. See page 777. New in Version 1; modified in
Version 3.
-
Length
Length[expr] gives the number of elements in expr.
See page 236. , When expr is a SparseArray object, Length[expr] returns the length of corresponding ordinary
list. - Otherwise, Length[expr] returns 0 whenever AtomQ[expr] is True. See also: LeafCount, ByteCount, Depth.
New in Version 1; modified in Version 5.0.
LerchPhi Level
1193
LerchPhi
LerchPhi[z, s, a] gives the Lerch transcendent Ez s a.
k
s
Mathematical function (see Section A.3.10). Ez s a
k z a k , where any term with k a is excluded.
k
s
LerchPhi[z, s, a, DoublyInfinite->True] gives the sum
z
LerchPhi is a generalization of
k a k .
Zeta and PolyLog. See page 772. Related package: NumberTheory`Ramanujan` . New in Version 1.
Less
x < y yields True if x is determined to be less than y.
x < x < x
yields True if the xi form a strictly increasing sequence.
Less gives True or False when its arguments are real numbers. Less does some simplification when its
arguments are not numbers. For exact numeric quantities, Less internally uses numerical approximations to
establish numerical ordering. This process can be affected by the setting of the global variable $MaxExtraPrecision .
See page 86. See also: LessEqual, Greater, Positive, Element. New in Version 1; modified in Version 3.
LessEqual
x <= y or x y yields True if x is determined to be less than or equal to y.
x x x
yields True if the xi form a non-decreasing sequence.
x y can be entered as x H <= H y or x \[LessEqual] y. LessEqual gives True or False when its arguments are
real numbers. LessEqual does some simplification when its arguments are not numbers. For exact numeric
quantities, LessEqual internally uses numerical approximations to establish numerical ordering. This process can be
affected by the setting of the global variable $MaxExtraPrecision . In StandardForm, LessEqual is printed
using . x ( y, entered as x H </ H y or x \[LessSlantEqual] y, can be used on input as an alternative to x y.
See page 86. See also: Less, GreaterEqual, Element. New in Version 1; modified in Version 3.
LetterQ
LetterQ[string] yields True if all the characters in the string are letters, and yields False
otherwise.
LetterQ[string] by default gives False if string contains any space or punctuation characters. LetterQ handles
both ordinary and special characters. LetterQ treats as letters all special characters explicitly listed as letters in
the table on pages 13541401. In general, LetterQ treats as letters all characters that appear as ordinary text in
any language. LetterQ treats as letters such special characters as , , and . LetterQ does not treat as
letters Z (\[EmptySet]),
(\[HBar]), (\[Angstrom]) or (\[Sum]). See page 413. See also: DigitQ,
UpperCaseQ, LowerCaseQ, CharacterRange . New in Version 2; modified in Version 3.
Level
Level[expr, levelspec] gives a list of all subexpressions of expr on levels specified by levelspec.
Level[expr, levelspec, f] applies f to the list of subexpressions.
Level uses the standard level specification described on page 1041. Level[expr, {-1}] gives a list of all atomic
objects in expr. Level traverses expressions in depth-first order, so that the subexpressions in the final list are
ordered lexicographically by their indices. See page 239. See also: Apply, Map, Scan. New in Version 1.
Lighting LimitsPositioning
1194
Lighting
Lighting is an option for Graphics3D and related functions that specifies whether to use
simulated illumination in three-dimensional pictures.
Lighting -> True uses simulated illumination. The ambient light level is specified by the option AmbientLight.
The option LightSources gives the positions and intensities of point light sources. Lighting -> False uses no
simulated illumination. In SurfaceGraphics , polygons are then shaded according to their height, or according to
the ColorFunction option that is given. See pages 526 and 544. See also: Shading, ColorFunction ,
SurfaceColor. New in Version 1.
LightSources
LightSources is an option for Graphics3D and related functions that specifies the properties
of point light sources for simulated illumination.
The basic form is LightSources -> {s , s , . . . }, where the si are the specifications for each light source. Each si
has the form {direction, color}. The direction is specified as {x, y, z}, where the components are with respect to
the final display area. The x and y are horizontal and vertical in the plane of the display; z is orthogonal to the
display. Positive z is in front. Only the relative magnitude of the components is relevant; the overall normalization
of the vector is ignored. The color can be specified by GrayLevel, Hue or RGBColor. Simulated illumination
determines the shading of polygons in three-dimensional pictures. The shading of a particular polygon is
computed as a sum of contributions from point light sources, plus a contribution from ambient light. Surface
properties of polygons are specified by SurfaceColor directives. Light reflection properties assumed for polygons
are described in the notes for SurfaceColor . See page 545. See also: AmbientLight . New in Version 1.
-
Limit
Limit[expr, x->x ] finds the limiting value of expr when x approaches x .
Example: Limit[Sin[x]/x, x->0] # 1 . Limit[expr, x->x , Direction -> 1] computes the limit as x
approaches x from smaller values. Limit[expr, x->x , Direction -> -1] computes the limit as x approaches x
from larger values. Limit returns Interval objects to represent ranges of possible values, for example at essential
singularities. Limit returns unevaluated when it encounters functions about which it has no specific information.
Limit therefore by default makes no explicit assumptions about symbolic functions. - Assumptions can be
specified as a setting for the option Assumptions. See page 893. See also: Series, Residue. Related package:
NumericalMath`NLimit` . New in Version 1; modified in Version 5.0.
LimitsPositioning
LimitsPositioning is an option for UnderoverscriptBox and related boxes which specifies
whether to change the positioning of underscripts and overscripts in the way conventional for
limits.
UnderoverscriptBox[x, y, z, LimitsPositioning->False] is always displayed with explicit underscripts and
z
z
overscripts, as x . UnderoverscriptBox[x, y, z, LimitsPositioning->True] is displayed as x when large, and
y
The xzy form is used when the box appears in a subscript or other script, or inline in a piece of
text. With the default setting LimitsPositioning->Automatic the display of UnderoverscriptBox[x, y, z]
depends on x. If x is \[Sum], \[Product] or another form conventionally displayed with limits, then
LimitsPositioning->True is effectively used. Otherwise, LimitsPositioning->False is used.
LimitsPositioningTokens is a Cell option which can be set to a list of forms for which
LimitsPositioning->True should be used. See page 458. See also: ScriptSizeMultipliers . New in
Version 3.
Line LinearSolve
1195
Line
Line[{pt , pt , ... }] is a graphics primitive which represents a line joining a sequence of points.
Line can be used in both Graphics and Graphics3D (two- and three-dimensional graphics). The positions of
points can be specified either in ordinary coordinates, as {x, y} or {x, y, z}, or in scaled coordinates as
Scaled[{x, y}] or Scaled[{x, y, z}]. Offset can be used to specify coordinates in two dimensions. The line
consists of a sequence of straight segments joining the specified points. Line thickness can be specified using
Thickness or AbsoluteThickness . Line dashing can be specified using Dashing or AbsoluteDashing . Line
shading or coloring can be specified using CMYKColor, GrayLevel, Hue or RGBColor. See pages 492 and 520. See
also: Polygon, PlotJoined. Related packages: Graphics`Arrow` , Graphics`Spline` . New in Version 1; modified
in Version 3.
-
LinearProgramming
LinearProgramming[c, m, b] finds a vector x which minimizes the quantity c.x subject to the
constraints m x ! b and x ! .
, LinearProgramming[c, m, {{b , s }, {b , s }, ... }] finds a vector x which minimizes c.x
subject to x ! and linear constraints specified by the matrix m and the pairs {bi , si }. For each
row mi of m, the corresponding constraint is mi . x bi if si == 1, or mi . x == bi if si == 0, or
mi . x bi if si == -1.
, LinearProgramming[c, m, b, l] minimizes c.x subject to the constraints specified by m and
b and x ! l.
, LinearProgramming[c, m, b, {l , l , ... }] minimizes c.x subject to the constraints
specified by m and b and xi ! li .
, LinearProgramming[c, m, b, {{l , u }, {l , u }, ... }] minimizes c.x subject to the
constraints specified by m and b and li * xi * ui .
All entries in the vectors c and b and the matrix m must be real numbers. , The bounds li and ui must be real
numbers or Infinity or -Infinity. LinearProgramming gives exact rational number results if its input is exact.
, LinearProgramming returns unevaluated if no solution can be found. , LinearProgramming finds approximate
numerical results if its input contains approximate numbers. The option Tolerance specifies the tolerance to be used
for internal comparisons. The default is Tolerance->Automatic , which does exact comparisons for exact numbers,
and uses tolerance for approximate numbers. , SparseArray objects can be used in LinearProgramming .
, With Method->"InteriorPoint" , LinearProgramming uses interior point methods.
See page 975.
Implementation notes: see page 1068. See also: NMinimize, Minimize. New in Version 2; modified in Version 5.0.
LinearSolve
LinearSolve[m, b] finds an x which solves the matrix equation m.x==b.
, LinearSolve[m] generates a LinearSolveFunction[... ] which can be applied repeatedly
to different b.
LinearSolve works on both numerical and symbolic matrices, as well as SparseArray objects. The argument
b can be either a vector or a matrix. The matrix m can be square or rectangular. , LinearSolve[m] and
LinearSolveFunction[. . . ] provide an efficient way to solve the same approximate numerical linear system many
times. , LinearSolve[m, b] is equivalent to LinearSolve[m][b]. For underdetermined systems, LinearSolve
will return one of the possible solutions; Solve will return a general solution. LinearSolve[m, b, Modulus -> n]
takes the matrix equation to be modulo n. LinearSolve[m, b, ZeroTest -> test] evaluates test[ m[[i, j]] ] to
determine whether matrix elements are zero. The default setting is ZeroTest -> (# == 0 &). - A Method option
can also be given. Settings for exact and symbolic matrices include "CofactorExpansion" ,
"DivisionFreeRowReduction" and "OneStepRowReduction" . Settings for approximate numerical matrices include
"Cholesky", and for sparse arrays "Multifrontal" and "Krylov". The default setting of Automatic switches
between these methods depending on the matrix given. See page 907. Implementation notes: see page 1069.
See also: Inverse, PseudoInverse , Solve, NullSpace, CoefficientArrays , CholeskyDecomposition . New in
Version 1; modified in Version 5.0.
-
LinearSolveFunction LinkClose
1196
LinearSolveFunction
LinearSolveFunction[dimensions, data] represents a function for providing solutions to a
matrix equation.
LinearSolveFunction[. . . ] is generated by LinearSolve[m]. LinearSolveFunction works like Function.
LinearSolveFunction[. . . ][b] finds the solution to the matrix equation m . x == b for the specific vector or
matrix b. In standard output format, only the dimensions element of a LinearSolveFunction object is printed
explicitly. The remaining elements are indicated by <>. dimensions specifies the dimensions of the matrix m from
which the LinearSolveFunction was constructed. See page 252. See also: LinearSolve, Inverse,
LUDecomposition , CholeskyDecomposition . New in Version 5.0.
LineIndent
LineIndent is an option for Cell, StyleBox and StyleForm which specifies how many ems of
indentation to add at the beginnings of lines for each level of nesting in an expression.
The typical default setting is LineIndent->1. The setting for LineIndent determines the amount of indentation
that will be inserted after any explicit RETURN is entered when AutoIndent->True. See also:
LineIndentMaxFraction , PageWidth. New in Version 3.
LineIndentMaxFraction
LineIndentMaxFraction is an option for Cell, StyleBox and StyleForm which specifies the
maximum fraction of the total page width to indent at the beginnings of lines.
The typical default setting is LineIndentMaxFraction->0.5 . The setting for LineIndentMaxFraction is relevant
in formatting deeply nested expressions. See also: LineIndent, PageWidth. New in Version 3.
LineSpacing
LineSpacing is an option for Cell, StyleBox and StyleForm which specifies the spacing
between successive lines of text.
LineSpacing->{c, 0} leaves space so that the total height of each line is c times the height of its contents.
LineSpacing->{0, n} makes the total height of each line exactly n printers points. LineSpacing->{c, n}
makes the total height c times the height of the contents plus n printers points. A typical default setting is
LineSpacing->{1, 1}, which leaves space for the contents of the line, plus 1 printers point (approximately
of
an inch) of extra space. LineSpacing->{2, 0} makes text double spaced. LineSpacing-> {1, -n} tightens
text by n printers points. LineSpacing applies both to ordinary text and Mathematica expressions. In ordinary
text, LineSpacing determines the spacing between lines produced by automatic linebreaking. For lines produced by
explicit RETURN characters ParagraphSpacing is added. In Mathematica expressions, LineSpacing is used whether
lines are produced by automatic linebreaking or by explicit RETURN characters. Extra space specified by
LineSpacing is inserted equally above and below a line, except that no extra space is inserted before the first line
or after the last line of an expression or cell. See page 611. See also: FontSize, ParagraphSpacing . New in
Version 3.
LinkClose
LinkClose[link] closes an open MathLink connection.
link must be an active LinkObject, as returned by functions like LinkLaunch and Links.
connection does not necessarily terminate the program at the other end of the connection.
also: LinkInterrupt, Close. New in Version 3.
Closing a MathLink
See page 680. See
LinkConnect LinkLaunch
1197
LinkConnect
LinkConnect["name"] connects to a MathLink link created by another program.
LinkConnect by default operates with internet TCP links, with names of the form port@host. Ports are typically
specified by numbers. LinkConnect can connect to a port on a remote computer system. On some computer
systems, LinkConnect[ ] will bring up a port browser. LinkConnect returns a LinkObject. You can use
LinkConnect with LinkCreate to set up peer-to-peer communication between two Mathematica processes.
LinkConnect can be used to connect to a link created by calling LinkCreate in another Mathematica process.
LinkConnect can be used to connect to an external program that has created a MathLink link by calling the
appropriate MathLink library functions. External programs built from MathLink templates using mcc and mprep can
typically create MathLink links whenever they are given -linkcreate command-line arguments. The option
LinkProtocol specifies the underlying data transport protocol that LinkConnect should use. LinkConnect
internally calls a function analogous to the MLOpenArgv() function in the MathLink library. Even though no
program may yet be connected to the other end of the MathLink link, the function LinkConnect will return
immediately and will not block. See page 680. See also: LinkCreate, LinkLaunch, LinkClose. New in
Version 3.
LinkCreate
LinkCreate["name"] creates a MathLink link with the specified name for another program to
connect to.
LinkCreate[ ] picks an unused port on your computer system and creates a MathLink link
on it.
LinkCreate returns a LinkObject. You can use LinkCreate and LinkConnect to set up peer-to-peer
communication between two Mathematica processes. The option LinkProtocol specifies the underlying data
transport protocol to use. LinkCreate internally calls a function analogous to the MLOpenArgv() function in the
MathLink library. See page 680. See also: LinkConnect, LinkLaunch, LinkClose. New in Version 3.
LinkInterrupt
LinkInterrupt[link] sends an interrupt to the program at the other end of the specified
MathLink connection.
link must be an active LinkObject, as returned by functions such as LinkLaunch or Links. It is up to the
external program to determine how it will handle the interrupt. External programs created from MathLink
templates will by default set the global variable MLAbort if they receive an abort. See page 686. See also:
Interrupt, LinkClose. New in Version 3.
LinkLaunch
LinkLaunch["prog"] starts the external program prog and opens a MathLink connection to it.
LinkLaunch["prog"] runs prog as a subsidiary or child process to your current Mathematica session. You can use a
command such as LinkLaunch["math -mathlink"] to launch a subsidiary Mathematica kernel process from within
your Mathematica session. On most computer systems calling LinkLaunch["prog"] multiple times with the same
argument will start several prog processes running. On some computer systems, LinkLaunch[ ] will bring up a
program browser. LinkLaunch returns a LinkObject. The option LinkProtocol specifies the underlying data
transport protocol to use. LinkLaunch internally calls a function analogous to the MLOpenArgv() function in the
MathLink library. See page 683. See also: Install, LinkCreate, LinkConnect, LinkClose. New in Version 3.
LinkObject Links
1198
LinkObject
LinkObject["name", n] is an object that represents an active MathLink connection for
functions such as LinkRead and LinkWrite .
LinkConnect, LinkCreate, LinkLaunch and Install all return LinkObject objects. The integer n is a serial
number used to distinguish links with the same name. name is typically the name of an external program, or an
internet TCP specification of the form port@host. See pages 659 and 687. See also: Links, LinkReadyQ,
InputStream. New in Version 3.
LinkPatterns
LinkPatterns[link] gives a list of the patterns for which definitions were set up when the
external program associated with the specified MathLink connection was installed.
Each element of the list returned by LinkPatterns is wrapped in HoldForm to prevent evaluation. The patterns
in LinkPatterns typically originate in :Pattern: specifications in the MathLink templates used to create source
code for the external program. Uninstall[link] calls Unset on the patterns in LinkPatterns[link] . See
page 662. See also: Install. New in Version 3.
-
LinkProtocol
LinkProtocol is an option to LinkLaunch , Install and related functions which specifies the
underlying data transport protocol to use for a new MathLink link.
Typical settings for LinkProtocol are "SharedMemory" and "FileMap" (Windows), "Pipes" (Unix, Macintosh)
and "TCPIP" (all systems). See page 677. New in Version 3; modified in Version 5.0.
LinkRead
LinkRead[link] reads one expression from the specified MathLink connection.
LinkRead[link, h] wraps h around the expression read before evaluating it.
link must be an active LinkObject, as returned by functions like LinkLaunch or Links. LinkRead will wait until
it has read a complete expression before returning. You can test whether an expression is ready to be read from a
particular link using LinkReadyQ. You can use LinkRead[link, Hold] to get an expression from a link without
evaluating it. See page 680. See also: LinkReadyQ, LinkWrite, Read. New in Version 3.
LinkReadyQ
LinkReadyQ[link] tests whether there is an expression ready to read from the specified
MathLink connection.
link must be an active LinkObject, as returned by functions like LinkLaunch or Links. If LinkReadyQ[link]
returns True, then LinkRead[link] will not block under any normal circumstances. If LinkReadyQ[link] returns
False, then LinkRead[link] will block, and will not return until something becomes available to read on link.
LinkReadyQ[link] tests whether there is any data to read; it cannot determine whether the data represents a
complete expression. LinkReadyQ corresponds to the MathLink library function MLReady(). See page 680. See
also: LinkRead, LinkWrite, LinkInterrupt. New in Version 3.
Links
Links[ ] gives a list of all MathLink connections that are currently open.
Links["name"] lists only links with the specified name.
Links returns a list of LinkObject objects. See page 662.
LinkReadyQ, LinkLaunch, LinkClose. New in Version 3.
LinkWrite ListConvolve
1199
LinkWrite
LinkWrite[link, expr] writes expr to the specified MathLink connection.
link must be an active LinkObject, as returned by functions like LinkLaunch or Links. You can use
LinkWrite[link, Unevaluated[expr]] to write expr to the link without evaluating it. The head of expr will often
be a packet which specifies how expr should be processed by the program which receives it. When LinkWrite is
used to send data to a Mathematica kernel, EnterTextPacket["string"] enters the text of an input line, and
EvaluatePacket[expr] sends an expression for evaluation. See page 680. See also: LinkRead, Write,
FrontEndExecute. New in Version 3.
List
{e , e , ... } is a list of elements.
Lists are very general objects that represent collections of expressions. Functions with attribute Listable are
automatically threaded over lists, so that they act separately on each list element. Most built-in mathematical
functions are Listable. {a, b, c} represents a vector. {{a, b}, {c, d}} represents a matrix. Nested lists can
be used to represent tensors. See page 115. See also: Sequence. New in Version 1.
Listable
Listable is an attribute that can be assigned to a symbol f to indicate that the function f
should automatically be threaded over lists that appear as its arguments.
Listable functions are effectively applied separately to each element in a list, or to corresponding elements in each
list if there is more than one list. Most built-in mathematical functions are Listable. Example: Log is Listable.
Log[{a,b,c}] # Log
a, Log
b, Log
c . All the arguments which are lists in a Listable function must
be of the same length. Arguments that are not lists are copied as many times as there are elements in the lists.
Example: Plus is Listable. {a, b, c} + x # a x, b x, c x . See page 329. See also: Thread, Map,
Sequence, SparseArray. New in Version 1.
ListContourPlot
ListContourPlot[array] generates a contour plot from an array of height values.
ListContourPlot returns a ContourGraphics object. ListContourPlot has the same options as
ContourGraphics. Successive rows of array are arranged up the page; successive columns across the page.
notes for ContourGraphics . See page 159. New in Version 1.
See
ListConvolve
ListConvolve[ker, list] forms the convolution of the kernel ker with list.
ListConvolve[ker, list, k] forms the cyclic convolution in which the kth element of ker is
aligned with each element in list.
ListConvolve[ker, list, {kL , kR }] forms the cyclic convolution whose first element contains
list[[1]] ker[[kL ]] and whose last element contains list[[-1]] ker[[kR ]].
ListConvolve[ker, list, klist, p] forms the convolution in which list is padded at each end
with repetitions of the element p.
ListConvolve[ker, list, klist, {p , p , ... }] forms the convolution in which list is padded at
each end with cyclic repetitions of the pi .
ListConvolve[ker, list, klist, padding, g, h] forms a generalized convolution in which g is
used in place of Times and h in place of Plus.
ListConvolve[ker, list, klist, padding, g, h, lev] forms a convolution using elements at level
lev in ker and list.
(continued)
1200
ListConvolve
(continued)
With kernel Kr and list as , ListConvolve[ker, list] computes r Kr asr , where the limits of the sum are such that
the kernel never overhangs either end of the list. Example:
ListConvolve[{x,y}, {a,b,c}] # b x a y, c x b y . ListConvolve[ker, list] gives a result of length
Length[list]-Length[ker]+1 . ListConvolve[ker, list] allows no overhangs and is equivalent to
ListConvolve[ker, list, {-1, 1}]. ListConvolve[ker, list, k] is equivalent to ListConvolve[ker, list, {k, k}].
The values of kL and kR in ListConvolve[ker, list, {kL , kR }] determine the amount of overhang to allow at
each end of list. Common settings for {kL , kR } are:
{-1, 1}
{-1, -1}
{1, 1}
{1, -1}
no overhangs (default)
maximal overhang at the right-hand end
maximal overhang at the left-hand end
maximal overhangs at both beginning and end
ListCorrelate
ListCorrelate[ker, list] forms the correlation of the kernel ker with list.
ListCorrelate[ker, list, k] forms the cyclic correlation in which the kth element of ker is
aligned with each element in list.
ListCorrelate[ker, list, {kL , kR }] forms the cyclic correlation whose first element contains
list[[1]] ker[[kL ]] and whose last element contains list[[-1]] ker[[kR ]].
ListCorrelate[ker, list, klist, p] forms the correlation in which list is padded at each end
with repetitions of the element p.
ListCorrelate[ker, list, klist, {p , p , ... }] forms the correlation in which list is padded at
each end with cyclic repetitions of the pi .
ListCorrelate[ker, list, klist, padding, g, h] forms a generalized correlation in which g is
used in place of Times and h in place of Plus.
ListCorrelate[ker, list, klist, padding, g, h, lev] forms a correlation using elements at level
lev in ker and list.
(continued)
ListCorrelate
1201
(continued)
With kernel Kr and list as , ListCorrelate[ker, list] computes r Kr asr , where the limits of the sum are such
that the kernel never overhangs either end of the list. Example:
ListCorrelate[{x,y}, {a,b,c}] # a x b y, b x c y . For a one-dimensional list ListCorrelate[ker, list]
is equivalent to ListConvolve[Reverse[ker], list]. For higher-dimensional lists, ker must be reversed at every
level. See notes for ListConvolve. Settings for kL and kR are negated in ListConvolve relative to
ListCorrelate. Common settings for {kL , kR } in ListCorrelate are:
{1, -1}
{1, 1}
{-1, -1}
{-1, 1}
no overhangs (default)
maximal overhang at the right-hand end
maximal overhang at the left-hand end
maximal overhangs at both beginning and end
ListDensityPlot
ListDensityPlot[array] generates a density plot from an array of height values.
ListDensityPlot returns a DensityGraphics object. ListDensityPlot has the same options as
DensityGraphics. Successive rows of array are arranged up the page; successive columns across the page.
notes for DensityGraphics . See page 159. New in Version 1.
See
ListInterpolation
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.
You can replace {xmin, xmax} etc. by explicit lists of positions for grid lines. The grid lines are otherwise assumed
to be equally spaced. ListInterpolation[array] assumes grid lines at integer positions in each direction. array
can be an array in any number of dimensions, corresponding to a list with any number of levels of nesting.
ListInterpolation[array, domain] generates an InterpolatingFunction object which returns values with the
same precision as those in {array, domain}. See notes for Interpolation. See page 934. See also:
FunctionInterpolation , ListContourPlot, Quantile. New in Version 3.
ListPlay
ListPlay[{a , a , ... }] plays a sound whose amplitude is given by the sequence of levels ai .
ListPlay returns a Sound object.
DisplayFunction
Epilog
PlayRange
Prolog
SampleDepth
SampleRate
$SoundDisplayFunction
{}
Automatic
{}
8
8192
ListPlay[{list , list }] generates stereo sound. The left-hand channel is given first.
ListPlay[{list , list , . . . }] generates sound on any number of channels. If the lists are of different lengths,
silence is inserted at the ends of the shorter lists. See page 172. See also: Play, SampledSoundList , Show.
Related package: Miscellaneous`Audio` . New in Version 2.
ListPlot LogGamma
1202
ListPlot
ListPlot[{y , y , ... }] plots a list of values. The x coordinates for each point are taken to be
1, 2, ... .
ListPlot[{{x , y }, {x , y }, ... }] plots a list of values with specified x and y coordinates.
ListPlot returns a Graphics object.
PlotJoined
PlotStyle
False
Automatic
ListPlot has the same options as Graphics, with the following additions:
Setting PlotJoined -> True gives a line joining the points. ListPlot has the default option setting
Axes -> True. See page 159. See also: Plot, Fit. Related packages: Graphics`MultipleListPlot` ,
Graphics`Graphics` . New in Version 1.
ListPlot3D
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.
ListPlot3D returns a SurfaceGraphics object. ListPlot3D has the same options as SurfaceGraphics.
ListPlot3D has the default option setting Axes -> True. array should be a rectangular array of real numbers,
representing z values. There will be holes in the surface corresponding to any array elements that are not real
numbers. If array has dimensions m n, then shades must have dimensions m n . The elements of
shades must be either GrayLevel, Hue or RGBColor, or SurfaceColor objects. See page 159. See also: Plot3D.
Related packages: Graphics`Graphics3D` , DiscreteMath`ComputationalGeometry` . New in Version 1.
Locked
Locked is an attribute which, once assigned, prevents modification of any attributes of a
symbol.
See page 329.
New in Version 1.
Log
Log[z] gives the natural logarithm of z (logarithm to base e).
Log[b, z] gives the logarithm to base b.
Mathematical function (see Section A.3.10). Log gives exact rational number results when possible. Log[z] has a
branch cut discontinuity in the complex z plane running from to . See page 761. See also: Exp, Power, Arg,
MantissaExponent , ProductLog, HarmonicNumber. New in Version 1.
LogGamma
LogGamma[z] gives the logarithm of the gamma function log z.
Mathematical function (see Section A.3.10). Unlike Log[Gamma[z]], LogGamma[z] is analytic throughout the
complex z plane, except for a branch cut discontinuity along the negative real axis. See page 770. New in
Version 2.
LogicalExpand MachinePrecision
1203
LogicalExpand
LogicalExpand[expr] expands out expressions containing logical connectives such as &&
and ||.
LogicalExpand applies distributive laws for logical operations. Example:
LogicalExpand[p && !(q || r)] # p && 9 q && 9 r . LogicalExpand generates ORs of ANDs corresponding to
disjunctive normal form, with some contractions. See pages 87 and 889. See also: Expand. New in Version 1.
LogIntegral
LogIntegral[z] is the logarithmic integral function liz.
z
Mathematical function (see Section A.3.10). The logarithmic integral function is defined by liz dtlog t , where
the principal value of the integral is taken. LogIntegral[z] has a branch cut discontinuity in the complex z
plane running from to . See page 774. See also: ExpIntegralE. New in Version 1.
LowerCaseQ
LowerCaseQ[string] yields True if all the characters in the string are lower-case letters, and
yields False otherwise.
LowerCaseQ treats both ordinary and special characters. See page 413. See also: UpperCaseQ, LetterQ,
ToLowerCase, ToCharacterCode . New in Version 2; modified in Version 3.
LUDecomposition
LUDecomposition[m] generates a representation of the LU decomposition of a square
matrix m.
LUDecomposition returns a list of three elements. The first element is a combination of upper and lower triangular
matrices, the second element is a vector specifying rows used for pivoting, and for approximate numerical matrices
m the third element is an estimate of the L condition number of m. See page 914. Implementation notes: see
page 1069. See also: LinearSolveFunction , CholeskyDecomposition , QRDecomposition, SchurDecomposition .
Related package: LinearAlgebra`Orthogonalization` . New in Version 3.
MachineNumberQ
MachineNumberQ[expr] returns True if expr is a machine-precision real or complex number,
and returns False otherwise.
See page 728.
Version 2.
,
New in
MachinePrecision
MachinePrecision is a symbol used to indicate machine-number precision.
The numerical value of MachinePrecision is $MachinePrecision . Precision[1.] gives MachinePrecision .
MachinePrecision is the default specification for precision in N and other numerical functions. Approximate real
numbers are assumed to have precision specified by MachinePrecision if fewer than $MachinePrecision explicit
digits are entered. The option setting WorkingPrecision->MachinePrecision specifies that internal computations
in numerical functions should be done with machine numbers. MachinePrecision is treated as a numeric
constant, with attribute Constant. See page 728. See also: $MachinePrecision , Precision. New in Version 5.0.
Magnification MantissaExponent
1204
Magnification
Magnification is an option for Cell which specifies at what magnification to display the cell.
Magnification is often set for styles of cells or whole notebooks instead of individual cells.
affects spaces between cells as well as individual cells. See page 604. New in Version 3.
Magnification
MakeBoxes
MakeBoxes[expr, form] is the low-level function used in Mathematica sessions to convert
expressions into boxes.
MakeBoxes does not evaluate expr. form can be StandardForm, TraditionalForm , or any other output form. You
can give definitions for MakeBoxes[expr, form] to specify your own rules for how expressions should be converted
to boxes. MakeBoxes is not automatically called on the results it generates. This means that explicit MakeBoxes
calls must typically be inserted into definitions that are given. If you change the output format for an expression
by giving a definition for MakeBoxes, there is no guarantee that output you get will subsequently be able to be
interpreted by Mathematica. Definitions you give for MakeBoxes will override built-in Mathematica rules for
generating output. See page 475. See also: MakeExpression, ToBoxes, Format. New in Version 3.
MakeExpression
MakeExpression[boxes, form] is the low-level function used in Mathematica sessions to
construct expressions from boxes.
MakeExpression returns its result wrapped in HoldComplete. form can be StandardForm , TraditionalForm , or
other forms for which interpretation rules have been defined. You can give definitions for
MakeExpression[expr, form] to specify your own rules for how boxes should be converted to expressions.
MakeExpression is not automatically called on the results it generates. This means that explicit MakeExpression
calls must typically be inserted into definitions for MakeExpression . MakeExpression is used whenever boxes are
supplied as input to Mathematica. The boxes that are fed to MakeExpression are constructed from textual input
by forming tokens, then grouping these according to standard Mathematica operator precedence rules, stripping out
spacing characters. StyleBox and other objects not intended for interpretation are removed. Definitions you give
for MakeExpression will override built-in Mathematica rules for processing input. Giving input prefaced by \!
makes Mathematica effectively perform MakeExpression. See page 475. See also: MakeBoxes, ToExpression.
New in Version 3.
MantissaExponent
MantissaExponent[x] gives a list containing the mantissa and exponent of a number x.
MantissaExponent[x, b] gives the base-b mantissa and exponent of x.
Example: MantissaExponent[3.4 10^25] # 0.34, 26 . The mantissa always lies between b and or
and b. MantissaExponent works with exact as well as approximate numeric quantities. Example:
MantissaExponent[Exp[Pi], 2] # , 5
.
32
New in Version 2; modified in Version 4.
Map MapIndexed
1205
Map
Map[f, expr] or f /@ expr applies f to each element on the first level in expr.
Map[f, expr, levelspec] applies f to parts of expr specified by levelspec.
Examples: Map[f, {a, b, c}] # f
a, f
b, f
c ; Map[f, a + b + c] # f
a f
b f
c . Level
specifications are described on page 1041. The default value for levelspec in Map is {1}. Examples:
Map[f, {{a,b},{c,d}}] # f
a, b, f
c, d ;
Map[f, {{a,b},{c,d}}, 2] # f
f
a, f
b, f
f
c, f
d ;
Map[f, {{a,b},{c,d}}, -1] # f
f
a, f
b, f
f
c, f
d . , If expr is a SparseArray object,
Map[f, expr] applies f to the values or subarrays that appear in expr. See page 244. See also: Apply, Scan,
MapAll, MapAt, MapIndexed, MapThread, Level, Operate. New in Version 1.
MapAll
MapAll[f, expr] or f //@ expr applies f to every subexpression in expr.
Example: MapAll[f, {{a,b},{c,d}}] # f
f
f
a, f
b, f
f
c, f
d . MapAll[f, expr] is
equivalent to Map[f, expr, {0, Infinity}]. MapAll[f, expr, Heads -> True] applies f inside the heads of the
parts of expr. See page 245. See also: ExpandAll, ReplaceAll. New in Version 1.
MapAt
MapAt[f, expr, n] applies f to the element at position n in expr. If n is negative, the position is
counted from the end.
MapAt[f, expr, {i, j, ... }] applies f to the part of expr at position {i, j, ... }.
MapAt[f, expr, {{i , j , ... }, {i , j , ... }, ... }] applies f to parts of expr at several
positions.
Example: MapAt[f, {a, b, c}, 2] # a, f
b, c .
MapAt[f, {a, b, c, d}, {{1}, {4}}] # f
a, b, c, f
d . MapAt[f, expr, {i, j, . . . }] or
MapAt[f, expr, {{i, j, . . . }}] applies f to the part expr[[i, j, . . . ]].
MapAt[f, expr, {{i , j , . . . }, {i , j , . . . }, . . . }] applies f to parts expr[[i , j , . . . ]], expr[[i , j , . . . ]], . . . .
The list of positions used by MapAt is in the same form as is returned by the function Position. MapAt applies
f repeatedly to a particular part if that part is mentioned more than once in the list of positions. Example:
MapAt[f, {a, b, c}, {{1}, {3}, {1}}] # f
f
a, b, f
c . See page 245. See also: ReplacePart,
Delete, FlattenAt. New in Version 1.
MapIndexed
MapIndexed[f, expr] applies f to the elements of expr, giving the part specification of each
element as a second argument to f.
MapIndexed[f, expr, levspec] applies f to all parts of expr on levels specified by levspec.
Example: MapIndexed[f, {a, b, c}] # f
a, 1, f
b, 2, f
c, 3 . Level specifications are
described on page 1041. The default value for levelspec in MapIndexed is {1}. Example:
MapIndexed[f, {{a, b}, {c, d}}, Infinity] #
f
f
a, 1, 1, f
b, 1, 2, 1, f
f
c, 2, 1, f
d, 2, 2, 2 . See page 246. See also:
MapAt. New in Version 2.
MapThread MathieuCharacteristicB
1206
MapThread
MapThread[f, {{a , a , ... }, {b , b , ... }, ... }] gives
{f [a , b , ... ], f [a , b , ... ], ... }.
MapThread[f, {expr , expr , ... }, n] applies f to the parts of the expri at level n.
Example: MapThread[f, {{a1, a2}, {b1, b2}}] # f
a1, b1, f
a2, b2 .
MapThread[f, {{{a1, a2}}, {{b1, b2}}}] # f
a1, a2, b1, b2 .
MapThread[f, {{{a1, a2}}, {{b1, b2}}}, 2] # f
a1, b1, f
a2, b2 .
Thread, Inner. New in Version 2.
MatchLocalNames
MatchLocalNames is an option for Trace and related functions which specifies whether
symbols such as x should match symbols with local names of the form x$nnn.
The default setting is MatchLocalNames -> True. With the default setting, Trace[expr, x = rhs] will show
assignments to local variables whose names are of the form x$nnn.
Trace[expr, x = rhs, MatchLocalNames->False] shows assignments only for the global symbol x. See
page 365. New in Version 2.
MatchQ
MatchQ[expr, form] returns True if the pattern form matches expr, and returns False
otherwise.
See page 268.
New in Version 1.
MathieuC
MathieuC[a, q, z] gives the even Mathieu function with characteristic value a and
parameter q.
Mathematical function (see Section A.3.10). The Mathieu functions satisfy the equation y$$ a q coszy .
See page 789. See also: MathieuCPrime . New in Version 3.
MathieuCharacteristicA
MathieuCharacteristicA[r, q] gives the characteristic value ar for even Mathieu functions
with characteristic exponent r and parameter q.
Mathematical function (see Section A.3.10). The characteristic value ar gives the value of the parameter a in
y$$ a q coszy for which the solution has the form eirz fz where fz is an even function of z with period
. See page 789. See also: MathieuCharacteristicB . New in Version 3.
MathieuCharacteristicB
MathieuCharacteristicB[r, q] gives the characteristic value br for odd Mathieu functions
with characteristic exponent r and parameter q.
Mathematical function (see Section A.3.10). The characteristic value br gives the value of the parameter a in
y$$ a q coszy for which the solution has the form eirz fz where fz is an odd function of z with period
. When r is not a real integer, MathieuCharacteristicB gives the same results as MathieuCharacteristicA .
See notes for MathieuCharacteristicA . See page 789. New in Version 3.
MathieuCharacteristicExponent MatrixForm
1207
MathieuCharacteristicExponent
MathieuCharacteristicExponent[a, q] gives the characteristic exponent r for Mathieu
functions with characteristic value a and parameter q.
Mathematical function (see Section A.3.10). All Mathieu functions have the form eirz fz where fz has period
and r is the Mathieu characteristic exponent. See page 789. New in Version 3.
MathieuCPrime
MathieuCPrime[a, q, z] gives the derivative with respect to z of the even Mathieu function
with characteristic value a and parameter q.
Mathematical function (see Section A.3.10).
New in Version 3.
MathieuS
MathieuS[a, q, z] gives the odd Mathieu function with characteristic value a and
parameter q.
Mathematical function (see Section A.3.10).
See page 789. New in Version 3.
MathieuSPrime
MathieuSPrime[a, q, z] gives the derivative with respect to z of the odd Mathieu function
with characteristic value a and parameter q.
Mathematical function (see Section A.3.10).
,
New in Version 3.
MathMLForm
MathMLForm[expr] prints as a MathML form of expr.
MathMLForm gives presentation MathML, although its output can normally be interpreted by Mathematica.
MathMLForm[expr] gives MathML for the TraditionalForm of expr. MathMLForm[StandardForm[expr]] gives
MathML for the StandardForm of expr. MathMLForm acts as a wrapper, which affects printing, but not
evaluation. MathMLForm gives special characters using HTML aliases. See pages 211 and 425. See also:
HTMLSave, Export, TeXForm, Import. New in Version 4.1.
MatrixExp
MatrixExp[mat] gives the matrix exponential of mat.
MatrixExp[mat] effectively evaluates the power series for the exponential function, with ordinary powers replaced
by matrix powers. MatrixExp works only on square matrices. See page 906. Implementation notes: see
page 1069. See also: MatrixPower, Dot, JordanDecomposition , QRDecomposition . New in Version 2.
-
MatrixForm
MatrixForm[list] prints with the elements of list arranged in a regular array.
In StandardForm the array is shown enclosed in parentheses. MatrixForm prints a single-level list in a column. It
prints a two-level list in standard matrix form. More deeply nested lists are by default printed with successive
dimensions alternating between rows and columns. Elements in each column are by default centered.
, MatrixForm prints SparseArray objects like the corresponding ordinary lists.
MatrixForm takes the same set
of options as TableForm. MatrixForm acts as a wrapper, which affects printing, but not evaluation. See
page 439. See also: TableForm, ColumnForm, GridBox, GraphicsArray . New in Version 1; modified in Version 5.0.
MatrixPower MaxBend
1208
MatrixPower
MatrixPower[mat, n] gives the nth matrix power of mat.
MatrixPower[mat, n] effectively evaluates the product of a matrix with itself n times. When n is negative,
MatrixPower finds powers of the inverse of mat. MatrixPower works only on square matrices. , MatrixPower
can be used on SparseArray objects. See page 906. See also: Dot, MatrixExp. New in Version 2.
MatrixQ
MatrixQ[expr] gives True if expr is a list of lists or a two-dimensional SparseArray object
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.
MatrixQ[expr] gives True only if expr is a list, and each of its elements is a list of the same length, containing
no elements that are themselves lists, or is a two-dimensional SparseArray object. MatrixQ[expr, NumberQ] tests
whether expr is a numerical matrix. See pages 267 and 900. See also: VectorQ, ArrayQ, ArrayDepth. Related
package: LinearAlgebra`MatrixManipulation` . New in Version 1; modified in Version 2.
MatrixRank
MatrixRank[m] gives the rank of the matrix m.
MatrixRank works on both numerical and symbolic matrices. The rank of a matrix is the number of linearly
independent rows or columns. MatrixRank[m, Modulus->n] finds the rank for integer matrices modulo n.
MatrixRank[m, ZeroTest -> test] evaluates test[ m[[i, j]] ] to determine whether matrix elements are zero.
The default setting is ZeroTest -> Automatic. MatrixRank[m, Tolerance -> t] gives the minimum rank with
each element in a numerical matrix assumed to be correct only to within tolerance t. See page 907.
Implementation notes: see page 1069. See also: NullSpace, Det, Eigensystem, RowReduce, SingularValueList .
New in Version 5.0.
Max
Max[x , x , ... ] yields the numerically largest of the xi .
Max[{x , x , ... }, {y , ... }, ... ] yields the largest element of any of the lists.
Max yields a definite result if all its arguments are real numbers. In other cases, Max carries out some
simplifications. Max[ ] gives -Infinity. , Max works on SparseArray objects. See page 745. See also: Min,
Ordering, Maximize, FindMaximum. New in Version 1.
MaxBend
MaxBend is an option for Plot which measures the maximum bend angle between successive
line segments on a curve.
Plot uses an adaptive algorithm to try and include enough sample points so that there are no bends larger than
MaxBend between successive segments of the plot. Plot will not, however, subdivide by a factor of more than
PlotDivision. Smaller settings for MaxBend will lead to smoother curves, based on more sample points. See
page 138. New in Version 1.
Maximize MeijerG
1209
Maximize
Maximize[f, {x, y, ... }] maximizes f with respect to x, y, ... .
Maximize[{f, cons}, {x, y, ... }] maximizes f subject to the constraints cons.
Maximize returns a list of the form {fmax , {x -> xmax , y -> ymax , . . . }}. cons can contain equations, inequalities
or logical combinations of these. If f and cons are linear or polynomial, Maximize will always find a global
maximum. Maximize will return exact results if given exact input. If the maximum is achieved only
infinitesimally outside the region defined by the constraints, or only asymptotically, Maximize will return the
supremum and the closest specifiable point. By default, all variables are assumed to be real. x Integers can
be used to specify that a variable can take on only integer values. If the constraints cannot be satisfied, Maximize
returns {-Infinity, {x -> Indeterminate, . . . }}. See page 850. Implementation notes: see page 1070. See
also: Minimize, NMaximize, FindMaximum, Max, D, LinearProgramming . New in Version 5.0.
MaxMemoryUsed
MaxMemoryUsed[ ] gives the maximum number of bytes used to store all data for the current
Mathematica session.
On most computer systems, MaxMemoryUsed[ ] will give results close to those obtained from external process status
requests. MaxMemoryUsed[ ] will not typically account for code space, stack space or the effects of heap
fragmentation. See page 712. See also: MemoryInUse, ByteCount. New in Version 1.
,
Mean
Mean[list] gives the statistical mean of the elements in list.
Mean[list] is equivalent to Total[list]/Length[list] . Mean handles both numerical and symbolic data.
Mean[{{x , y , . . . }, {x , y , . . . }, . . . }] gives {Mean[{x , x , . . . }], Mean[{y , y , . . . }]}. Mean works
with SparseArray objects. See pages 794 and 924. See also: Total, StandardDeviation , Variance, Median.
Related packages: Statistics`DescriptiveStatistics` , Statistics`MultiDescriptiveStatistics` . New in
Version 5.0.
Median
Median[list] gives the median of the elements in list.
Median[list] gives the center element in the sorted version of list, or the average of the two center elements if list
is of even length. Median[{{x , y , . . . }, {x , y , . . . }, . . . }] gives
{Median[{x , x , . . . }], Median[{y , y , . . . }]}. Median works with SparseArray objects. See page 924.
See also: Mean, Quantile, Sort, Max, Ordering. Related packages: Statistics`DescriptiveStatistics` ,
Statistics`MultiDescriptiveStatistics` . New in Version 5.0.
MeijerG
MeijerG[{{a , ... , an }, {an , ... , ap }}, {{b , ... , bm }, {bm , ... , bq }}, z] is the Meijer
a a
p
G function Gmn
pq z b b .
Mathematical function (see Section A.3.10). The generalized form MeijerG[alist, blist, z, r] is defined for real r by
ri e a rs an rsb rs bm rsfean rs ap rs bm rs bq rsfzs ds,
where in the default case r . In many special cases, MeijerG is automatically converted to other functions.
See page 780. See also: HypergeometricPFQ . New in Version 3.
MemberQ MeshStyle
1210
MemberQ
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.
form can be a pattern. Example: MemberQ[{x^2, y^2}, x^_] # True . The first argument of MemberQ can have
any head, not necessarily List. MemberQ[list, form] immediately tests whether any expression in list matches
form; Element[x, dom] asserts that x is an element of the symbolic domain dom. See page 268. See also: FreeQ,
Element, Count, Cases, IntervalMemberQ. New in Version 1.
MemoryConstrained
MemoryConstrained[expr, b] evaluates expr, stopping if more than b bytes of memory are
requested.
MemoryConstrained[expr, b, failexpr] returns failexpr if the memory constraint is not met.
MemoryConstrained generates an interrupt to stop the evaluation of expr if the amount of additional memory
requested during the evaluation of expr exceeds b bytes. MemoryConstrained evaluates failexpr only if the
evaluation is aborted. MemoryConstrained returns $Aborted if the evaluation is aborted and no failexpr is
specified. Aborts generated by MemoryConstrained are treated just like those generated by Abort, and can thus
be overruled by AbortProtect. See page 713. See also: TimeConstrained , MaxMemoryUsed , $RecursionLimit ,
Abort. New in Version 1.
MemoryInUse
MemoryInUse[ ] gives the number of bytes currently being used to store all data in the current
Mathematica session.
See page 712. See also: MaxMemoryUsed , ByteCount, Share.
New in Version 1.
Mesh
Mesh is an option for SurfaceGraphics and DensityGraphics that specifies whether an
explicit xy mesh should be drawn.
See page 539.
New in Version 1.
MeshRange
MeshRange is an option for ListPlot3D , SurfaceGraphics , ListContourPlot ,
ListDensityPlot and related functions which specifies the range of x and y coordinates that
correspond to the array of z values given.
MeshRange->{{xmin, xmax}, {ymin, ymax}} specifies ranges in x and y. Mesh lines are taken to be equally
spaced. MeshRange->Automatic takes x and y to be a grid of integers determined by indices in the array.
Settings for MeshRange are produced automatically by Plot3D, etc. for insertion into SurfaceGraphics etc.
MeshRange is used to determine tick values for surface, contour and density plots. See page 539. See also:
PlotRange, PlotPoints. New in Version 2.
MeshStyle
MeshStyle is an option for Plot3D, DensityPlot and related functions which specifies how
mesh lines should be rendered.
MeshStyle can be set to a list of graphics directives including Dashing, Thickness, GrayLevel, Hue and RGBColor.
See pages 503 and 539. See also: Mesh, AxesStyle, Prolog, Epilog, DisplayFunction. New in Version 2.
Message Messages
1211
Message
Message[symbol::tag] prints the message symbol::tag unless it has been switched off.
Message[symbol::tag, e , e , ... ] prints a message, inserting the values of the ei as needed.
Message generates output on the channel $Messages. You can switch off a message using Off[symbol::tag] . You
can switch on a message using On[symbol::tag]. Between any two successive input lines, Mathematica prints a
message with a particular name at most three times. On the last occurrence, it prints the message General::stop .
During the evaluation of a particular input line, names of messages associated with that input line are appended
to the list $MessageList, wrapped with HoldForm. At the end of the evaluation of the nth input line, the value of
$MessageList is assigned to MessageList[n] . Message[mname, e , e , . . . ] is printed as
StringForm[mess, e , e , . . . ] where mess is the value of the message mname. Entries of the form `i` in the string
mess are replaced by the corresponding ei . Given a message specified as symbol::tag, Message first searches for
messages symbol::tag::lang i for each of the languages in the list $Language. If it finds none of these, it then
searches for the actual message symbol::tag. If it does not find this, it then performs the same search procedure for
General::tag. If it still finds no message, it applies any value given for the global variable $NewMessage to symbol
and "tag". If you specify a message as symbol::tag::lang, then Message will search only for messages with the
particular language lang. See page 482. See also: Print, CellPrint, Write, On, Off, Check, MessageList. New
in Version 1.
MessageList
MessageList[n] is a global object assigned to be a list of the names of messages generated
during the processing of the nth input line.
Only messages that are actually output are included in the list MessageList[n]. The message names in the list
are wrapped with HoldForm. MessageList[n] includes messages generated both by built-in functions and by
explicit invocations of Message. See pages 481 and 702. See also: $MessageList. New in Version 2.
MessageName
symbol::tag is a name for a message.
You can specify messages by defining values for symbol::tag. symbol::tag is converted to
MessageName[symbol, "tag"]. tag can contain any characters that can appear in symbol names. symbol::"tag" can
also be used. Assignments for s::tag are stored in the Messages value of the symbol s. The following messages
are typically defined for built-in functions:
f::template
f::usage
?f prints out the message f::usage. When ?form finds more than one function, only the names of each function
are printed. You can switch on and off messages using On[s::tag] and Off[s::tag].
MessageName[symbol, "tag", "lang"] or symbol::tag::lang represents a message in a particular language. See
page 479. See also: Message, MessageList, $MessageList. New in Version 1; modified in Version 4.
Messages
Messages[symbol] gives all the messages assigned to a particular symbol.
Messages that have been switched off using Off are enclosed in $Off.
New in Version 1.
Min Minus
1212
Min
Min[x , x , ... ] yields the numerically smallest of the xi .
Min[{x , x , ... }, {y , ... }, ... ] yields the smallest element of any of the lists.
Min yields a definite result if all its arguments are real numbers. In other cases, Min carries out some
simplifications. Min[ ] gives Infinity. , Min works on SparseArray objects. See page 745. See also: Max,
Ordering, Minimize, FindMinimum. New in Version 1.
,
Minimize
Minimize[f, {x, y, ... }] minimizes f with respect to x, y, ... .
Minimize[{f, cons}, {x, y, ... }] minimizes f subject to the constraints cons.
Minimize returns a list of the form {fmin , {x -> xmin , y -> ymin , . . . }}. cons can contain equations, inequalities
or logical combinations of these. If f and cons are linear or polynomial, Minimize will always find a global
minimum. Minimize will return exact results if given exact input. If the minimum is achieved only
infinitesimally outside the region defined by the constraints, or only asymptotically, Minimize will return the
infimum and the closest specifiable point. By default, all variables are assumed to be real. x Integers can be
used to specify that a variable can take on only integer values. If the constraints cannot be satisfied, Minimize
returns {+Infinity, {x -> Indeterminate, . . . }}. Even if the same minimum is achieved at several points, only
one is returned. See page 850. Implementation notes: see page 1070. See also: Maximize, NMinimize,
FindMinimum, Min, D, FindInstance, LinearProgramming . New in Version 5.0.
Minors
Minors[m] gives the minors of a matrix m.
Minors[m, k] gives kth minors.
For an n n matrix the i jth element of Minors[m] gives the determinant of the matrix obtained by deleting the
n i th row and the n j th column of m. Map[Reverse, Minors[m], {0,1}] makes the i jth element
correspond to deleting the ith row and jth column of m. Minors[m] is equivalent to Minors[m, n-1].
Minors[m, k] gives the determinants of the k k submatrices obtained by picking each possible set of k rows and
k columns from m. Each element in the result corresponds to taking rows and columns with particular lists of
positions. The ordering of the elements is such that reading across or down the final matrix the successive lists of
n
n
positions appear in lexicographic order. For an n n matrix Minors[m, k] gives a k k matrix.
Minors[m, k, f] applies the function f rather than Det to each of the submatrices picked out. See page 905.
See also: Det, Delete. New in Version 1; modified in Version 4.
Minus
-x is the arithmetic negation of x.
-x is converted to Times[-1, x] on input.
New in Version 1.
Mod Modulus
1213
Mod
Mod[m, n] gives the remainder on division of m by n.
Mod[m, n, d] uses an offset d.
For integers m and n Mod[m, n] lies between 0 and n . Mod[m, n, 1] gives a result in the range to n,
suitable for use in functions such as Part. Mod[m, n, d] gives a result x such that d * x ) d n and
x mod n m mod n. The sign of Mod[m, n] is always the same as the sign of n, at least so long as m and n are
both real. Mod[m, n] is equivalent to m - n Quotient[m, n]. Mod[m, n, d] is equivalent to
m - n Quotient[m, n, d]. The arguments of Mod can be any numeric quantities, not necessarily integers.
Mod[x, 1] gives the fractional part of x. For exact numeric quantities, Mod internally uses numerical
approximations to establish its result. This process can be affected by the setting of the global variable
$MaxExtraPrecision . See page 749. See also: PowerMod, Quotient, FractionalPart , MantissaExponent ,
PolynomialMod, PolynomialRemainder , Xor. New in Version 1; modified in Version 4.
ModularLambda
ModularLambda[] gives the modular lambda elliptic function .
Mathematical function (see Section A.3.10). ModularLambda is defined only in the upper half of the complex
plane. It is not defined for real . The argument is the ratio of Weierstrass half-periods $ . ModularLambda
gives the parameter m for elliptic functions in terms of according to m . ModularLambda is related to
EllipticTheta by i
qi
q where the nome q is given by ei . is invariant under any
combination of the modular transformations # and # . See page 782 for a discussion of
argument conventions for elliptic functions. See page 787. See also: DedekindEta, KleinInvariantJ ,
WeierstrassHalfPeriods . New in Version 3.
Module
Module[{x, y, ... }, expr] specifies that occurrences of the symbols x, y, ... in expr should be
treated as local.
Module[{x = x , ... }, expr] defines initial values for x, ... .
Module allows you to set up local variables with names that are local to the module. Module creates new symbols
to represent each of its local variables every time it is called. Module creates a symbol with name xxx$nnn to
represent a local variable with name xxx. The number nnn is the current value of $ModuleNumber. The value of
$ModuleNumber is incremented every time any module is used. Before evaluating expr, Module substitutes new
symbols for each of the local variables that appear anywhere in expr except as local variables in scoping constructs.
Symbols created by Module carry the attribute Temporary. Symbols created by Module can be returned from
modules. You can use Module[{vars}, body /; cond] as the right-hand side of a transformation rule with a
condition attached. Module has attribute HoldAll. Module is a scoping construct (see Section A.3.8). Module
constructs can be nested in any way. Module implements lexical scoping. See page 378. See also: With, Block,
Unique, GeneratedParameters . New in Version 2.
Modulus
Modulus->n is an option that can be given in certain algebraic functions to specify that
integers should be treated modulo n.
Equations for Modulus can be given in Solve and related functions.
Modulus appears as an option in Factor, PolynomialGCD and PolynomialLCM, as well as in linear algebra functions
such as Inverse, LinearSolve and Det. Arithmetic is usually done over the full ring of integers; setting the
option Modulus specifies that arithmetic should instead be done in the finite ring n . The setting Modulus -> 0
specifies the full ring of integers. Some functions require that Modulus be set to a prime, or a power of a
prime. n is a finite field when n is prime. See page 809. See also: Extension. New in Version 1.
MoebiusMu N
1214
MoebiusMu
MoebiusMu[n] gives the Mobius
function n.
Integer mathematical function (see Section A.3.10). n is if n is a product of an even number of distinct
primes, if it is a product of an odd number of primes, and if it has a multiple prime factor. See page 752.
See also: Divisors, FactorInteger, JacobiSymbol. New in Version 1.
,
Most
Most[expr] gives expr with the last element removed.
Example: Most[{a, b, c}] # a, b . Most[expr] is equivalent to Drop[expr, -1].
Rest, Drop, Last, Part, Take. New in Version 5.0.
See also:
Multinomial
Multinomial[n , n , ... ] gives the multinomial coefficient n n dndn d .
Integer mathematical function (see Section A.3.10). The multinomial coefficient Multinomial[n , n , . . . ],
denoted Ng n n nm , gives the number of ways of partitioning N distinct objects into m sets, each of size ni
(with N m
See page 757. See also: Binomial. New in Version 1.
i ni ).
MultiplicativeOrder
MultiplicativeOrder[k, n] gives the multiplicative order of k modulo n, defined as the
smallest integer m such that km Q mod n.
MultiplicativeOrder[k, n, {r , r , ... }] gives the generalized multiplicative order of k
modulo n, defined as the smallest integer m such that km Q ri mod n for some i.
Integer mathematical function (see Section A.3.10). MultiplicativeOrder returns unevaluated if there is no
integer m satisfying the necessary conditions. See page 752. See also: EulerPhi, PowerMod, CarmichaelLambda,
RealDigits. New in Version 4.
N
N[expr] gives the numerical value of expr.
N[expr, n] attempts to give a result with n-digit precision.
Unless numbers in expr are exact, or of sufficiently high precision, N[expr, n] may not be able to give results with
n-digit precision. N[expr, n] may internally do computations to more than n digits of precision.
$MaxExtraPrecision specifies the maximum number of extra digits of precision that will ever be used internally.
The precision n is given in decimal digits; it need not be an integer. n must lie between $MinPrecision and
$MaxPrecision. $MaxPrecision can be set to Infinity. , n can be smaller than $MachinePrecision . N[expr]
gives a machine-precision number, so long as its magnitude is between $MinMachineNumber and
$MaxMachineNumber . , N[expr] is equivalent to N[expr, MachinePrecision] . N[0] gives the number 0. with
machine precision. N converts all non-zero numbers to Real or Complex form. N converts each successive
argument of any function it encounters to numerical form, unless the head of the function has an attribute such as
NHoldAll. You can define numerical values of functions using N[f [args]] := value and N[f [args], n] := value.
, N[expr, {p, a}] attempts to generate a result with precision at most p and accuracy at most a.
, N[expr, {Infinity, a}] attempts to generate a result with accuracy a. , N[expr, {Infinity, 1}] attempts to
find a numerical approximation to the integer part of expr. See pages 30, 33, 728 and 735. Implementation notes:
see page 1067. See also: Chop, CompiledFunction , Rationalize, MachinePrecision , NHoldAll, RealDigits.
New in Version 1; modified in Version 5.0.
NameQ NDSolve
1215
NameQ
NameQ["string"] yields True if there are any symbols whose names match the string pattern
given, and yields False otherwise.
You can test for classes of symbol names using string patterns with metacharacters such as *, as specified on
page 1044. See page 403. See also: Names. New in Version 1.
Names
Names["string"] gives a list of the names of symbols which match the string.
Names["string", SpellingCorrection->True] includes names which match after spelling
correction.
Names["string"] gives the same list of names as ?string. Names returns a list of strings corresponding to the
names of symbols. The string can be a string pattern, with metacharacters such as * and @, as described on
page 1044. Names["context`*"] lists all symbols in the specified context. With SpellingCorrection -> True,
Names includes names which differ in a small fraction of their characters from those specifically requested. With
IgnoreCase -> True or SpellingCorrection -> True, Names treats lower- and upper-case letters as equivalent
when matching names. Names[ ] lists all names in all contexts. See page 403. See also: Information,
Contexts, Unique, ValueQ, FileNames, NameQ. New in Version 1.
,
Nand
Nand[e , e , ... ] is the logical NAND function. It evaluates its arguments in order, giving
True immediately if any of them are False, and False if they are all True.
Nand[e , e , . . . ] can be input in StandardForm and InputForm as e e . . . . The character can be entered
as , nand , or \[Nand]. Nand[e , e , . . . ] is equivalent to Not[And[e , e , . . . ]]. Nand evaluates its arguments
in a non-standard way (see page 1046). Nand gives symbolic results when necessary, removing initial arguments
that are True. Nand is not Flat. See page 87. See also: LogicalExpand, And. New in Version 4.1.
NDSolve
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, {y , y , ... }, {x, xmin, xmax}] finds numerical solutions for the
functions yi .
NDSolve gives results in terms of InterpolatingFunction objects. NDSolve[eqns, y[x], {x, xmin, xmax}] gives
solutions for y[x] rather than for the function y itself. Differential equations must be stated in terms of derivatives
such as y'[x], obtained with D, not total derivatives obtained with Dt. NDSolve solves a wide range of ordinary
differential equations as well as many partial differential equations. In ordinary differential equations the functions
yi must depend only on the single variable x. In partial differential equations they may depend on more than one
variable. The differential equations must contain enough initial or boundary conditions to determine the solutions
for the yi completely. Initial and boundary conditions are typically stated in form y[x ] == c , y'[x ] == dc , etc.,
but may consist of more complicated equations. , The c , dc , etc. can be lists, specifying that y[x] is a function
with vector or general list values. , Periodic boundary conditions can be specified using y[x ] == y[x ]. The
point x that appears in the initial or boundary conditions need not lie in the range xmin to xmax over which the
solution is sought. The differential equations in NDSolve can involve complex numbers. , NDSolve can solve
many differential-algebraic equations, in which some of the eqns are purely algebraic, or some of the variables are
implicitly algebraic. , The yi can be functions of the dependent variables, and need not include all such variables.
(continued)
1216
NDSolve
-
(continued)
AccuracyGoal
Compiled
DependentVariables
EvaluationMonitor
MaxStepFraction
MaxSteps
MaxStepSize
Method
NormFunction
PrecisionGoal
StartingStepSize
StepMonitor
WorkingPrecision
Automatic
True
Automatic
None
1/10
10000
Infinity
Automatic
Automatic
Automatic
Automatic
None
MachinePrecision
NDSolve adapts its step size so that the estimated error in the solution is just within the tolerances specified by
PrecisionGoal and AccuracyGoal . , The option NormFunction -> f specifies that the estimated errors for each of
the yi should be combined using f[{e , e , . . . }]. - AccuracyGoal effectively specifies the absolute local error
allowed at each step in finding a solution, while PrecisionGoal specifies the relative local error. If solutions
must be followed accurately when their values are close to zero, AccuracyGoal should be set larger, or to
Infinity. - The default setting of Automatic for AccuracyGoal and PrecisionGoal is equivalent to
WorkingPrecision/2 . , The setting for MaxStepFraction specifies the maximum step to be taken by NDSolve as
a fraction of the range of values for each independent variable. , With DependentVariables->Automatic ,
NDSolve attempts to determine the dependent variables by analyzing the equations given. , Possible explicit
settings for the Method option include:
,
"Adams"
"BDF"
"ExplicitRungeKutta"
"ImplicitRungeKutta"
"SymplecticPartitionedRungeKutta"
"ExplicitEuler"
"ExplicitMidpoint"
"ExplicitModifiedMidpoint"
"LinearlyImplicitEuler"
"LinearlyImplicitMidpoint"
"LinearlyImplicitModifiedMidpoint"
"LocallyExact"
See page 961.
in Version 5.0.
Needs NestWhile
1217
Needs
Needs["context`"] loads an appropriate file if the specified context is not already in
$Packages .
Needs["context`", "file"] loads file if the specified context is not already in $Packages .
Needs["context`"] calls Get["context`"]. By convention, the file loaded in this way is the one which contains a
package that defines context`. Example: Needs["Collatz`"] typically reads in a file named Collatz.m. See
page 400. See also: Get, DeclarePackage , FileNames. Related package: Utilities`Package` . New in
Version 1.
Negative
Negative[x] gives True if x is a negative number.
Negative[x] gives False if x is manifestly a non-negative or complex numerical quantity. Otherwise, it remains
unevaluated. See also: NonNegative, Positive, Sign, Less, Simplify, Assumptions. New in Version 1.
Nest
Nest[f, expr, n] gives an expression with f applied n times to expr.
Example: Nest[f, x, 3] # f
f
f
x . You can use Throw to exit from Nest before it is finished. See
page 241. See also: NestList, NestWhile, Fold, Function, FixedPoint, Do. New in Version 1; modified in
Version 3.
NestList
NestList[f, expr, n] gives a list of the results of applying f to expr 0 through n times.
Example: NestList[f, x, 3] # x, f
x, f
f
x, f
f
f
x . NestList[f, expr, n] gives a list of length
n + 1. See page 241. See also: Nest, NestWhileList, FoldList, ComposeList. New in Version 1.
NestWhile
NestWhile[f, expr, test] starts with expr, then repeatedly applies f until applying test to the
result no longer yields True.
NestWhile[f, expr, test, m] supplies the most recent m results as arguments for test at each
step.
NestWhile[f, expr, test, All] supplies all results so far as arguments for test at each step.
NestWhile[f, expr, test, m, max] applies f at most max times.
NestWhile[f, expr, test, m, max, n] applies f an extra n times.
NestWhile[f, expr, test, m, max, -n] returns the result found when f had been applied n
fewer times.
NestWhile[f, expr, test] returns the first expression f[f[. . . f[expr]. . . ]] to which applying test does not yield True.
If test[expr] does not yield True, NestWhile[f, expr, test] returns expr. NestWhile[f, expr, test, m] at each
step evaluates test[res , res , . . . , resm ]. It does not put the results resi in a list. The resi are given in the order
they are generated, with the most recent coming last. NestWhile[f, expr, test, m] does not start applying test
until at least m results have been generated. NestWhile[f, expr, test, {mmin, m}] does not start applying test
until at least mmin results have been generated. At each step it then supplies as arguments to test as many recent
results as possible, up to a maximum of m. NestWhile[f, expr, test, m] is equivalent to
NestWhile[f, expr, test, {m, m}]. NestWhile[f, expr, UnsameQ, 2] is equivalent to FixedPoint[f, expr].
(continued)
1218
NestWhile
(continued)
NestWhile[f, expr, test, All] is equivalent to NestWhile[f, expr, test, {1, Infinity}].
NestWhile[f, expr, UnsameQ, All] goes on applying f until the same result first appears more than once.
NestWhile[f, expr, test, m, max, n] applies f an additional n times after test fails, or max applications have
already been performed. NestWhile[f, expr, test, m, max, -n] is equivalent to
Part[NestWhileList[f, expr, test, m, max], -n-1]. NestWhile[f, expr, test, m, Infinity, -1] returns, if
possible, the last expression in the sequence expr, f[expr], f[f[expr]], . . . for which test yields True. See page 242.
See also: NestWhileList, FixedPoint, Nest, While. New in Version 4.
NestWhileList
NestWhileList[f, expr, test] generates a list of the results of applying f repeatedly, starting
with expr, and continuing until applying test to the result no longer yields True.
NestWhileList[f, expr, test, m] supplies the most recent m results as arguments for test at
each step.
NestWhileList[f, expr, test, All] supplies all results so far as arguments for test at each step.
NestWhileList[f, expr, test, m, max] applies f at most max times.
The last element of the list returned by NestWhileList[f, expr, test] is always an expression to which applying
test does not yield True. NestWhileList[f, expr, test, m] at each step evaluates test[res , res , . . . , resm ]. It
does not put the results resi in a list. The resi are given in the order they are generated, with the most recent
coming last. NestWhileList[f, expr, test, m] does not start applying test until at least m results have been
generated. NestWhileList[f, expr, test, {mmin, m}] does not start applying test until at least mmin results have
been generated. At each step it then supplies as arguments to test as many recent results as possible, up to a
maximum of m. NestWhileList[f, expr, test, m] is equivalent to NestWhileList[f, expr, test, {m, m}].
NestWhileList[f, expr, UnsameQ, 2] is equivalent to FixedPointList[f, expr].
NestWhileList[f, expr, test, All] is equivalent to NestWhileList[f, expr, test, {1, Infinity}].
NestWhileList[f, expr, UnsameQ, All] goes on applying f until the same result first appears more than once.
NestWhileList[f, expr, test, m, max, n] applies f an extra n times, appending the results to the list generated.
NestWhileList[f, expr, test, m, max, -n] drops the last n elements from the list generated. See page 242.
See also: NestWhile, FixedPointList , NestList, While. New in Version 4.
NHoldAll
NHoldAll is an attribute which specifies that none of the arguments to a function should be
affected by N.
NHoldAll, NHoldFirst and NHoldRest are useful in ensuring that arguments to functions are maintained as exact
integers, rather than being converted by N to approximate numbers. See page 329. See also: NumericFunction,
HoldAll. New in Version 3.
NHoldFirst
NHoldFirst is an attribute which specifies that the first argument to a function should not be
affected by N.
See page 329.
New in Version 3.
NHoldRest NMaximize
1219
NHoldRest
NHoldRest is an attribute which specifies that all but the first argument to a function should
not be affected by N.
See page 329.
-
New in Version 3.
NIntegrate
xmax
NIntegrate[f, {x, xmin, xmax}] gives a numerical approximation to the integral xmin f dx.
Multidimensional integrals can be specified, as in Integrate. NIntegrate tests for singularities at the end points
of the integration range. NIntegrate[f, {x, x , x , . . . , xk }] tests for singularities at each of the intermediate
points xi . If there are no singularities, the result is equivalent to an integral from x to xk . You can use complex
numbers xi to specify an integration contour in the complex plane. - The following options can be given:
AccuracyGoal
Compiled
GaussPoints
EvaluationMonitor
MaxPoints
MaxRecursion
Method
MinRecursion
PrecisionGoal
SingularityDepth
WorkingPrecision
Infinity
True
Automatic
None
Automatic
6
Automatic
0
Automatic
4
MachinePrecision
NIntegrate usually uses an adaptive algorithm, which recursively subdivides the integration region as needed. In
one dimension, GaussPoints specifies the number of initial points to choose. The default setting for GaussPoints is
Floor[WorkingPrecision/3] . In any number of dimensions, MinRecursion specifies the minimum number of
recursive subdivisions to try. MaxRecursion gives the maximum number. NIntegrate usually continues doing
subdivisions until the error estimate it gets implies that the final result achieves either the AccuracyGoal or the
PrecisionGoal specified. The default setting for PrecisionGoal is usually equal to the setting for
WorkingPrecision minus 10 digits. If an explicit setting for MaxPoints is given, NIntegrate uses quasi Monte
Carlo methods to get an estimate of the result, sampling at most the number of points specified. The default
setting for PrecisionGoal is taken to be 2 in this case. You should realize that with sufficiently pathological
functions, the algorithms used by NIntegrate can give wrong answers. In most cases, you can test the answer by
looking at its sensitivity to changes in the setting of options for NIntegrate. N[Integrate[ . . . ]] calls
NIntegrate for integrals that cannot be done symbolically. NIntegrate has attribute HoldAll. Possible settings
for Method are GaussKronrod, DoubleExponential , Trapezoidal, Oscillatory, MultiDimensional , MonteCarlo,
and QuasiMonteCarlo . GaussKronrod and MultiDimensional are adaptive methods. MonteCarlo and
QuasiMonteCarlo are randomized methods, appropriate for high-dimensional integrals. See page 954.
Implementation notes: see page 1068. See also: NDSolve, NSum. Related packages:
NumericalMath`ListIntegrate` , NumericalMath`CauchyPrincipalValue` , NumericalMath`GaussianQuadrature` .
New in Version 1; modified in Version 5.0.
,
NMaximize
NMaximize[f, {x, y, ... }] maximizes f numerically with respect to x, y, ... .
NMaximize[{f, cons}, {x, y, ... }] maximizes f numerically subject to the constraints cons.
See notes for NMinimize.
NMinimize NonNegative
1220
NMinimize
NMinimize[f, {x, y, ... }] minimizes f numerically with respect to x, y, ... .
NMinimize[{f, cons}, {x, y, ... }] minimizes f numerically subject to the constraints cons.
NMinimize returns a list of the form {fmin , {x -> xmin , y -> ymin , . . . }}. cons can contain equations, inequalities
or logical combinations of these. NMinimize always attempts to find a global minimum of f subject to the
constraints given. Unless f and cons are both linear, NMinimize may sometimes find only a local minimum. By
default, all variables are assumed to be real. x Integers can be used to specify that a variable can take on
only integer values. If NMinimize determines that the constraints cannot be satisfied, it returns
{Infinity, {x -> Indeterminate, . . . }}. The following options can be given:
AccuracyGoal
EvaluationMonitor
MaxIterations
Method
PrecisionGoal
StepMonitor
WorkingPrecision
Automatic
None
100
Automatic
Automatic
None
MachinePrecision
The default settings for AccuracyGoal and PrecisionGoal are WorkingPrecision/2 . The settings for
AccuracyGoal and PrecisionGoal specify the number of digits to seek in both the value of the position of the
maximum, and the value of the function at the minimum. NMinimize continues until either of the goals specified
by AccuracyGoal or PrecisionGoal is achieved. Possible settings for the Method option include "NelderMead",
"DifferentialEvolution" , "SimulatedAnnealing" and "RandomSearch" . See page 974. Implementation notes:
see page 1068. See also: NMaximize, Minimize, FindMinimum, FindFit. New in Version 5.0.
NonCommutativeMultiply
a ** b ** c is a general associative, but non-commutative, form of multiplication.
NonCommutativeMultiply has attribute Flat. Instances of NonCommutativeMultiply are automatically flattened,
but no other simplification is performed. You can use NonCommutativeMultiply as a generalization of ordinary
multiplication for special mathematical objects. See page 1026. See also: Dot, Times, Cross. New in Version 1.
NonConstants
NonConstants is an option for D which gives a list of objects to be taken to depend implicitly
on the differentiation variables.
If c does not appear in the list of NonConstants, then D[c, x] is taken to be 0 unless c and x are identical
expressions. See page 853. See also: Dt. New in Version 1.
None
None is a setting used for certain options.
See also: All, Automatic.
New in Version 1.
NonNegative
NonNegative[x] gives True if x is a non-negative number.
NonNegative[x] gives False if x is manifestly a negative or complex numerical quantity. Otherwise, it remains
unevaluated. See also: Negative, Positive, Sign, Greater, Simplify, Assumptions. New in Version 1.
NonPositive Notebook
1221
NonPositive
NonPositive[x] gives True if x is a non-positive number.
See notes for NonNegative.
,
New in Version 3.
Nor
Nor[e , e , ... ] is the logical NOR function. It evaluates its arguments in order, giving False
immediately if any of them are True, and True if they are all False.
Nor[e , e , . . . ] can be input in StandardForm and InputForm as e e . . . . The character can be entered as
, nor , or \[Nor]. Nor[e , e , . . . ] is equivalent to Not[Or[e , e , . . . ]]. Nor evaluates its arguments in a
non-standard way (see page 1046). Nor gives symbolic results when necessary, removing initial arguments that are
False. Nor is not Flat. See page 87. See also: LogicalExpand, Or, Xor. New in Version 4.1.
Norm
Norm[expr] gives the norm of a number or array.
Norm[expr, p] gives the p-norm.
For complex numbers, Norm[z] is Abs[z]. For vectors, Norm[v] is Sqrt[v . Conjugate[v]]. Norm[v, p] is
Total[Abs[v^p]]^(1/p) . Norm[v, Infinity] is the -norm given by Max[Abs[v]]. For matrices, Norm[m]
gives the maximum singular value of m. Norm can be used on SparseArray objects. See page 119. See also:
Abs, Dot, Total, SingularValueList , Integrate. New in Version 5.0.
Normal
Normal[expr] converts expr to a normal expression, from a variety of special forms.
Normal[expr] converts a power series to a normal expression by truncating higher-order terms. , Normal[expr]
converts SparseArray objects into ordinary arrays. Normal[expr] converts RootSum objects into explicit sums
involving Root objects. When additional data types are introduced, Normal should be defined to convert them,
when possible, to normal expressions. See page 888. See also: SeriesCoefficient . New in Version 1.0; modified
in Version 5.0.
Not
!expr is the logical NOT function. It gives False if expr is True, and True if it is False.
Not[expr] can be input in StandardForm and InputForm as expr. The character can be entered as , ! ,, , not , or
\[Not]. Not gives symbolic results when necessary, applying various simplification rules to them. If you are
using Mathematica with a text-based front end, then you cannot use the notation !expr for Not[expr] if it appears at
the very beginning of a line. In this case, !expr is interpreted as a shell escape. See page 87. See also:
LogicalExpand, BitNot, Nand, Nor. New in Version 1; modified in Version 3.
Notebook
Notebook[{cell , cell , ... }] represents a notebook that can be manipulated by the
Mathematica front end.
Notebook files contain
notebooks in the front
notebooks in the front
SetOptions to look at
explicit Notebook expressions written out in textual form. You can manipulate open
end using standard commands in the front end, and using the options inspector. Open
end are referred to in the kernel by NotebookObject constructs. You can use Options and
and modify options for open notebooks. See page 576. See also: Cell. New in Version 3.
NotebookApply NotebookDelete
1222
NotebookApply
NotebookApply[notebook, data] writes data into a notebook at the current selection, replacing
the first selection placeholder in data by the current selection, and then setting the current
selection to be just after the data written.
NotebookApply[notebook, data, sel] writes data into a notebook and then sets the current
selection to be as specified by sel.
The first argument of NotebookApply is a NotebookObject . NotebookApply does the same as NotebookWrite,
except that it replaces the first selection placeholder in data by the current selection. NotebookApply is often used
in setting up actions for buttons in palettes. Selection placeholders are represented by the character or
\[SelectionPlaceholder] . Possible settings for sel are as in NotebookWrite . See page 585. See also:
NotebookWrite, NotebookRead, SelectionMove , ButtonFunction . New in Version 3.
NotebookAutoSave
NotebookAutoSave is an option for Notebook which specifies whether the notebook should
automatically be saved after each piece of output generated by evaluation in it.
See page 618.
New in Version 3.
NotebookClose
NotebookClose[notebook] closes the notebook corresponding to the specified notebook object.
NotebookClose will make a notebook disappear from your screen, and will invalidate all notebook objects which
refer to that notebook. See page 591. See also: NotebookSave, Close. New in Version 3.
NotebookCreate
NotebookCreate[ ] creates a new open notebook in the front end.
NotebookCreate[options] sets up the specified options for the new notebook.
NotebookCreate will by default create a notebook with name "Untitled-n". Unless you set the option
Visible->False , NotebookCreate will cause a new window to appear on your screen. See page 591. See also:
NotebookOpen, NotebookClose. New in Version 3.
NotebookDelete
NotebookDelete[notebook] deletes the current selection corresponding to the specified
notebook object.
Using NotebookDelete in the kernel is equivalent to using the Clear command in the front end. After
NotebookDelete , the current selection becomes an insertion point at the position of the deleted material. notebook
must be a NotebookObject, as returned by NotebookOpen , etc. See page 585. See also: NotebookRead,
NotebookWrite. New in Version 3.
NotebookFind NotebookLocate
1223
NotebookFind
NotebookFind[notebook, data]
the next occurrence of data.
NotebookFind[notebook, data,
occurrence.
NotebookFind[notebook, data,
NotebookFind[notebook, data,
NotebookFind returns $Failed if the search it performs finds no occurrence of data. notebook must be a
NotebookObject, as returned by NotebookOpen, etc. data can be a string, box expressions, or a complete cell.
The possible elements are:
CellContents
CellLabel
CellStyle
CellTags
{elem , elem , . . . }
The default for elems is CellContents. Unless the option setting AutoScroll->False is given, the front end
will scroll a notebook so that the result of NotebookFind is visible. The front end will also usually highlight the
region corresponding to the result. See page 584. See also: NotebookLocate , SelectionMove , NotebookOpen,
Find. New in Version 3.
NotebookGet
NotebookGet[obj] gets the expression corresponding to the notebook represented by the
notebook object obj.
NotebookGet[ ] gets the expression corresponding to the currently selected notebook.
NotebookGet allows you to take a notebook that is open in the front end, and get the expression corresponding to
it in the kernel. NotebookGet returns an expression with head Notebook. See page 578. See also:
NotebookOpen, NotebookPut, Get. New in Version 3.
NotebookLocate
NotebookLocate["tag"] locates all cells with the specified tag in your currently selected
notebook, selecting the cells and scrolling to the position of the first one.
NotebookLocate[{"file", "tag"}] if necessary opens the notebook stored in file, then locates
cells with the specified tag.
NotebookLocate sets the current selection to contain all cells with the specified tag. If the cells are in closed
groups, NotebookLocate will open all these groups. NotebookLocate is used for following hyperlinks within one
notebook or between notebooks. NotebookLocate searches for tags in the list given as the setting for the
CellTags option of each cell. See page 585. See also: NotebookFind, NotebookOpen, SetSelectedNotebook ,
ButtonBox. New in Version 3.
NotebookObject NotebookPut
1224
NotebookObject
NotebookObject[fe, id] is an object that represents an open notebook in the front end.
fe is a FrontEndObject which specifies the front end in which the notebook is open. id is an integer that gives a
unique serial number for this open notebook. In StandardForm and OutputForm notebook objects are printed so
as to indicate the current title of the window that would be used to display the notebook. Functions such as
NotebookPrint and NotebookClose take NotebookObject as their argument. Within any open notebook, there is
always a current selection. The current selection can be modified by applying functions such as SelectionMove to
NotebookObject . See page 579. See also: NotebookSelection , NotebookOpen, Notebooks, SelectedNotebook.
New in Version 3; modified in Version 4.
NotebookOpen
NotebookOpen["name"] opens an existing notebook with the specified name, returning the
corresponding notebook object.
NotebookOpen["name", options] opens a notebook using the options given.
NotebookOpen will usually cause a new notebook window to be opened on your screen. NotebookOpen returns
$Failed if it cannot open a notebook with the specified name. NotebookOpen searches the directories specified by
the NotebookPath global option for the front end. With the option Visible->False set, NotebookOpen will return
a NotebookObject , but will not cause a window to appear on your screen. NotebookOpen initially sets the
current selection to be before the first cell in the notebook. See pages 578 and 591. See also: NotebookCreate ,
NotebookLocate , NotebookSelection , OpenRead, Get, SetSelectedNotebook . New in Version 3.
NotebookPrint
NotebookPrint[notebook] sends a notebook to your printer.
NotebookPrint[notebook, stream] sends a PostScript version of the notebook to the specified
stream.
If notebook is a NotebookObject , then NotebookPrint will print the complete notebook. If it is a
NotebookSelection , then NotebookPrint will print just the selection. NotebookPrint uses the printing options
set for the specified notebook, taking defaults from the global options set for the whole front end.
NotebookPrint[notebook, "file.ps"] saves the PostScript form of the notebook in a file.
NotebookPrint[notebook, "!command"] gives the PostScript form of the notebook as input to a command. See
page 591. See also: NotebookSave, NotebookWrite, PrintingStyleEnvironment . New in Version 3.
NotebookPut
NotebookPut[expr] creates a notebook corresponding to expr and makes it the currently
selected notebook in the front end.
NotebookPut[expr, obj] replaces the notebook represented by the notebook object obj with one
corresponding to expr.
NotebookPut allows you to take a notebook expression in the kernel and make it an open notebook in the front
end. expr must be a notebook expression with head Notebook. NotebookPut returns a NotebookObject
corresponding to the notebook it creates. NotebookPut[expr, obj] overwrites whatever data was contained in the
notebook represented by the notebook object obj. See page 578. See also: NotebookGet, NotebookCreate , Put.
New in Version 3.
NotebookRead NotebookWrite
1225
NotebookRead
NotebookRead[notebook] gives the expression corresponding to the current selection in the
specified notebook object.
NotebookRead is the basic way to get into the kernel pieces of notebooks that are being manipulated by the front
end. See page 585. See also: Get, NotebookWrite , NotebookDelete , ButtonSource. New in Version 3.
Notebooks
Notebooks[ ] gives a list of notebooks currently open in the front end.
Notebooks[ ] returns a list of NotebookObject constructs. Notebooks[fe] gives a list of notebooks open in a
specific front end, specified by a FrontEndObject. The default is $FrontEnd. See page 579. See also:
SelectedNotebook, EvaluationNotebook , NotebookOpen, Streams. New in Version 3.
NotebookSave
NotebookSave[notebook] saves the current version of a notebook in a file.
NotebookSave[notebook, "file"] saves the notebook in the specified file.
NotebookSave[notebook, stream] sends the expression corresponding to the current version of
the notebook to the specified stream.
notebook must be a NotebookObject. NotebookSave[notebook] saves the notebook in a file whose name is given
by the notebook object notebook. NotebookSave writes out the Mathematica expression corresponding to the
notebook, together with Mathematica comments which make it easier for the front end to read the notebook in
again. See page 591. See also: NotebookAutoSave , NotebookPrint. New in Version 3.
NotebookSelection
NotebookSelection[notebook] represents the current selection in an open notebook in the
front end.
NotebookSelection takes a NotebookObject as its argument. You can use Options and SetOptions to read and
write options associated with your current selection. See page 591. See also: SelectionMove. New in Version 3.
NotebookWrite
NotebookWrite[notebook, data] writes data into a notebook at the current selection, setting the
current selection to be just after the data written.
NotebookWrite[notebook, data, sel] writes data into a notebook setting the current selection to
be as specified by sel.
The first argument of NotebookWrite is a NotebookObject. NotebookWrite does essentially the same as a Paste
operation in the front end: it replaces by data whatever the current selection in the notebook is. NotebookWrite is
the basic way to use the Mathematica kernel to modify the contents of notebooks that are being manipulated by the
front end. NotebookWrite automatically wraps Cell around the data you specify if this is necessary. Possible
settings for sel are:
After
All
Before
None
Placeholder
place
make
place
leave
make
the
the
the
the
the
current
current
current
current
current
selection
selection
selection
selection
selection
The default for sel is After, so that NotebookWrite[obj, data] can be called repeatedly to insert several pieces of
data in sequence. See page 585. See also: NotebookApply, NotebookRead, NotebookDelete , SelectionMove.
New in Version 3.
NProduct Null
1226
NProduct
NProduct[f, {i, imin, imax}] gives a numerical approximation to the product imax
iimin f .
NProduct[f, {i, imin, imax, di}] uses a step di in the product.
See notes for NSum. The options NSumExtraTerms and NSumTerms are replaced by NProductExtraFactors and
NProductFactors . See page 957. Related package: NumericalMath`NLimit` . New in Version 1.
-
NSolve
NSolve[lhs==rhs, var] gives a list of numerical approximations to the roots of a polynomial
equation.
, NSolve[{eqn , eqn , ... }, {var , var , ... }] solves a system of polynomial equations.
NSolve[eqns, vars, n] gives results to n-digit precision. NSolve[eqns, vars] gives the same final result as
N[Solve[eqns, vars]], apart from issues of numerical precision. See page 959. Implementation notes: see
page 1068. See also: Solve, FindRoot, NDSolve. Related package: NumberTheory`Recognize` . New in
Version 2; modified in Version 4.1.
NSum
NSum[f, {i, imin, imax}] gives a numerical approximation to the sum imax
iimin f .
NSum[f, {i, imin, imax, di}] uses a step di in the sum.
NSum can be used for sums with both finite and infinite limits. NSum[f, {i, . . . }, {j, . . . }, . . . ] can be used to
evaluate multidimensional sums. - The following options can be given:
AccuracyGoal
Compiled
EvaluationMonitor
Method
NSumExtraTerms
NSumTerms
PrecisionGoal
VerifyConvergence
WorkingPrecision
Infinity
True
None
Automatic
12
15
Automatic
True
MachinePrecision
NSum uses either the Euler-Maclaurin (Integrate) or Wynn epsilon (Fit) method. With the Euler-Maclaurin
method, the options AccuracyGoal and PrecisionGoal can be used to specify the accuracy and precision to try
and get in the final answer. NSum stops when the error estimates it gets imply that either the accuracy or precision
sought has been reached. You should realize that with sufficiently pathological summands, the algorithms used by
NSum can give wrong answers. In most cases, you can test the answer by looking at its sensitivity to changes in the
setting of options for NSum. VerifyConvergence is only used for sums with infinite limits. N[Sum[ . . . ]] calls
NSum. NSum has attribute HoldAll. See page 957. Implementation notes: see page 1068. See also: NProduct.
Related packages: NumericalMath`ListIntegrate` , NumericalMath`NLimit` . New in Version 1; modified in
Version 5.0.
Null
Null is a symbol used to indicate the absence of an expression or a result. When it appears as
an output expression, no output is printed.
e ; e ; . . . ; ek ; returns Null, and prints no output. Expressions like f [e ,,e ] are interpreted to have Null
between each pair of adjacent commas. New in Version 1.
NullRecords NumberForm
1227
NullRecords
NullRecords is an option for Read and related functions which specifies whether null records
should be taken to exist between repeated record separators.
With the default setting NullRecords -> False, repeated record separators are treated like single record separators.
See page 646. See also: WordSeparators. New in Version 2.
NullSpace
NullSpace[m] gives a list of vectors that forms a basis for the null space of the matrix m.
NullSpace works on both numerical and symbolic matrices. NullSpace[m, Modulus->n] finds null spaces for
integer matrices modulo n. NullSpace[m, ZeroTest -> test] evaluates test[ m[[i, j]] ] to determine whether
matrix elements are zero. The default setting is ZeroTest -> Automatic. A Method option can also be given.
Possible settings are as for LinearSolve. See page 907. Implementation notes: see page 1069. See also:
MatrixRank, LinearSolve, RowReduce, SingularValueList . New in Version 1; modified in Version 3.
NullWords
NullWords is an option for Read and related functions which specifies whether null words
should be taken to exist between repeated word separators.
With the default setting NullWords -> False, repeated word separators are treated like single word separators.
See page 646. See also: TokenWords, RecordSeparators . New in Version 2.
Number
Number represents an exact integer or an approximate real number in Read.
An integer is returned if no explicit decimal point is present. Approximate real numbers can be given in C or
Fortran forms, such as 2.4E5 or -3.4e-4. See page 646. See also: Real, DigitQ. New in Version 1.
NumberForm
NumberForm[expr, n] prints with approximate real numbers in expr given to n-digit precision.
NumberForm[expr, {n, f}] prints with approximate real numbers having n digits, with f digits to the right of the
decimal point. NumberForm works on integers as well as approximate real numbers. - The following options can
be given:
DigitBlock
ExponentFunction
NumberFormat
NumberMultiplier
NumberPadding
NumberPoint
NumberSeparator
NumberSigns
SignPadding
Infinity
Automatic
Automatic
""
{"", ""}
"."
","
{"-", "+"}
False
All options except ExponentFunction apply to integers as well as approximate real numbers. You can mix
NumberForm and BaseForm. NumberForm acts as a wrapper, which affects printing, but not evaluation. See
page 435. See also: ScientificForm , EngineeringForm , AccountingForm , BaseForm, PaddedForm, N. New in
Version 1; modified in Version 3.
NumberFormat NumberQ
1228
NumberFormat
NumberFormat is an option for NumberForm and related functions which specifies how the
mantissa, base and exponent should be assembled into a final print form.
With the setting NumberFormat -> f, the function f is supplied with three arguments: the mantissa, base and
exponent of each number to be printed. The arguments are all given as strings. When no exponent is to be
printed, the third argument is given as "". The function f must return the final format for the number. See
page 436. See also: ExponentFunction . New in Version 2.
NumberMarks
NumberMarks is an option for InputForm and related functions that specifies whether ` marks
should be included in the printed forms of approximate numbers.
The default setting for NumberMarks is given by the value of $NumberMarks. NumberMarks->True indicates that `
should be used in all approximate numbers, both machine-precision and arbitrary-precision ones.
NumberMarks -> Automatic indicates that ` should be used in arbitrary-precision but not machine-precision
numbers. NumberMarks -> False indicates that ` should never be used in outputting numbers. Number marks
are used to indicate the type of numbers, and their precision or accuracy. The *^ form for scientific notation is
always used in InputForm, and is independent of NumberMarks. See page 730. See also: NumberForm. New in
Version 3.
NumberMultiplier
NumberMultiplier is an option for NumberForm and related functions which gives the string
to use as a multiplication sign in scientific notation.
The default is NumberMultiplier -> "\[Times]".
New in Version 3.
NumberPadding
NumberPadding is an option for NumberForm and related functions which gives strings to use
as padding on the left- and right-hand sides of numbers.
NumberPadding -> {"sleft", "sright"} specifies strings to use for padding on the left and right. In NumberForm,
the default setting is NumberPadding -> {"", ""}. In PaddedForm, the default setting is
NumberPadding -> {" ", "0"}. The strings specified as padding are inserted in place of digits. See page 436.
See also: SignPadding. New in Version 2.
NumberPoint
NumberPoint is an option for NumberForm and related functions which gives the string to use
as a decimal point.
The default is NumberPoint -> ".".
New in Version 1.
NumberQ
NumberQ[expr] gives True if expr is a number, and False otherwise.
NumberQ[expr] returns False unless expr is manifestly a number (i.e., has head Complex, Integer, Rational or
Real). NumberQ[Infinity] gives False. NumberQ[Overflow[ ]] and NumberQ[Underflow[ ]] give True. You
can use NumberQ[x] ^= True to override the normal operation of NumberQ, and effectively define x to be a number.
See pages 267 and 723. See also: NumericQ, IntegerQ, MachineNumberQ , TrueQ, Complexes. New in Version 1;
modified in Version 3.
NumberSeparator NumericQ
1229
NumberSeparator
NumberSeparator is an option for NumberForm and related functions which gives the string to
insert at breaks between digits.
NumberSeparator -> "s" specifies that the string s should be inserted at every break between digits specified by
DigitBlock. NumberSeparator -> {"sleft", "sright"} specifies different strings to be used on the left and right of
the decimal point. The default setting is NumberSeparator -> ",". See page 436. New in Version 1.
NumberSigns
NumberSigns is an option for NumberForm and related functions which gives strings to use as
signs for negative and positive numbers.
NumberSigns -> {"sneg", "spos"} specifies that "sneg" should be given as the sign for negative numbers, and
"spos" for positive numbers. The default setting is NumberSigns -> {"-", ""}.
NumberSigns -> {{"snleft", "snright"}, {"spleft", "spright"}} specifies strings to put both on the left and right
of numbers to specify their signs. In AccountingForm, the default setting is NumberSigns -> {{"(", ")"}, ""}.
See page 436. See also: SignPadding. New in Version 2.
Numerator
Numerator[expr] gives the numerator of expr.
Numerator picks out terms which do not have superficially negative exponents. Denominator picks out the
remaining terms. An exponent is superficially negative if it has a negative number as a factor. The standard
representation of rational expressions as products of powers means that you cannot simply use Part to extract
numerators. Numerator can be used on rational numbers. See page 74. See also: ExpandNumerator . New in
Version 1.
NumericFunction
NumericFunction is an attribute that can be assigned to a symbol f to indicate that
f[arg , arg , ... ] should be considered a numeric quantity whenever all the argi are numeric
quantities.
Most standard built-in mathematical functions have the attribute NumericFunction. NumericQ checks the
NumericFunction attribute of every function it encounters. If you assign the attribute NumericFunction to a
function that does not yield numerical values, then NumericQ will give misleading results. See pages 329 and 724.
See also: NumericQ, NHoldAll. New in Version 3.
NumericQ
NumericQ[expr] gives True if expr is a numeric quantity, and False otherwise.
An expression is considered a numeric quantity if it is either an explicit number or a mathematical constant such as
Pi, or is a function that has attribute NumericFunction and all of whose arguments are numeric quantities. In
most cases, NumericQ[expr] gives True whenever N[expr] would yield an explicit number. See page 724. See
also: NumberQ. New in Version 3.
O On
1230
O
O[x]^n represents a term of order xn .
O[x]^n is generated to represent omitted higher-order terms in power series.
O[x, x ]^n represents a term of order x x n .
Normal can be used to truncate power series, and remove O terms.
New in Version 1.
OddQ
OddQ[expr] gives True if expr is an odd integer, and False otherwise.
OddQ[expr] returns False unless expr is manifestly an odd integer (i.e., has head Integer, and is odd). You can
use OddQ[x] ^= True to override the normal operation of OddQ, and effectively define x to be an odd integer. See
pages 267 and 723. See also: IntegerQ, EvenQ, TrueQ. New in Version 1.
Off
Off[symbol::tag] switches off a message, so that it is no longer printed.
Off[s] switches off tracing messages associated with the symbol s.
Off[m , m , ... ] switches off several messages.
Off[ ] switches off all tracing messages.
The value of symbol::tag is not affected by Off. Off[s] is equivalent to Off[s::trace]. Off[ ] is equivalent to
Off[s::trace] for all symbols. See pages 61 and 479. See also: On, Message, Check. New in Version 1.
Offset
Offset[{dx, dy}, position] gives the position of a graphical object obtained by starting at the
specified position and then moving by absolute offset {dx, dy}.
Offset can be used to specify offsets in any two-dimensional graphics primitive. position can be either {x, y} or
Scaled[{x, y}, . . . ]. The offset is measured in units of printers points, approximately equal to
of an inch.
Offset[{dx, dy}] can be used to specify an absolute radius in a Circle or Disk object. See page 506. See
also: Scaled, AbsolutePointSize , AbsoluteThickness . New in Version 3.
On
On[symbol::tag] switches on a message, so that it can be printed.
On[s] switches on tracing for the symbol s.
On[m , m , ... ] switches on several messages.
On[ ] switches on tracing for all symbols.
When tracing is switched on, each evaluation of a symbol, on its own, or as a function, is printed, together with
the result. Note that the tracing information is printed when a function returns. As a result, traces of recursive
functions appear in the opposite order from their calls. On[s] is equivalent to On[s::trace]. On[ ] is equivalent
to On[s::trace] for all symbols. See pages 61 and 479. See also: Off, TracePrint. New in Version 1.
OneIdentity OpenTemporary
1231
OneIdentity
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.
OneIdentity has an effect only if f has attribute Flat. Functions like Plus and Times have the attribute
OneIdentity. The fact that Times has attribute OneIdentity allows a pattern like n_. x_ to match x. See
pages 271 and 329. See also: Flat, Nest. New in Version 1.
,
OpenAppend
OpenAppend["file"] opens a file to append output to it, and returns an OutputStream object.
The following options can be given:
CharacterEncoding
FormatType
NameConversion
NumberMarks
PageWidth
TotalWidth
"ASCII"
InputForm
None
$NumberMarks
78
Infinity
On computer systems that support pipes, OpenAppend["!command"] runs the external program specified by
command, and opens a pipe to send input to it. If OpenRead does not succeed in opening a particular file or pipe,
it generates a message, and returns $Failed. OpenAppend resolves file names according to the procedure
described in Section A.6.1. OpenAppend returns OutputStream["name", n], where name is the full name of a file
or command, and n is a serial number that is unique across all streams opened in the current Mathematica session.
SetOptions can be used to change the properties of an output stream, after it is already open. Functions like
Put and Write automatically open the files or pipes they need, if they are not already open. Setting the option
DOSTextFormat->True causes newlines specified by \n to be output as \r\n pairs, suitable for text-mode files on
MS-DOS and related systems. See page 632. See also: Close, Put, Streams, LinkCreate. New in Version 1;
modified in Version 3.
OpenRead
OpenRead["file"] opens a file to read data from, and returns an InputStream object.
OpenRead prepares to read from a file, starting at the beginning of the file. On systems that support pipes,
OpenRead["!command"] runs the external program specified by command, and opens a pipe to get input from it.
If OpenRead does not succeed in opening a particular file or pipe, it generates a message, and returns $Failed.
OpenRead resolves file names according to the procedure described in Section A.6.1. The function ReadList
automatically opens files or pipes that it needs. OpenRead returns InputStream["name", n], where name is the
full name of a file or command, and n is a serial number that is unique across all streams opened in the current
Mathematica session. Setting the option DOSTextFormat->True causes all input to be treated as coming from a
text-mode file on an MS-DOS or related system. This means that \r\n pairs are interpreted as single newlines, and
Z is interpreted as EndOfFile. See page 649. See also: Close, Read, ReadList, Streams, LinkCreate. New
in Version 1; modified in Version 3.
OpenTemporary
OpenTemporary[ ] opens a temporary file to which output can be written, and returns an
OutputStream object.
OpenTemporary is often used in conjunction with Put and Get as a way of preparing data that is exchanged
between Mathematica and external programs. OpenTemporary always creates a new file, that does not already
exist. On Unix systems, OpenTemporary typically creates a file in the /tmp directory. The global variable
$TemporaryPrefix gives the base of the file name used by OpenTemporary . See page 629. See also: Close, Run.
New in Version 1.
OpenWrite Options
1232
OpenWrite
OpenWrite["file"] opens a file to write output to it, and returns an OutputStream object.
OpenWrite deletes any existing contents in a file, and prepares to write output starting at the beginning of the file.
For output to pipes, OpenWrite and OpenAppend are equivalent. See notes for OpenAppend. See page 632.
New in Version 1.
Operate
Operate[p, f [x, y]] gives p[f][x, y].
Operate[p, expr, n] applies p at level n in the head of expr.
Examples: Operate[p, f[x,y]] # p
f
x, y ; Operate[p, f[x][y][z], 1] # p
f
x
y
z ;
Operate[p, f[x][y][z], 2] # p
f
x
y
z . Operate[p, f [x]] effectively applies the functional operator p
to the function f. Operate is essentially a generalization of Apply, which allows you to apply an operator to the
head of an expression, rather than simply to replace the head. See page 254. See also: Through, Apply, Heads.
New in Version 1.
Optional
p:v is a pattern object which represents an expression of the form p, which, if omitted, should
be replaced by v.
Optional is used to specify optional arguments in functions represented by patterns. The pattern object p gives
the form the argument should have, if it is present. The expression v gives the default value to use if the
argument is absent. Example: the pattern f[x_, y_:1] is matched by f[a], with x taking the value a, and y
taking the value 1. It can also be matched by f[a, b], with y taking the value b. The form s_:v is equivalent to
Optional[s_, v]. This form is also equivalent to s:_:v. There is no syntactic ambiguity since s must be a symbol
in this case. The special form s_. is equivalent to Optional[s_] and can be used to represent function arguments
which, if omitted, should be replaced by default values globally specified for the functions in which they occur.
Values for Default[f, . . . ] specify default values to be used when _. appears as an argument of f. Any
assignments for Default[f, . . . ] must be made before _. first appears as an argument of f. Optional[s_h]
represents a function which can be omitted, but which, if present, must have head h. There is no simpler syntactic
form for this case. Functions with built-in default values include Plus, Times and Power. See pages 274
and 1030. See also: Alternatives. New in Version 1.
Options
Options[symbol] gives the list of default options assigned to a symbol.
Options[expr] gives the options explicitly specified in a particular expression such as a
graphics object.
Options[stream] or Options["sname"] gives options associated with a particular stream.
Options[object] gives options associated with an external object such as a NotebookObject .
Options[obj, name] gives the setting for the option name.
Options[obj, {name , name , ... }] gives a list of the settings for the options namei .
Many built-in functions allow you to give additional arguments that specify options with rules of the form
name -> value. Options[f] gives the list of rules to be used for the options associated with a function f if no
explicit rules are given when the function is called. Options always returns a list of transformation rules for
option names. You can assign a value to Options[symbol] to redefine all the default option settings for a
function. SetOptions[symbol, name -> value] can be used to specify individual default options. You can use
Options on InputStream and OutputStream objects. If there is only one stream with a particular name, you can
give the name as a string as the argument of Options. If you ask for Options[NotebookObject[ . . . ], name] the
kernel will send a request to the front end to find the result. Explicit values are found for options associated with
cells even if these options are only set at the style, notebook or global level. See pages 144 and 1040. See also:
AbsoluteOptions . Related package: Utilities`FilterOptions` . New in Version 1; modified in Version 3.
Or Orderless
1233
Or
e || e || ... is the logical OR function. It evaluates its arguments in order, giving True
immediately if any of them are True, and False if they are all False.
Or[e , e , . . . ] can be input in StandardForm and InputForm as e e . . . . The character can be entered as
, || ,, , or , or \[Or]. Or evaluates its arguments in a non-standard way (see page 1046). Or gives symbolic
results when necessary, removing initial arguments that are False. See page 87. See also: Xor, LogicalExpand,
BitOr, Nor. New in Version 1; modified in Version 3.
Order
Order[expr , expr ] gives 1 if expr is before expr in canonical order, and -1 if expr is after
expr in canonical order. It gives 0 if expr is identical to expr .
Examples: Order[a, b] # 1 ; Order[b, a] # 1 .
Sort. See page 255. See also: Equal, SameQ, Sort.
OrderedQ
OrderedQ[h[e , e , ... ]] gives True if the ei are in canonical order, and False otherwise.
See notes for Order. OrderedQ[{e, e}] gives True. By default, OrderedQ uses canonical order as described in
the notes for Sort. OrderedQ[list, p] uses the function p to determine whether each pair of elements in list is in
order. See page 268. See also: Signature, Sort. New in Version 1.
,
Ordering
Ordering[list]
appears.
Ordering[list,
Ordering[list,
Ordering[list,
Example: Ordering[{c, a, b}] # 2, 3, 1. In a numerical list Ordering[list, n] gives the positions of the n
smallest elements. Ordering[list, -n] gives the positions of the n largest elements. If there are several smallest
elements in list, Ordering[list, 1] will give only the position of the one that appears first. list[[Ordering[list]]]
is the same as Sort[list]. Ordering[list, seq] is equivalent to Take[Ordering[list], seq].
Ordering[list, All, p] gives the position at which all elements of list appear in Sort[list, p]. Ordering can
be used on expressions with any head, not only List. See page 129. See also: Max, Min, Position, OrderedQ,
Median. New in Version 4.1.
Orderless
Orderless is an attribute that can be assigned to a symbol f to indicate that the elements ei in
expressions of the form f [e , e , ... ] should automatically be sorted into canonical order. This
property is accounted for in pattern matching.
The Orderless attribute for a function corresponds to the mathematical property of commutativity. Functions
with the Orderless attribute use canonical order as described in the notes for Sort. For an object that represents
a matrix or a tensor, the Orderless attribute represents symmetry among indices. Functions like Plus and Times
are Orderless. In matching patterns with Orderless functions, all possible orders of arguments are tried. The
Orderless attribute must be assigned before defining any values for an Orderless function. See page 329. See
also: Sort, Flat, OneIdentity. New in Version 1.
Out OutputStream
1234
Out
%n or Out[n] is a global object that is assigned to be the value produced on the nth output line.
% gives the last result generated.
%% gives the result before last. %% ... % (k times) gives the kth previous result.
Out[ ] is equivalent to %. Out[-k] is equivalent to %% . . . % (k times).
$HistoryLength , MessageList. New in Version 1.
Outer
Outer[f, list , list , ... ] gives the generalized outer product of the listi , forming all possible
combinations of the lowest-level elements in each of them, and feeding them as arguments to f.
Outer[f, list , list , ... , n] treats as separate elements only sublists at level n in the listi .
Outer[f, list , list , ... , n , n , ... ] treats as separate elements only sublists at level ni in
the corresponding listi .
Example: Outer[f,{a,b},{x,y}] # f
a, x, f
a, y, f
b, x, f
b, y . Outer[Times, list , list ]
gives an outer product. The result of applying Outer to the tensors Ti i ir and Uj j js is the tensor Vi i ir j j js
with elements f [Ti i ir ,Uj j js ]. Applying Outer to two tensors of ranks r and s gives a tensor of rank r s.
The heads of both listi must be the same, but need not necessarily be List. The listi need not necessarily be
cuboidal arrays. The specifications ni of levels must be integers. If only a single level specification is given, it is
assumed to apply to all the listi . If there are several ni , but fewer than the number of listi , all levels in the
remaining listi will be used. , Outer can be used on SparseArray objects, returning a SparseArray object when
possible. See page 917. See also: Inner, Distribute, Cross. New in Version 1; modified in Version 3.
OutputForm
OutputForm[expr] prints as a two-dimensional representation of expr using only keyboard
characters.
OutputForm is an approximation to StandardForm which uses only ordinary keyboard characters. The OutputForm
of many kinds of expressions is quite different from their internal representation. OutputForm acts as a
wrapper, which affects printing, but not evaluation. OutputForm cannot be used directly for input to
Mathematica. When possible, OutputForm uses approximations to special characters. Thus is given as >= and
as e'. See page 424. See also: StandardForm , TraditionalForm , InputForm, TeXForm, MathMLForm, Short,
FullForm. New in Version 1; modified in Version 3.
OutputStream
OutputStream["name", n] is an object that represents an output stream for functions such as
Write.
OpenWrite and OpenAppend return OutputStream objects. The serial number n is unique across all streams,
regardless of their name. See page 631. See also: Streams, InputStream. New in Version 2.
OverscriptBox PadLeft
1235
OverscriptBox
y
PaddedForm
PaddedForm[expr, n] prints with all numbers in expr padded to leave room for a total of n
digits.
PaddedForm[expr, {n, f}] prints with approximate real numbers having exactly f digits to the
right of the decimal point.
By default, PaddedForm pads with spaces on the left to leave room for n digits. PaddedForm pads with zeros on
the right in approximate real numbers. The length n specified in PaddedForm counts only digits, and not signs,
breaks between digits, and so on. PaddedForm takes the same options as NumberForm, but with some defaults
different. You can use PaddedForm to align columns of numbers. PaddedForm acts as a wrapper, which affects
printing, but not evaluation. See page 437. See also: ColumnForm, TableForm. New in Version 2.
PadLeft
PadLeft[list,
PadLeft[list,
PadLeft[list,
PadLeft[list,
PadLeft[list,
(continued)
1236
PadLeft
(continued)
PadRight
PadRight[list,
PadRight[list,
PadRight[list,
PadRight[list,
PadRight[list,
PageBreakAbove
PageBreakAbove is an option for Cell which specifies whether a page break should be made
immediately above the cell if the notebook that contains the cell is printed.
A setting of Automatic specifies that a page break should be made if necessary. A setting of True specifies that a
page break should always be made, while a setting of False specifies that it should never be made. See
page 609. See also: PageBreakBelow, ShowPageBreaks. New in Version 3.
PageBreakBelow
PageBreakBelow is an option for Cell which specifies whether a page break should be made
immediately below the cell if the notebook that contains the cell is printed.
A setting of Automatic specifies that a page break should be made if necessary. A setting of True specifies that a
page break should always be made, while a setting of False specifies that it should never be made. See
page 609. See also: PageBreakAbove, ShowPageBreaks. New in Version 3.
PageBreakWithin ParametricPlot
1237
PageBreakWithin
PageBreakWithin is an option for Cell which specifies whether a page break should be
allowed within the cell if the notebook that contains the cell is printed.
See page 609.
New in Version 3.
PageWidth
PageWidth is an option for output streams and for cells which specifies how wide each line of
text should be allowed to be.
-
Infinity
n
SetOptions[stream, PageWidth -> val] resets the line width allowed for an open stream.
cells are:
WindowWidth the width of the window on the screen
PaperWidth
the width of the page as it would be printed
n
explicit width given in printers points
PageWidth->WindowWidth allows each line to use the full width of the displayed window, taking into account
settings for CellMargins. See pages 609 and 634. See also: TotalWidth, TextJustification , AutoIndent.
New in Version 1; modified in Version 3.
ParagraphIndent
ParagraphIndent is an option for Cell which specifies how far in printers points to indent
the first line of each paragraph of text.
A new paragraph is taken to start at the beginning of a cell, and after every explicit RETURN character in your text.
Negative settings for ParagraphIndent make the first line of each paragraph stick out to the left. See page 609.
See also: AutoIndent, LineIndent, ParagraphSpacing . New in Version 3.
ParagraphSpacing
ParagraphSpacing is an option for Cell, StyleBox and StyleForm which specifies how much
extra space to leave between successive paragraphs of text.
ParagraphSpacing->{c, 0} leaves an extra space of c times the height of the font in the paragraph.
ParagraphSpacing->{0, n} leaves an extra space of exactly n printers points. ParagraphSpacing->{c, n}
leaves an extra space of c times the height of the font plus n printers points. Paragraph breaks are taken to
occur whenever an explicit RETURN character appears in a block of text. ParagraphSpacing is added to
LineSpacing to determine spacing between paragraphs. A typical default setting is ParagraphSpacing->{0, 0}.
ParagraphSpacing applies only to ordinary text, not Mathematica expressions. Extra space specified by
ParagraphSpacing is inserted before the first line of each paragraph. No extra space is inserted if the paragraph is
at the beginning of a cell or a string. See page 611. See also: LineSpacing, ParagraphIndent . New in
Version 3.
ParametricPlot
ParametricPlot[{f x , fy }, {t, tmin, tmax}] produces a parametric plot with x and y
coordinates fx and fy generated as a function of t.
ParametricPlot[{{f x , fy }, {gx , gy }, ... }, {t, tmin, tmax}] plots several parametric curves.
ParametricPlot evaluates its arguments in a non-standard way (see page 1046). You should use Evaluate to
evaluate the function to be plotted if this can safely be done before specific numerical values are supplied. The
options that can be given for ParametricPlot are the same as for Plot. ParametricPlot has the default option
setting Axes -> True. ParametricPlot returns a Graphics object. See page 161. See also: ContourPlot.
Related packages: Graphics`ImplicitPlot` , Graphics`PlotField` . New in Version 1.
ParametricPlot3D Part
1238
ParametricPlot3D
ParametricPlot3D[{f x , fy , fz }, {t, tmin, tmax}] produces a three-dimensional space curve
parametrized by a variable t which runs from tmin to tmax.
ParametricPlot3D[{f x , fy , fz }, {t, tmin, tmax}, {u, umin, umax}] produces a
three-dimensional surface parametrized by t and u.
ParametricPlot3D[{f x , fy , fz , s}, ... ] shades the plot according to the color specification s.
ParametricPlot3D[{{f x , fy , fz }, {gx , gy , gz }, ... }, ... ] plots several objects together.
ParametricPlot3D evaluates its arguments in a non-standard way (see page 1046). You should use Evaluate to
evaluate the function to be plotted if this can safely be done before specific numerical values are supplied.
ParametricPlot3D has the same options as Graphics3D, with the following additions:
Compiled
PlotPoints
True
Automatic
ParametricPlot3D has the default option setting Axes -> True. - With the default setting
PlotPoints -> Automatic, ParametricPlot3D uses PlotPoints -> 75 for curves and PlotPoints -> {30, 30} for
surfaces. ParametricPlot3D returns a Graphics3D object. See page 163. Related packages:
Graphics`PlotField3D` , Graphics`ContourPlot3D` , Graphics`SurfaceOfRevolution` , Graphics`Shapes` . New
in Version 2.
ParentDirectory
ParentDirectory[ ] gives the parent of the current working directory.
ParentDirectory["dir"] gives the parent of the directory dir.
ParentDirectory returns the full name of the directory as a string. ParentDirectory works only under
operating systems which support hierarchical file systems. See page 637. See also: Directory, $HomeDirectory ,
DirectoryName. New in Version 2.
-
Part
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[[ {i , i , ... } ]] gives a list of the parts i , i , ... of expr.
You can make an assignment like t[[i]] = value to modify part of an expression. When expr is a list,
expr[[ {i , i , . . . } ]] gives a list of parts. In general, the head of expr is applied to the list of parts. You can
get a nested list of parts from expr[[list , list , . . . ]]. Each part has one index from each list. If any of the listi
are All, all parts at that level are kept. expr[[All, i]] effectively gives the ith column in expr. Notice that lists
are used differently in Part than in functions like Extract, MapAt and Position. expr[[ Range[i, j] ]] can be
used to extract sequences of parts. , If expr is a SparseArray object, expr[[. . . ]] gives the parts in the
corresponding ordinary array. In StandardForm and InputForm, expr[[spec]] can be input as expr+spec,. + and
, can be entered as , [[ , and , ]] , or \[LeftDoubleBracket] and \[RightDoubleBracket] . In StandardForm,
expr[[spec]] can be input as expr
spec or expr+spec,
See pages 235 and 285. See also: First, Head, Last,
Extract, Position, ReplacePart, MapAt, Take, PadLeft. Related package: LinearAlgebra`MatrixManipulation` .
New in Version 1; modified in Version 5.0.
Partition Partition
1239
Partition
Partition[list, n] partitions list into non-overlapping sublists of length n.
Partition[list, n, d] generates sublists with offset d.
Partition[list, {n , n , ... }] partitions a nested list into blocks of size n n .
Partition[list, {n , n , ... }, {d , d , ... }] uses offset di at level i in list.
Partition[list, n, d, {kL , kR }] specifies that the first element of list should appear at
position kL in the first sublist, and the last element of list should appear at or after position kR
in the last sublist. If additional elements are needed, Partition fills them in by treating list as
cyclic.
Partition[list, n, d, {kL , kR }, x] pads if necessary by repeating the element x.
Partition[list, n, d, {kL , kR }, {x , x , ... }] pads if necessary by cyclically repeating the
elements xi .
Partition[list, n, d, {kL , kR }, {}] uses no padding, and so can yield sublists of different
lengths.
Partition[list, nlist, dlist, {klistL , klistR }, padlist] specifies alignments and padding in a
nested list.
Example: Partition[{a,b,c,d,e,f}, 2] # a, b, c, d, e, f . All the sublists generated by
Partition[list, n, d] are of length n. Some elements at the end of list may therefore not appear in any sublist.
The element e in Partition[{a,b,c,d,e}, 2] # a, b, c, d is dropped.
Partition[{a,b,c,d,e}, 3, 1] # a, b, c, b, c, d, c, d, e generates sublists with offset 1. All
elements of list appear in the sublists generated by Partition[list, n, 1]. If d is greater than n in
Partition[list, n, d], then elements in the middle of list are skipped. Partition[list, 1, d] picks out elements
in the same way as Take[list, {1, -1, d}]. Partition[list, n, d, {kL , kR }] effectively allows sublists that have
overhangs that extend past the beginning or end of list. Partition[list, n, d, k] is equivalent to
Partition[list, n, d, {k, k}]. Common settings for {kL , kR } are:
{1, -1}
{1, 1}
{-1, -1}
{-1, 1}
allow
allow
allow
allow
no overhangs
maximal overhang at the end
maximal overhang at the beginning
maximal overhangs at both beginning and end
Example: Partition[{a,b,c,d},2,1,{-1,1}] # d, a, a, b, b, c, c, d, d, a .
Partition[list, n, d, {kL , kR }, padlist] effectively lays down repeated copies of padlist, then superimposes one
copy of list on them, and partitions the result. Common settings for padlist are:
x
{x , x , . . . }
list
{}
(continued)
1240
Partition
(continued)
Example: Partition[{a,b,c,d},2,1,{-1,1},{x,y}] # y, a, a, b, b, c, c, d, d, x .
Partition[{a,b,c,d},2,1,{-1,1},{}] # a, a, b, b, c, c, d, d . If list has length s, then
Partition[list, n, d] yields Max[0, Floor[(s + d - n)/d]] sublists. Partition[list, {n , n , . . . , nr }]
effectively replaces blocks of elements at level r in list by depth r nested lists of neighboring elements. If no
offsets are specified, the neighborhoods are adjacent and non-overlapping. Partition[list, {n , n , . . . }, d] uses
offset d at every level. Partition[list, nlist, dlist, {{kL , kL , . . . }, {kR , kR , . . . }}] specifies that element
{1,1,. . . } of list should appear at position {kL , kL , . . . } in the {1,1,. . . } block of the result, while element
{-1,-1,. . . } of list should appear at or after position {kR , kR , . . . } in the {-1,-1,. . . } block of the result.
{kL , kR } is taken to be equivalent to {{kL , kL , . . . }, {kR , kR , . . . }}. {{k , k , . . . }} is taken to be equivalent
to {{k , k , . . . }, {k , k , . . . }}. Partition[list, {n , n , . . . , nr }, klist, padlist] effectively makes a depth r
array of copies of padlist, then superimposes list on them, and partitions the result. If list has dimensions
{s , s , . . . , sr } then Partition[list, {n , n , . . . , nr }] will have dimensions
{q , q , . . . , qr , n , n , . . . , nr } where qi is given by Floor[si /ni ]. The object list need not have head List.
Partition[f[a,b,c,d], 2] # f
f
a, b, f
c, d . , Partition can be used on SparseArray objects. See
page 292. See also: Flatten, RotateLeft, Split, Take, PadLeft, ListConvolve, CellularAutomaton . New in
Version 1; modified in Version 4.
PartitionsP
PartitionsP[n] gives the number pn of unrestricted partitions of the integer n.
Integer mathematical function (see Section A.3.10). See page 757.
also: PartitionsQ, DedekindEta. New in Version 1.
See
PartitionsQ
PartitionsQ[n] gives the number qn of partitions of the integer n into distinct parts.
Integer mathematical function (see Section A.3.10).
New in Version 1.
Path
Path is an option for Get and related functions which gives a list of directories to search in
attempting to find an external file.
The default setting is Path :> $Path. The possible settings for Path are the same as those for $Path.
page 637. See also: $Path, SetDirectory, $Input. New in Version 4.
See
Pattern
s:obj represents the pattern object obj, assigned the name s.
The name s must be a symbol. The object obj can be any pattern object. When a transformation rule is used,
any occurrence of s on the right-hand side is replaced by whatever expression it matched on the left-hand side.
The operator : has a comparatively low precedence. The expression x:_+_ is thus interpreted as x:(_+_), not
(x:_)+_. The form s_ is equivalent to s:_. Similarly, s_h is equivalent to s:_h, s__ to s:__, and so on. See
pages 263 and 1030. New in Version 1.
PatternTest Play
1241
PatternTest
p?test is a pattern object that stands for any expression which matches p, and on which the
application of test gives True.
Any result for test[pval] other than True is taken to signify failure. Example: _?NumberQ represents a number of
any type. The _ matches any expression, and ?NumberQ restricts to any expression which gives True on application
of the number test NumberQ. The operator ? has a high precedence. Thus _^_?t is _^(_?t) not (_^_)?t. In a
form such as __?test every element in the sequence matched by __ must yield True when test is applied. See
page 269. See also: Condition, Element. New in Version 1.
Pause
Pause[n] pauses for at least n seconds.
Pause is accurate only down to a granularity of at least $TimeUnit seconds. - The time elapsed during the
execution of Pause is counted in SessionTime and AbsoluteTiming, but not in TimeUsed or Timing. Under
multitasking operating systems, there may be a delay of significantly more than n seconds when you execute
Pause[n]. See page 710. New in Version 2.
Permutations
Permutations[list] generates a list of all possible permutations of the elements in list.
Example: Permutations[{a,b,c}] # a, b, c, a, c, b, b, a, c, b, c, a, c, a, b, c, b, a .
There are nd permutations of a list of n distinct elements. Repeated elements are treated as identical. The
object list need not have head List. See page 129. See also: Sort, Signature, Reverse, RotateLeft. Related
packages: DiscreteMath`Permutations` , DiscreteMath`Combinatorica` . New in Version 1.
Pi
Pi is , with numerical value
.
Mathematical constant (see Section A.3.11). Pi can be entered in StandardForm and InputForm as , , pi ,, , p , or
\[Pi]. In StandardForm, Pi is printed as . See page 765. Implementation notes: see page 1067. See also:
Degree. New in Version 1; modified in Version 3.
Play
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.
Play evaluates its arguments in a non-standard way (see page 1046). Play[{f , f }, {t, tmin, tmax}] produces
stereo sound. The left-hand channel is given first. Play[{f , f , . . . }, . . . ] generates sound output on any
number of channels. The following options can be given:
Compiled
DisplayFunction
Epilog
PlayRange
Prolog
SampleDepth
SampleRate
True
$SoundDisplayFunction
{}
Automatic
{}
8
8192
Play returns a Sound object. See page 171. See also: ListPlay, SampledSoundFunction , Show.
packages: Miscellaneous`Audio` , Miscellaneous`Music` . New in Version 2.
Related
PlayRange Plot3D
1242
PlayRange
PlayRange is an option for Play and related functions which specifies what range of sound
amplitude levels should be included.
All amplitudes are scaled so that the amplitude levels to be included lie within the range that can be output.
Amplitude levels outside the range specified are clipped. The possible settings for PlayRange are:
include all amplitude levels
outlying levels are dropped
explicit amplitude limits
All
Automatic
{amin, amax}
See page 172.
New in Version 2.
Plot
Plot[f, {x, xmin, xmax}] generates a plot of f as a function of x from xmin to xmax.
Plot[{f , f , ... }, {x, xmin, xmax}] plots several functions fi .
Plot evaluates its arguments in a non-standard way (see page 1046). You should use Evaluate to evaluate the
function to be plotted if this can safely be done before specific numerical values are supplied. Plot has the same
options as Graphics, with the following additions:
Compiled
MaxBend
PlotDivision
PlotPoints
PlotStyle
True
10.
20.
25
Automatic
Plot uses the default setting Axes -> True. Plot initially evaluates f at a number of equally spaced sample
points specified by PlotPoints. Then it uses an adaptive algorithm to choose additional sample points, attempting
to produce a curve in which the bend between successive segments is less than MaxBend. It subdivides a given
interval by a factor of at most PlotDivision. You should realize that with the finite number of sample points
used, it is possible for Plot to miss features in your function. To check your results, you should increase the
setting for PlotPoints. Plot returns a Graphics object. See page 131. See also: ListPlot, Graphics.
Related packages: Graphics`FilledPlot` , Graphics`Graphics` . New in Version 1.
Plot3D
Plot3D[f, {x, xmin, xmax}, {y, ymin, ymax}] generates a three-dimensional plot of f as a
function of x and y.
Plot3D[{f, s}, {x, xmin, xmax}, {y, ymin, ymax}] generates a three-dimensional plot in
which the height of the surface is specified by f, and the shading is specified by s.
Plot3D evaluates its arguments in a non-standard way (see page 1046). You should use Evaluate to evaluate the
function to be plotted if this can safely be done before specific numerical values are supplied. Plot3D has the
same options as SurfaceGraphics , with the following additions:
Compiled
PlotPoints
True
25
Plot3D has the default option setting Axes -> True. Plot3D returns a SurfaceGraphics object. The function f
should give a real number for all values of x and y at which it is evaluated. There will be holes in the final surface
at any values of x and y for which f does not yield a real number value. If Lighting->False and no shading
function s is specified, the surface is shaded according to height. The shading is determined by the option
ColorFunction; the default is gray levels. The shading function s must yield GrayLevel, Hue or RGBColor
directives, or SurfaceColor objects. Plot3D includes a setting for the MeshRange option in the SurfaceGraphics
object it returns. See page 149. See also: ListPlot3D, ContourPlot, DensityPlot, Graphics3D. New in
Version 1.
PlotDivision PlotRange
1243
PlotDivision
PlotDivision is an option for Plot which specifies the maximum amount of subdivision to be
used in attempting to generate a smooth curve.
Plot initially uses PlotPoints equally spaced sample points. In attempting to generate curves with no bends larger
than MaxBend, Plot subdivides by at most a factor of PlotDivision. The finest resolution in Plot is of order
1/(PlotPoints PlotDivision). See page 138. See also: MaxBend. New in Version 1.
PlotJoined
PlotJoined is an option for ListPlot that specifies whether the points plotted should be
joined by a line.
The style of the line can be specified using the option PlotStyle.
Version 1.
New in
PlotLabel
PlotLabel is an option for graphics functions that specifies an overall label for a plot.
PlotLabel -> None specifies that no label should be given. PlotLabel -> label specifies a label to give. Any
expression can be used as a label. It will be given in OutputForm. Arbitrary strings of text can be given as "text".
See page 511. See also: AxesLabel. Related package: Graphics`Legend` . New in Version 1.
PlotPoints
PlotPoints is an option for plotting functions that specifies how many sample points to use.
The sample points are equally spaced. In Plot, an adaptive procedure is used to choose more sample points.
With a single variable, PlotPoints -> n specifies the total number of sample points to use. With two variables,
PlotPoints -> n specifies that n points should be used in both x and y directions. PlotPoints -> {nx , ny }
specifies different numbers of sample points for the x and y directions. See page 138. See also: PlotDivision.
New in Version 1.
PlotRange
PlotRange is an option for graphics functions that specifies what points to include in a plot.
PlotRange can be used for both two- and three-dimensional graphics.
All
Automatic
{min, max}
{{xmin, xmax}, . . . }
When no explicit limits are given for a particular coordinate, a setting of Automatic is assumed. With the
Automatic setting, the distribution of coordinate values is found, and any points sufficiently far out in the
distribution are dropped. Such points are often produced as a result of singularities in functions being plotted. A
setting of the form {min, Automatic} specifies a particular minimum value for a coordinate, and a maximum
value to be determined automatically. AbsoluteOptions gives the explicit form of PlotRange specifications when
Automatic settings are given. See page 137. See also: PlotRegion, AspectRatio, AbsoluteOptions . New in
Version 1.
PlotRegion Point
1244
PlotRegion
PlotRegion is an option for graphics functions that specifies what region of the final display
area a plot should fill.
PlotRegion -> {{sxmin, sxmax}, {symin, symax}} specifies the region in scaled coordinates that the plot should
fill in the final display area. The scaled coordinates run from 0 to 1 in each direction. The default setting
PlotRegion -> {{0, 1}, {0, 1}} specifies that the plot should fill the whole display area. When the plot does
not fill the whole display area, the remainder of the area is rendered according to the setting for the option
Background. See page 507. See also: PlotRange, AspectRatio, Scaled, SphericalRegion. New in Version 2.
PlotStyle
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. PlotStyle -> {{style }, {style }, . . . } specifies that successive lines generated should use
graphics directives style , . . . . The styles must be enclosed in lists, perhaps of length one. The stylei are used
cyclically. Styles can be specified using graphics directives such as Dashing, Hue and Thickness. See pages 138
and 503. See also: Graphics, TextStyle. New in Version 1.
Plus
x + y + z represents a sum of terms.
Plus has attributes Flat, Orderless and OneIdentity. The default value for arguments of Plus, as used in x_.
patterns, is 0. Plus[ ] is taken to be 0. Plus[x] is x. x + 0 evaluates to x, but x + 0.0 is left unchanged.
Unlike other functions, Plus applies built-in rules before user-defined ones. As a result, it is not possible to make
definitions such as 2+2=5. See page 29. See also: Minus, Subtract, AddTo, Increment, Total. New in Version 1;
modified in Version 3.
Pochhammer
Pochhammer[a, n] gives the Pochhammer symbol an .
Mathematical function (see Section A.3.10). an aa a n a na. See page 770. See also:
Beta, Binomial, Gamma, Factorial, Hypergeometric0F1 , Hypergeometric1F1 , Hypergeometric2F1 . New in
Version 1.
Point
Point[coords] is a graphics primitive that represents a point.
The coordinates can be given either in the ordinary form {x, y} or {x, y, z} or in scaled form Scaled[{x, y}] or
Scaled[{x, y, z}]. Offset can be used to specify coordinates in two dimensions. Points are rendered if
possible as circular regions. Their diameters can be specified using the graphics primitive PointSize. Point
diameters are not accounted for in hidden surface elimination for three-dimensional graphics. Shading and
coloring of points can be specified using CMYKColor, GrayLevel, Hue or RGBColor. See pages 492 and 520. See
also: Text. New in Version 1; modified in Version 3.
PointSize PolygonIntersections
1245
PointSize
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.
PointSize can be used in both two- and three-dimensional graphics. The initial default is PointSize[0.008] for
two-dimensional graphics, and PointSize[0.01] for three-dimensional graphics. See page 500. See also:
AbsolutePointSize , Thickness. New in Version 1.
PolyGamma
PolyGamma[z] gives the digamma function z.
PolyGamma[n, z] gives the nth derivative of the digamma function n z.
PolyGamma[z] is the logarithmic derivative of the gamma function, given by z $ zz. PolyGamma[n, z] is
given by n z dn zdzn . The digamma function is z z; n z is the n th logarithmic derivative
of the gamma function. PolyGamma[z] and PolyGamma[n, z] are meromorphic functions of z with no branch cut
discontinuities. FullSimplify and FunctionExpand include transformation rules for PolyGamma. See page 770.
Implementation notes: see page 1068. See also: Gamma, LogGamma, EulerGamma. New in Version 1.
Polygon
Polygon[{pt , pt , ... }] is a graphics primitive that represents a filled polygon.
Polygon can be used in both Graphics and Graphics3D (two- and three-dimensional graphics). The positions of
points can be specified either in ordinary coordinates as {x, y} or {x, y, z}, or in scaled coordinates as
Scaled[{x, y}] or Scaled[{x, y, z}]. Offset can be used to specify coordinates in two dimensions. The
boundary of the polygon is formed by joining the last point you specify to the first one. In two dimensions,
self-intersecting polygons are allowed. In three dimensions, planar polygons that do not intersect themselves will
be drawn exactly as you specify them. Other polygons will be broken into triangles. You can use graphics
directives such as GrayLevel and RGBColor to specify how polygons should be filled. In three dimensions, the
shading can be produced from simulated illumination. In three-dimensional graphics, polygons are considered to
have both a front and a back face. The sense of a polygon is defined in terms of its first three vertices. When taken
in order, these vertices go in a counterclockwise direction when viewed from the front. (The frontward normal is thus
obtained from a right-hand rule.) You can use FaceForm to specify colors for the front and back faces of polygons.
In three-dimensional graphics, edges of polygons are shown as lines, with forms specified by the graphics
directive EdgeForm. See pages 492 and 520. See also: Raster, Rectangle, Cuboid, SurfaceColor . Related
packages: Geometry`Polytopes` , Graphics`Polyhedra` . New in Version 1; modified in Version 3.
PolygonIntersections
PolygonIntersections is an option for Graphics3D which specifies whether intersecting
polygons should be left unchanged.
With the default setting PolygonIntersections -> True, Graphics3D objects are returned unchanged whether or
not they contain intersecting polygons. With the setting PolygonIntersections -> False, Graphics3D objects are
modified by breaking polygons into smaller pieces which do not intersect each other.
PolygonIntersections -> False is useful in creating graphics objects which can be sent to certain external
three-dimensional rendering programs. See page 556. See also: RenderAll. New in Version 2.
PolyLog PolynomialQ
1246
PolyLog
PolyLog[n, z] gives the polylogarithm function Lin z.
PolyLog[n, p, z] gives the Nielsen generalized polylogarithm function Snp z.
Mathematical function (see Section A.3.10).
dpd
k n
Lin z
k z k .
PolynomialGCD
PolynomialGCD[poly , poly , ... ] gives the greatest common divisor of the polynomials polyi .
PolynomialGCD[poly , poly , ... , Modulus->p] evaluates the GCD modulo the prime p.
Example: PolynomialGCD[1 + x y, x + x^2 y] # 1 x y . In PolynomialGCD[poly , poly , . . . ], all symbolic
parameters are treated as variables. PolynomialGCD[poly , poly , . . . ] will by default treat algebraic numbers that
appear in the polyi as independent variables. PolynomialGCD[poly , poly , . . . , Extension->Automatic] extends
the coefficient field to include algebraic numbers that appear in the polyi . See page 803. See also:
PolynomialLCM, PolynomialQuotient , GCD, Cancel, Together, PolynomialMod. Related package:
Algebra`PolynomialExtendedGCD` . New in Version 2; modified in Version 3.
PolynomialLCM
PolynomialLCM[poly , poly , ... ] gives the least common multiple of the polynomials polyi .
PolynomialLCM[poly , poly , ... , Modulus->p] evaluates the LCM modulo the prime p.
Example: PolynomialLCM[1 + x y, x + x^2 y] # x x2 y . PolynomialLCM[poly , poly , . . . ] will by default
treat algebraic numbers that appear in the polyi as independent variables.
PolynomialLCM[poly , poly , . . . , Extension->Automatic] extends the coefficient field to include algebraic
numbers that appear in the polyi . See page 803. See also: PolynomialGCD, LCM. New in Version 2; modified in
Version 3.
PolynomialMod
PolynomialMod[poly, m] gives the polynomial poly reduced modulo m.
PolynomialMod[poly, {m , m , ... }] reduces modulo all of the mi .
PolynomialMod[poly, m] for integer m gives a polynomial in which all coefficients are reduced modulo m.
Example: PolynomialMod[3x^2 + 2x + 1, 2] # 1 x2 . When m is a polynomial, PolynomialMod[poly, m]
reduces poly by subtracting polynomial multiples of m, to give a result with minimal degree and leading coefficient.
PolynomialMod gives results according to a definite convention; other conventions could yield results differing by
multiples of m. Unlike PolynomialRemainder , PolynomialMod never performs divisions in generating its results.
See page 803. See also: PolynomialGCD , Mod, PolynomialRemainder , PolynomialReduce , GroebnerBasis .
Related package: Algebra`PolynomialPowerMod` . New in Version 2.
PolynomialQ
PolynomialQ[expr, var] yields True if expr is a polynomial in var, and yields False otherwise.
PolynomialQ[expr, {var , ... }] tests whether expr is a polynomial in the vari .
The vari need not be symbols; PolynomialQ[f[a] + f[a]^2, f[a]] # True .
Collect, Series. New in Version 1.
See also:
PolynomialQuotient Positive
1247
PolynomialQuotient
PolynomialQuotient[p, q, x] gives the quotient of p and q, treated as polynomials in x, with
any remainder dropped.
See page 803. See also: PolynomialRemainder , PolynomialReduce, PolynomialGCD, Apart, Cancel, Quotient.
New in Version 1.
PolynomialReduce
PolynomialReduce[poly, {poly , poly , ... }, {x , x , ... }] yields a list representing a
reduction of poly in terms of the polyi .
The list has the form {{a , a , ... }, b}, where b is minimal and a poly + a poly + ... + b is
exactly poly.
The polynomial b has the property that none of its terms are divisible by leading terms of any of the polyi . If the
polyi form a Grobner
basis then this property uniquely determines the remainder obtained from PolynomialReduce.
The following options can be given, as for GroebnerBasis:
MonomialOrder
CoefficientDomain
Modulus
Lexicographic
Rationals
0
Related package:
PolynomialRemainder
PolynomialRemainder[p, q, x] gives the remainder from dividing p by q, treated as
polynomials in x.
The degree of the result in x is guaranteed to be smaller than the degree of q. Unlike PolynomialMod,
PolynomialRemainder performs divisions in generating its results. See page 803. See also: PolynomialQuotient ,
Apart, Cancel, PolynomialMod , Mod, PolynomialReduce . New in Version 1.
Position
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.
Position[expr, pattern, levspec, n] gives the positions of the first n objects found.
Example: Position[{1+x^2, 5, x^4}, x^_] # 1, 2, 3 . Position[expr, pattern] tests all the subparts
of expr in turn to try and find ones that match pattern. Position returns a list of positions in a form suitable for
use in Extract, ReplacePart and MapAt. The form is different from the one used in Part. The default level
specification for Position is {0, Infinity}, with Heads -> True. A part specification {} returned by Position
represents the whole of expr. Position[list, pattern, {1}, Heads -> False] finds positions only of objects that
appear as complete elements of list. Level specifications are described on page 1041. See page 261. See also:
Cases, Count, StringPosition , Ordering, SparseArray, ReplaceList, Insert, Delete. New in Version 1.
Positive
Positive[x] gives True if x is a positive number.
Positive[x] gives False if x is manifestly a negative numerical quantity, a complex numerical quantity, or zero.
Otherwise, it remains unevaluated. See also: Negative, NonNegative, Sign, Greater, Simplify, Assumptions.
New in Version 1.
Postfix PowerMod
1248
Postfix
Postfix[f [expr]] prints with f [expr] given in default postfix form: expr // f.
Postfix[f [expr], h] prints as exprh.
Postfix[expr, h, precedence, grouping] can be used to specify how the output form should be parenthesized. See
the notes for Infix about precedence and grouping. See page 474. See also: Infix, Prefix. New in Version 1.
PostScript
PostScript["string"] is a graphics primitive which gives PostScript code to include verbatim
in graphics output.
Mathematica by default renders a point with coordinates 0 0 in the PostScript code at the bottom left-hand corner of
your plot, and a point with coordinates 1 r at the top right-hand corner, where r is the aspect ratio of the whole
plot. You can specify a bounding box for the objects represented by your PostScript code by including a standard
conforming PostScript comment of the form %%BoundingBox pxmin pymin pxmax pymax.
PostScript["string", {{xmin, ymin}, {xmax, ymax}}] then renders the point with coordinates pxmin pymin in
the PostScript code at position {xmin, ymin} in the Mathematica graphic, and the point with coordinates
pxmax pymax at position {xmax, ymax}. Mathematica will transform graphics represented by a PostScript
command to make it fill the specified rectangle. After execution of PostScript code included by the PostScript
command, all PostScript stacks must be restored to their original states. The utility of the PostScript command
depends on your PostScript interpreters ability to process the PostScript commands you specify. Display may or
may not convert graphics produced by PostScript commands to other formats. See page 554. See also: Raster,
RGBColor, Dashing, Thickness, PointSize, StyleForm. New in Version 2; modified in Version 3.
Power
x^y gives x to the power y.
Mathematical function (see Section A.3.10). Exact rational number results are given when possible for roots of the
form nm . For complex numbers x and y, Power gives the principal value of ey logx . (a b)^c is automatically
converted to a^c b^c only if c is an integer. (a^b)^c is automatically converted to a^(b c) only if c is an integer.
See page 29. See also: Sqrt, Exp, PowerExpand, PowerMod, Log. New in Version 1.
PowerExpand
PowerExpand[expr] expands all powers of products and powers.
Example: PowerExpand[Sqrt[x y]] # x y . PowerExpand converts (a b)^c to a^c b^c, whatever the form of
c is. PowerExpand also converts (a^b)^c to a^(b c), whatever the form of c is. The transformations made by
PowerExpand are correct in general only if c is an integer or a and b are positive real numbers. PowerExpand
converts Log[a^b] to b Log[a]. See page 798. See also: Expand, Distribute, ComplexExpand , FullSimplify,
FunctionExpand , Refine. New in Version 2; modified in Version 3.
PowerMod
PowerMod[a, b, n] gives ab mod n.
For negative b, PowerMod[a, b, n] gives modular inverses.
Integer mathematical function (see Section A.3.10). For positive b, PowerMod[a, b, n] gives the same answers as
Mod[a^b, n] but is much more efficient. For negative b, PowerMod[a, b, n] gives the integer k such that
kab Q mod n. If no such integer exists, PowerMod returns unevaluated. See page 752. See also: Mod,
ExtendedGCD, MultiplicativeOrder , EulerPhi. Related package: Algebra`PolynomialPowerMod` . New in
Version 1.
PrecedenceForm PreIncrement
1249
PrecedenceForm
PrecedenceForm[expr, prec] prints with expr parenthesized as it would be if it contained an
operator with precedence prec.
prec must be an integer. See notes for Infix. Example: a + PrecedenceForm[b c, 10] # a b c .
PrecedenceForm acts as a wrapper, which affects printing, but not evaluation. See page 474. New in
Version 1.
-
Precision
Precision[x] gives the effective number of digits of precision in the number x.
Precision[x] gives a measure of the relative uncertainty in the value of x. , With absolute uncertainty dx,
Precision[x] is -Log[10, dx/x]. For exact numbers such as integers, Precision[x] is Infinity.
, Precision[x] does not normally yield an integer result. , For machine-precision numbers Precision[x] yields
MachinePrecision. , Numbers entered in the form digits`p are taken to have precision p. , Numbers such as
0``a whose overall scale cannot be determined are treated as having zero precision. , Numbers with zero
precision are output in StandardForm as a , where a is their accuracy. If x is not a number, Precision[x]
gives the minimum value of Precision for all the numbers that appear in x. See page 727. See also: Accuracy,
N, Chop, SetPrecision , MachineNumberQ . New in Version 1; modified in Version 5.0.
,
PrecisionGoal
PrecisionGoal is an option for various numerical operations which specifies how many
effective digits of precision should be sought in the final result.
PrecisionGoal is an option for such functions as NIntegrate and NDSolve. - PrecisionGoal -> Automatic
normally yields a precision goal equal to half the setting for WorkingPrecision . PrecisionGoal -> Infinity
specifies that precision should not be used as the criterion for terminating the numerical procedure. AccuracyGoal
is typically used in this case. Even though you may specify PrecisionGoal->n, the results you get may
sometimes have much less than n-digit precision. In most cases, you must set WorkingPrecision to be at least as
large as PrecisionGoal. PrecisionGoal effectively specifies the relative error allowed in a numerical procedure.
With PrecisionGoal->p and AccuracyGoal->a, Mathematica attempts to make the numerical error in a result of
size x be less than a /x/ p . See pages 956 and 976. See also: AccuracyGoal, WorkingPrecision. New in
Version 2; modified in Version 5.0.
PreDecrement
--x decreases the value of x by 1, returning the new value of x.
PreDecrement has attribute HoldFirst.
SubtractFrom, Set. New in Version 1.
Prefix
Prefix[f [expr]] prints with f [expr] given in default prefix form: f @ expr.
Prefix[f [expr], h] prints as hexpr.
Prefix[expr, h, precedence, grouping] can be used to specify how the output form should be parenthesized. See
the notes for Infix about precedence and grouping. See page 474. See also: Infix, Postfix. New in Version 1.
PreIncrement
++x increases the value of x by 1, returning the new value of x.
PreIncrement has attribute HoldFirst.
Set. New in Version 1.
Prepend Primes
1250
Prepend
Prepend[expr, elem] gives expr with elem prepended.
Examples: Prepend[{a,b}, x] # x, a, b ; Prepend[f[a], x+y] # f
x y, a . , Prepend works on
SparseArray objects, returning ordinary lists if necessary. See pages 125 and 288. See also: Append, Insert,
PadRight. New in Version 1.
PrependTo
PrependTo[s, elem] prepends elem to the value of s, and resets s to the result.
PrependTo[s, elem] is equivalent to s = Prepend[s, elem]. PrependTo[s, elem] does not evaluate s. - You can
use PrependTo repeatedly to build up a list, though Sow and Reap will usually be more efficient. , PrependTo
works on SparseArray objects, returning ordinary lists if necessary. See page 306. See also: AppendTo, Sow.
New in Version 1.
Prime
Prime[n] gives the nth prime number.
Prime[1] is 2. On most computer systems, Prime[n] for n up to can be obtained quite quickly. See
page 750. Implementation notes: see page 1067. See also: FactorInteger, PrimeQ, PrimePi, Primes. Related
package: NumberTheory`NumberTheoryFunctions` . New in Version 1.
PrimePi
PrimePi[x] gives the number of primes x less than or equal to x.
The argument of PrimePi can be any positive real number. PrimePi[1] gives 0. See page 750.
Implementation notes: see page 1067. See also: Prime, Zeta. New in Version 2.
PrimeQ
PrimeQ[expr] yields True if expr is a prime number, and yields False otherwise.
PrimeQ[1] gives False. PrimeQ[-n], where n is prime, gives True. PrimeQ[n, GaussianIntegers->True]
determines whether n is a Gaussian prime. , PrimeQ[m + I m] automatically works over the Gaussian integers.
Simplify[expr Primes] can be used to try to determine whether a symbolic expression is mathematically a
prime. See page 750. Implementation notes: see page 1067. See also: FactorInteger, Primes. Related
package: NumberTheory`PrimeQ` . New in Version 1.
Primes
Primes represents the domain of prime numbers, as in x Primes.
x Primes evaluates only if x is a numeric quantity. Simplify[expr Primes] can be used to try to determine
whether an expression corresponds to a prime number. The domain of primes is taken to be a subset of the
domain of integers. PrimeQ[expr] returns False unless expr explicitly has head Integer. Primes is output in
TraditionalForm as . See pages 73 and 817. See also: Element, Simplify, PrimeQ, Prime, Integers. New in
Version 4.
PrincipalValue Product
1251
PrincipalValue
PrincipalValue is an option for Integrate that specifies whether the Cauchy principal value
should be found for a definite integral.
The default setting PrincipalValue->False computes ordinary Riemann integrals. Setting PrincipalValue->True
gives finite answers for integrals that had single pole divergences with PrincipalValue->False . See page 866.
See also: Residue, Limit, GenerateConditions , DiracDelta. Related package:
NumericalMath`CauchyPrincipalValue` . New in Version 3.
Print
Print[expr , expr , ... ] prints the expri , followed by a newline (line feed).
Print sends its output to the channel $Output. Print uses the format type of $Output as its default format type.
Print concatenates the output from each expri together, effectively using SequenceForm. You can arrange to
have expressions on several lines by using ColumnForm. See page 477. See also: CellPrint, Message, Put,
Write, Reap. New in Version 1.
PrintingStyleEnvironment
PrintingStyleEnvironment is an option for notebooks which specifies the style environment
to be used in printing the notebook on paper.
See notes for ScreenStyleEnvironment . Style environments appropriate for printed output are typically
substantially denser than those appropriate for on-screen display. See page 197. See also:
ScreenStyleEnvironment , StyleDefinitions , NotebookPrint . New in Version 3.
Product
Product[f, {i, imax}] evaluates the product imax
i 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 product
jmax
imax
iimin jjmin f.
f.
Product[f, {i, imax}] can be entered as *imax
i
ProductLog PseudoInverse
1252
ProductLog
ProductLog[z] gives the principal solution for w in z wew .
ProductLog[k, z] gives the kth solution.
Mathematical function (see Section A.3.10). The solutions are ordered according to their imaginary parts. For
z c e, ProductLog[z] is real. ProductLog[z] satisfies the differential equation dwdz wz w.
ProductLog[z] has a branch cut discontinuity in the complex z plane running from to e.
ProductLog[k, z] for integer k c has a branch cut discontinuity from to . See page 781. See also: Log.
New in Version 3.
Prolog
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.
Graphics primitives specified by Prolog are rendered after axes, boxes and frames are rendered. In
three-dimensional graphics, two-dimensional graphics primitives can be specified by the Prolog option. The
graphics primitives are rendered in a 0,1 coordinate system. See page 504. See also: Background, DefaultColor,
Epilog, AxesStyle, PlotStyle, DisplayFunction. New in Version 2.
Protect
Protect[s , s , ... ] sets the attribute Protected for the symbols si .
Protect["form ", "form ", ... ] protects all symbols whose names match any of the string
patterns formi .
Protect["form"] allows metacharacters such as *, as specified on page 1044. Protect["context`*"] protects all
symbols in a particular context. See pages 321 and 1044. See also: Unprotect. New in Version 1.
Protected
Protected is an attribute which prevents any values associated with a symbol from being
modified.
Many built-in Mathematica functions have the attribute Protected.
ReadProtected, Editable. New in Version 1.
-
PseudoInverse
PseudoInverse[m] finds the pseudoinverse of a rectangular matrix.
PseudoInverse works on both symbolic and numerical matrices. , For numerical matrices, PseudoInverse is based
on SingularValueDecomposition . PseudoInverse[m, Tolerance -> t] specifies that singular values smaller
than t times the maximum singular value should be dropped. With the default setting Tolerance->Automatic ,
singular values are dropped when they are less than 100 times p , where p is Precision[m]. For non-singular
square matrices M, the pseudoinverse M is equivalent to the standard inverse. See page 914. See also:
Inverse, SingularValueDecomposition , Fit, CholeskyDecomposition . New in Version 1; modified in Version 5.0.
Put Quantile
1253
Put
expr >> filename writes expr to a file.
PutAppend
expr >>> filename appends expr to a file.
PutAppend[expr , expr , ... , "filename"] appends a sequence of expressions expri to a file.
PutAppend works the same as Put, except that it adds output to the end of the file, rather than replacing the
complete contents of the file. See page 624. See also: Write. New in Version 1.
QRDecomposition
QRDecomposition[m] yields the QR decomposition for a numerical matrix m. The result is a
list {q, r}, where q is an orthogonal matrix and r is an upper triangular matrix.
The original matrix m is equal to Conjugate[Transpose[q]] . r. For non-square matrices, q is row orthonormal.
The matrix r has zeros for all entries below the leading diagonal. QRDecomposition[m, Pivoting -> True]
yields a list {q, r, p} where p is a permutation matrix such that m . p is equal to Conjugate[Transpose[q]] . r.
See page 914. Implementation notes: see page 1069. See also: SchurDecomposition , LUDecomposition ,
SingularValueDecomposition , JordanDecomposition , CholeskyDecomposition . Related package:
LinearAlgebra`Orthogonalization` . New in Version 2.
,
Quantile
Quantile[list, q] gives the qth quantile of list.
Quantile[list, {q , q , ... }] gives a list of quantiles q , q , ... .
Quantile[list, q, {{a, b}, {c, d}}] uses the quantile definition specified by parameters a, b,
c, d.
Quantile[list, q] gives Sort[list, Less][[Ceiling[q Length[list]]]] .
Quantile[{{x , y , . . . }, {x , y , . . . }, . . . }, q] gives
{Quantile[{x , x , . . . }, q], Quantile[{y , y , . . . }, q]}. For a list of length n,
Quantile[list, q, {{a, b}, {c, d}}] depends on x = a + (n + b) q. If x is an integer, the result is s[[x]], where
s = Sort[list, Less]. Otherwise the result is
s[[Floor[x]]] + (s[[Ceiling[x]]] - s[[Floor[x]]]) (c + d FractionalPart[x]) , with the indices taken to be 1
or n if they are out of range. The default choice of parameters is {{0, 0}, {1, 0}}. Quantile[list, q] always
gives a result equal to an element of list. The same is true whenever d . When d , Quantile is piecewise
linear as a function of q. Median[list] is equivalent to Quantile[list, 1/2, {{1/2, 0}, {0, 1}}]. About ten
different choices of parameters are in use in statistical work. Quantile works with SparseArray objects. See
pages 794 and 924. See also: Median, Ordering, Variance, Sort, ListInterpolation . Related packages:
Statistics`DescriptiveStatistics` , Statistics`MultiDescriptiveStatistics` . New in Version 5.0.
Quit Random
1254
Quit
Quit[ ] terminates a Mathematica kernel session.
Quit[ ] quits only the Mathematica kernel, not the front end. , To quit a notebook front end, choose the Quit
menu item. All kernel definitions are lost when the kernel session terminates. If you have kept the definitions in
a file or in a notebook you can always re-enter them in a subsequent session. Before terminating a kernel session,
Mathematica executes any delayed value that has been assigned to the global variable $Epilog. Conventionally, this
attempts to read in a file end.m of commands to be executed before termination. On most computer systems,
Quit[n] terminates the Mathematica kernel, passing the integer n as an exit code to the operating system. Exit is
a synonym for Quit. See pages 706 and 1057. See also: Return, $IgnoreEOF. New in Version 1.
,
Quotient
Quotient[m, n] gives the integer quotient of m and n.
Quotient[m, n, d] uses an offset d.
Integer mathematical function (see Section A.3.10). Quotient[m, n] is equivalent to Floor[m/n] for integers m
and n. Quotient[m, n, d] gives a result x such that d * m nx ) d n. n*Quotient[m, n, d] + Mod[m, n, d]
is always equal to m. See page 749. See also: Mod, PolynomialQuotient . New in Version 1; modified in
Version 4.
RadicalBox
RadicalBox[x, n] represents
n
x in input and output.
Inside \( . . . \) RadicalBox[x, n] can be input as \@x\%n. In a notebook a RadicalBox can be created using
@ or 2 , then using % to move to the index position. moves out of the radical. In
StandardForm and InputForm, RadicalBox[x, n] is interpreted on input as x^(1/n). The baseline of
RadicalBox[x, n] is taken to be the baseline of x. If RadicalBox[x, n] does not fit on a single line, it is output
as x ^ (1/n). In StandardForm, explicit RadicalBox objects are output literally. You can use DisplayForm to see
the display form of such objects. See page 445. See also: SqrtBox, OverscriptBox , GridBox. New in Version 3.
Random
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[Integer] gives 0 or 1 with probability . Random[Complex] gives a pseudorandom complex number in
the rectangle with corners and i. Random[Complex, {zmin, zmax}] uses the rectangle defined by zmin and
zmax. Random[Real, range, n] generates a pseudorandom real number with n-digit precision. Both leading and
trailing digits may be chosen as 0. Random gives a different sequence of pseudorandom numbers whenever you
run Mathematica. You can start Random with a particular seed using SeedRandom. See page 747. Implementation
notes: see page 1067. See also: $RandomState, FindInstance . Related packages:
Statistics`ContinuousDistributions` , Statistics`DiscreteDistributions` . New in Version 1.
Range Rational
1255
Range
Range[imax] generates the list {1, 2, ... , imax}.
Range[imin, imax] generates the list {imin, ... , imax}. Range[imin, imax, di] uses step di.
Example: Range[4] # 1, 2, 3, 4 . The arguments to Range need not be integers. Range starts from imin,
and successively adds increments of di until the result is greater than imax.
Range[0, 1, .3] # 0, 0.3, 0.6, 0.9 . Range[x, x+2] # x, 1 x, 2 x . Range uses the standard
Mathematica iteration specification, as applied to a single variable. See page 119. See also: Table, Interval,
CharacterRange. New in Version 1.
Raster
Raster[{{a , a , ... }, ... }] is a two-dimensional graphics primitive which represents a
rectangular array of gray cells.
Raster[array, ColorFunction -> f] specifies that each cell should be rendered using the graphics directives
obtained by applying the function f to the scaled value of the cell. Raster[array, ColorFunction -> Hue]
generates an array in which cell values are specified by hues. With the option ColorFunctionScaling -> False
the original cell values aij , rather than scaled cell values, are fed to the color function. With the default setting
ColorFunctionScaling -> True cell values in Raster[array] outside the range 0 to 1 are clipped. If array has
dimensions {m, n}, then Raster[array] is assumed to occupy the rectangle Rectangle[{0, 0}, {m, n}].
Raster[array, {{xmin, ymin}, {xmax, ymax}}] specifies that the raster should be taken instead to fill the
rectangle Rectangle[{xmin, ymin}, {xmax, ymax}]. Scaled and Offset can be used to specify the coordinates
for the rectangle. Raster[array, rect, {zmin, zmax}] specifies that cell values should be scaled so that zmin
corresponds to 0 and zmax corresponds to 1. Cell values outside this range are clipped. , array can be a
SparseArray object. See page 497. See also: RasterArray, DensityGraphics , GraphicsArray . New in
Version 2; modified in Version 4.
RasterArray
RasterArray[{{g , g , ... }, ... }] is a two-dimensional graphics primitive which
represents a rectangular array of cells colored according to the graphics directives gij .
Each of the gij must be GrayLevel, RGBColor or Hue. If array has dimensions {m, n}, then RasterArray[array]
is assumed to occupy the rectangle Rectangle[{0, 0}, {m, n}].
RasterArray[array, {{xmin, ymin}, {xmax, ymax}}] specifies that the raster should be taken instead to fill the
rectangle Rectangle[{xmin, ymin}, {xmax, ymax}]. Scaled and Offset can be used to specify the coordinates
for the rectangle. See page 497. See also: Raster, GraphicsArray . New in Version 2; modified in Version 3.
Rational
Rational is the head used for rational numbers.
You can enter a rational number in the form n/m. The pattern object _Rational can be used to stand for a
rational number. It cannot stand for a single integer. You have to use Numerator and Denominator to extract
parts of Rational numbers. See page 722. See also: Rationals, Integer, Numerator, Denominator. New in
Version 1.
Rationalize Read
1256
Rationalize
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.
Example: Rationalize[3.78] # 189 50 . Rationalize[x, dx] yields the rational number with the smallest
denominator that lies within dx of x. Rationalize[N[Pi]] # 3.14159 does not give a rational number, since
there is none sufficiently close to N[Pi]. A rational number pq is considered sufficiently close to a Real x if
/pq x/ ) cq , where c is chosen to be
. Rationalize[x, 0] converts any x to rational form. See page 746.
See also: Chop, Round, ContinuedFraction , LatticeReduce. Related package: NumberTheory`Rationalize` .
New in Version 1.
Rationals
Rationals represents the domain of rational numbers, as in x Rationals .
x Rationals evaluates immediately only if x is a numeric quantity. Simplify[expr Rationals] can be used
to try to determine whether an expression corresponds to a rational number. The domain of integers is taken to
be a subset of the domain of rationals. Rationals is output in TraditionalForm as . See page 817. See
also: Element, Simplify, Algebraics, Integers, Rational, Denominator. New in Version 4.
Raw
Raw[h, "hexstring"] constructs a raw data object with head h, and with contents corresponding to
the binary bit pattern represented by the string hexstring, interpreted as a hexadecimal number.
Raw should be used only under very special circumstances. It is possible to crash Mathematica by creating a
fundamental Mathematica data object with Raw, and specifying illegal internal data for it. If you create an object
with head Real, but with internal data incompatible with Mathematica Real numbers, you may end up crashing
your whole Mathematica session. Raw encodes data so that two hexadecimal digits represent one byte. Identical
hexstring may lead to different internal data on different computer systems. You cannot necessarily transport raw
arrays of bytes from one type of computer to another without encountering byte swap incompatibilities. See
page 1016. See also: Run. Related package: Utilities`BinaryFiles` . New in Version 1.
Re
Re[z] gives the real part of the complex number z.
Re[expr] is left unevaluated if expr is not a numeric quantity.
ComplexExpand. New in Version 1.
Read
Read[stream] reads one expression from an input stream, and returns the expression.
Read[stream, type] reads one object of the specified type.
Read[stream, {type , type , ... }] reads a sequence of objects of the specified types.
Possible types to read are:
Byte
Character
Expression
Number
(continued)
Read
1257
(continued)
Real
Record
String
Word
Objects of type Real can be given in the scientific notation format used by languages such as C and Fortran, as
well as in standard Mathematica format. A form like 2.e5 or 2E5 as well as 2*^5 can be used to represent the
number . Objects read as type Real are always returned as approximate numbers. Objects read as type
Number are returned as integers if they contain no explicit decimal points. The following options can be given:
NullRecords
NullWords
RecordSeparators
TokenWords
WordSeparators
False
False
{"\n"}
{}
{" ", "\t"}
Objects of type String must be terminated by newlines ("\n" characters). You can specify any nested list of
types for Read to look for. Each successive object read will be placed in the next position in the list structure. A
depth-first traversal of the list structure is used. Example: Read[stream, {Number, Number}] reads a pair of
numbers from an input stream, and gives the result as a two-element list.
Read[stream, {{Number, Number}, {Number, Number}}] reads a matrix, going through each column, then
each row. You can use Read to get objects to insert into any expression structure, not necessarily a list. Example:
Read[stream, Hold[Expression]] gets an expression and places it inside Hold. The first argument to Read can be
InputStream["name", n], or simply "name" if there is only one open input stream with the specified name. You
can open a file or pipe to get an InputStream object using OpenRead. There is always a current point
maintained for any stream. When you read an object from a stream, the current point is left after the input you
read. Successive calls to Read can therefore be used to read successive objects in a stream such as a file. Read
returns EndOfFile for each object you try to read after you have reached the end of a file. Read returns $Failed
if it cannot read an object of the type you requested. If there is a syntax error in a Mathematica expression that
you try to read, then Read leaves the current point at the position of the error, and returns $Failed. See page 649.
See also: Input, Get, Skip, Find, StringToStream , LinkRead, Import. New in Version 1; modified in Version 3.
ReadList
ReadList["file"] reads all the remaining expressions in a file, and returns a list of them.
ReadList["file", type] reads objects of the specified type from a file, until the end of the file is
reached. The list of objects read is returned.
ReadList["file", {type , type , ... }] reads objects with a sequence of types, until the end of
the file is reached.
ReadList["file", types, n] reads only the first n objects of the specified types.
The option setting RecordLists -> True makes ReadList create separate sublists for objects that appear in
separate records. With the default setting RecordSeparators -> {"\n"}, RecordLists -> True puts objects on
separate lines into separate sublists. The option RecordSeparators gives a list of strings which are taken to
delimit records. ReadList takes the same options as Read, with the addition of RecordLists. If file is not
already open for reading, ReadList opens it, then closes it when it is finished. If the file is already open, ReadList
does not close it at the end. ReadList prints a message if any of the objects remaining in the file are not of the
specified types. ReadList["file", {type , . . . }] looks for the sequence of typei in order. If the end of file is
reached while part way through the sequence of typei , EndOfFile is returned in place of the elements in the
sequence that have not yet been read. ReadList[stream] reads from an open input stream, as returned by
OpenRead. See notes for Read. See page 644. See also: Import, FindList. New in Version 1.
ReadProtected Reals
1258
ReadProtected
ReadProtected is an attribute which prevents values associated with a symbol from being
seen.
Individual values associated with read-protected symbols can be used during evaluation. Definition[f] , ?f, and
related functions give only the attributes for read-protected symbols f. See page 329. See also: Locked,
Protected, Copyable. New in Version 1.
Real
Real is the head used for real (floating-point) numbers.
_Real can be used to stand for a real number in a pattern. You can enter a floating-point number of any length.
You can enter a number in scientific notation by using the form mantissa*^exponent. You can enter a
floating-point number in base b using b^^digits. The base must be less than 36. The letters az or AZ are used in
sequence to stand for digits 10 through 35. Real is also used to indicate an approximate real number in Read.
See page 722. See also: RealDigits, BaseForm, Number, Reals. New in Version 1; modified in Version 3.
RealDigits
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 bn .
RealDigits[x] normally returns a list of digits whose length is equal to Precision[x]. RealDigits[x] and
RealDigits[x, b] normally require that x be an approximate real number, returned for example by N.
RealDigits[x, b, len] also works on exact numbers. - For integers and rational numbers with terminating digit
expansions, RealDigits[x] returns an ordinary list of digits. For rational numbers with non-terminating digit
expansions it yields a list of the form {a , a , . . . , {b , b , . . . }} representing the digit sequence consisting of the
ai followed by infinite cyclic repetitions of the bi . If len is larger than Log[10, b] Precision[x], then remaining
digits are filled in as Indeterminate. RealDigits[x, b, len, n] starts with the digit which is the coefficient of
bn , truncating or padding with zeros as necessary. RealDigits[x, b, len, -1] starts with the digit immediately
to the right of the base-b decimal point in x. The base b in RealDigits[x, b] need not be an integer. For any
real b such that b c , RealDigits[x, b] successively finds the largest integer multiples of powers of b that can be
removed while leaving a non-negative remainder. RealDigits[x] discards the sign of x. FromDigits can be
used as the inverse of RealDigits. See page 725. Implementation notes: see page 1067. See also:
MantissaExponent , IntegerDigits , BaseForm, FromDigits, ContinuedFraction , MultiplicativeOrder . New in
Version 2; modified in Version 4.
Reals
Reals represents the domain of real numbers, as in x Reals.
x Reals evaluates immediately only if x is a numeric quantity. Simplify[expr Reals] can be used to try to
determine whether an expression corresponds to a real number. Within Simplify and similar functions, objects
that satisfy inequalities are always assumed to be real. Reals is output in TraditionalForm as . See pages 73,
817 and 839. See also: Element, Simplify, Real, Integers, Complexes, Algebraics, ComplexExpand,
PowerExpand. New in Version 4.
Reap RecordSeparators
1259
Reap
Reap[expr] gives the value of expr together with all expressions to which Sow has been applied
during its evaluation.
Expressions sown using Sow[e] or Sow[e, tagi ] with different tags are given in different lists.
Reap[expr, patt] reaps only expressions sown with tags that match patt.
Reap[expr, {patt , patt , ... }] puts expressions associated with each of patti in a separate list.
Reap[expr, patt, f] returns {expr, {f[tag , {e , e , ... }], ... }}.
Sow and Reap provide a convenient way to accumulate a list of intermediate results in a computation. Reap
accumulates expressions in the order in which Sow is applied to them. Expressions sown with a particular tag are
collected by the innermost Reap whose pattern matches the tag. Reap[expr] is equivalent to Reap[expr, _].
Reap has attribute HoldFirst. See page 355. See also: Sow, Catch, AppendTo, Print. New in Version 5.0.
Record
Record represents a record in Read, Find and related functions.
The record is delimited by strings in the list given as the setting for RecordSeparators .
Word. Related package: Utilities`BinaryFiles` . New in Version 2.
See also:
RecordLists
RecordLists is an option for ReadList which specifies whether objects from separate records
should be returned in separate sublists.
With the default setting RecordSeparators -> {"\n"}, setting RecordLists -> True makes RecordLists return
objects that appear on different lines in different sublists. With RecordLists -> False, ReadList returns a single
list of all objects it reads. With RecordLists -> True, ReadList returns a list containing a sublist for each record.
See page 644. New in Version 2.
RecordSeparators
RecordSeparators is an option for Read, Find and related functions which specifies the list of
strings to be taken as delimiters for records.
The default setting is RecordSeparators -> {"\n"}. With this setting, each complete line of input is considered as
a record. Strings used as record separators may contain several characters. With the option setting
NullRecords -> False, any number of record separators may appear between any two successive records.
RecordSeparators -> { } specifies that everything is to be included in a single record.
RecordSeparators -> {{lsep , . . . }, {rsep , . . . }} specifies different left and right separators for records. When
there are nested left and right separators, records are taken to be delimited by the innermost balanced pairs of
separators. Example: with RecordSeparators -> {{"<"}, {">"}}, the records aaa and bbb are extracted from
<x<aaa>yyy<<bbb>>> . Text that does not appear between left and right separators is discarded. See page 646.
See also: WordSeparators. New in Version 2.
Rectangle Reduce
1260
Rectangle
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.
Scaled and Offset can be used to specify the coordinates for the rectangle.
Rectangle[Scaled[{xmin, ymin}], Scaled[{xmax, ymax}]] yields a rectangle with corners specified by scaled
coordinates. Any combination of ordinary coordinates, as well as Scaled and Offset, can be used to specify the
corners of the rectangle. Rectangle[{xmin, ymin}, {xmax, ymax}] is equivalent to a suitable Polygon with four
corners. You can use graphics directives such as GrayLevel and RGBColor to specify how
Rectangle[{xmin, ymin}, {xmax, ymax}] should be filled. In
Rectangle[{xmin, ymin}, {xmax, ymax}, graphics], graphics can be any graphics object. The rectangle is taken as
the complete display area in which the graphics object is rendered. When rectangles overlap, their backgrounds
are effectively taken to be transparent. Fonts and absolute size specifications are not affected by the size of the
rectangle in which the graphics are rendered. The options DisplayFunction , ColorOutput and
CharacterEncoding are ignored for graphics objects given inside Rectangle. See page 492. See also: Polygon,
Raster, RasterArray, Cuboid, GraphicsArray. New in Version 1; modified in Version 3.
-
Reduce
- Reduce[expr, vars] reduces the statement expr by solving equations or inequalities for vars
and eliminating quantifiers.
, Reduce[expr, vars, dom] does the reduction over the domain dom. Common choices of dom
are Reals, Integers and Complexes .
,
lhs == rhs
lhs != rhs
lhs > rhs or lhs >= rhs
expr dom
ForAll[x, cond, expr]
Exists[x, cond, expr]
equations
inequations
inequalities
domain specifications
universal quantifiers
existential quantifiers
The result of Reduce[expr, vars] always describes exactly the same mathematical set as expr.
Reduce[{expr , expr , . . . }, vars] is equivalent to Reduce[expr && expr && . . . , vars]. , Reduce[expr, vars]
assumes by default that quantities appearing algebraically in inequalities are real, while all other quantities are
complex. , Reduce[expr, vars, dom] restricts all variables and parameters to belong to the domain dom. , If dom
is Reals, or a subset such as Integers or Rationals, then all constants and function values are also restricted to
be real. , Reduce[expr && vars Reals, vars, Complexes] performs reductions with variables assumed real, but
function values allowed to be complex. , Reduce[expr, vars, Integers] reduces Diophantine equations over the
integers. , Reduce[expr, {x , x , . . . }, . . . ] effectively writes expr as a combination of conditions on x , x , . . . ,
where each condition involves only the earlier xi . , Algebraic variables in expr free of the xi are treated as
independent parameters. , Applying LogicalExpand to the results of Reduce[expr, . . . ] yields an expression of
the form e || e || . . . , where each of the ei can be thought of as representing a separate component in the set
defined by expr. , The ei may not be disjoint, and may have different dimensions. After LogicalExpand, each of
the ei have the form e && e && . . . . , Without LogicalExpand, Reduce by default returns a nested collection of
conditions on the xi , combined alternately by Or and And on successive levels. , When expr involves only
polynomial equations and inequalities over real or complex domains then Reduce can always in principle solve
directly for all the xi . , When expr involves transcendental conditions or integer domains Reduce will often
introduce additional parameters in its results. , When expr involves only polynomial conditions,
Reduce[expr, vars, Reals] gives a cylindrical algebraic decomposition of expr.
,
(continued)
Reduce
1261
(continued)
Reduce can give explicit representations for solutions to all linear equations and inequalities over the integers,
and can solve a large fraction of Diophantine equations described in the literature. , When expr involves only
polynomial conditions over real or complex domains, Reduce[expr, vars] will always eliminate quantifiers, so that
quantified variables do not appear in the result. , The following options can be given:
,
Backsubstitution
Cubics
GeneratedParameters
Modulus
Quartics
False
False
C
0
False
Reduce[expr, {x , x , . . . }, Backsubstitution->True] yields a form in which values from equations generated
for earlier xi are backsubstituted so that the conditions for a particular xi have only minimal dependence on earlier
xi . See page 839. Implementation notes: see page 1070. See also: Solve, FindInstance, Roots, Eliminate,
Resolve, LogicalExpand , ToRules, GroebnerBasis, Simplify. New in Version 1; modified in Version 5.0.
,
Refine
Refine[expr, assum] gives the form of expr that would be obtained if symbols in it were
replaced by explicit numerical expressions satisfying the assumptions assum.
Refine[expr] uses default assumptions specified by any enclosing Assuming constructs.
Example: Refine[Sqrt[x^2], x > 0] # x . Assumptions can consist of equations, inequalities, domain
specifications such as x Integers, and logical combinations of these. Example:
Refine[Sqrt[x^2], x Reals] # Abs
x . Refine can be used on equations, inequalities and domain
specifications. Quantities that appear algebraically in inequalities are always assumed to be real. Refine is one
of the transformations tried by Simplify. Refine has the option Assumptions, with default setting
$Assumptions. Refine[expr, a, Assumptions->b] uses assumptions a && b. See page 815. See also: Simplify,
PowerExpand, Assuming. New in Version 5.0.
ReleaseHold
ReleaseHold[expr] removes Hold, HoldForm, HoldPattern and HoldComplete in expr.
Example: ReleaseHold[{2, Hold[1 + 1]}] # 2, 2 . ReleaseHold removes only one layer of Hold etc.; it
does not remove inner occurrences in nested Hold etc. functions. See page 339. See also: Evaluate. New in
Version 2.
Remove
Remove[symbol , ... ] removes symbols completely, so that their names are no longer
recognized by Mathematica.
Remove["form ", "form ", ... ] removes all symbols whose names match any of the string
patterns formi .
You can use Remove to get rid of symbols that you do not need, and which may shadow symbols in contexts later
on your context path. Remove["form"] allows metacharacters such as *, as specified on page 1044.
Remove["context`*"] removes all symbols in a particular context. Remove does not affect symbols with the
attribute Protected. Once you have removed a symbol, you will never be able to refer to it again, unless you
recreate it. If you have an expression that contains a symbol which you remove, the removed symbol will be
printed as Removed["name"], where its name is given in a string. See pages 395, 403 and 1052. See also: Clear.
New in Version 1.
RenameDirectory Replace
1262
RenameDirectory
RenameDirectory["dir ", "dir "] renames the directory dir to dir .
dir must already exist; dir must not. RenameDirectory sets the modification date for dir to be the same as for
dir . RenameDirectory returns the full new directory name, or $Failed if the directory cannot be renamed. See
page 641. See also: CopyDirectory, CreateDirectory, DeleteDirectory. New in Version 2.
RenameFile
RenameFile["file ", "file "] renames file to file .
file must already exist; file must not. RenameFile sets the modification date for file to be the same as for file .
RenameFile returns the full new file name, or $Failed if the file cannot be renamed. See page 641. See also:
CopyFile, DeleteFile, RenameDirectory . New in Version 2.
RenderAll
RenderAll is an option for Graphics3D which specifies whether or not PostScript should be
generated for all polygons.
When RenderAll->False , PostScript will be generated only for those polygons or parts of polygons which are
visible in the final picture. If RenderAll->True, PostScript is generated for all polygons. The PostScript for
polygons that are further back is given before the PostScript for those in front. If the PostScript is displayed
incrementally, you can see the object being drawn from the back. Setting RenderAll->False will usually lead to
a smaller amount of PostScript code, but may take longer to run. There may be slight differences in the images
obtained with different settings for RenderAll, primarily as a result of different numerical roundoff in the
PostScript code, and the rendering system. See page 555. See also: PolygonIntersections . New in Version 1.
Repeated
p.. is a pattern object which represents a sequence of one or more expressions, each
matching p.
p.. can appear as an argument of any function. It represents any sequence of arguments. All the objects in the
sequence represented by p.. must match p, but the objects need not be identical. The expression p may, but need
not, itself be a pattern object. See pages 277 and 1028. See also: RepeatedNull , BlankSequence. New in
Version 1.
RepeatedNull
p... is a pattern object which represents a sequence of zero or more expressions, each
matching p.
See notes for Repeated.
New in Version 1.
Replace
Replace[expr, rules] applies a rule or list of rules in an attempt to transform the entire
expression expr.
Replace[expr, rules, levelspec] applies rules to parts of expr specified by levelspec.
Examples: Replace[x^2, x^2 -> a] # a . Replace[x + 1, x -> a] # 1 x . The rules must be of the
form lhs -> rhs or lhs :> rhs. A list of rules can be given. The rules are tried in order. The result of the first one
that applies is returned. If none of the rules apply, the original expr is returned. If the rules are given in nested
lists, Replace is effectively mapped onto the inner lists. Thus Replace[expr, {{r , r }, {r , . . . }, . . . }] is
equivalent to {Replace[expr, {r , r }], Replace[expr, {r , . . . }], . . . }. Delayed rules defined with :> can
contain /; conditions. Level specifications are described on page 1041. The default value for levelspec in Replace
is {0}. Replacements are performed to parts specified by levelspec even when those parts have Hold or related
wrappers. Replace takes a Heads option, with default setting Heads -> False. See page 301. See also: Rule,
Set, ReplacePart, ReplaceList, StringReplace, PolynomialReduce . New in Version 1; modified in Version 4.
ReplaceAll ReplaceRepeated
1263
ReplaceAll
expr /. rules applies a rule or list of rules in an attempt to transform each subpart of an
expression expr.
Example: x + 2 /. x -> a # 2 a . ReplaceAll looks at each part of expr, tries all the rules on it, and then
goes on to the next part of expr. The first rule that applies to a particular part is used; no further rules are tried on
that part, or on any of its subparts. ReplaceAll applies a particular rule only once to an expression. Example:
x /. x -> x + 1 # 1 x . See the notes on Replace for a description of how rules are applied to each part of
expr. expr /. rules returns expr if none of the rules apply. See page 299. See also: Rule, Set, MapAll,
ReplaceRepeated, TransformationFunctions . New in Version 1.
ReplaceList
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.
ReplaceList[expr, rules, n] gives a list of at most n results.
When no transformation is possible, ReplaceList returns {}.
See also: Cases, StringPosition, Trace, Position, Split.
ReplacePart
ReplacePart[expr,
new.
ReplacePart[expr,
ReplacePart[expr,
positions by new.
ReplacePart[expr,
npos in new.
Example: ReplacePart[{a, b, c, d}, x, 3] # a, b, x, d . The list of positions used by ReplacePart is in
the same form as is returned by the function Position. ReplacePart[expr, Hold[new], pos, 1] can be used to
replace a part without evaluating it. If pos and npos both specify multiple parts, each part in pos is replaced by
the corresponding part in npos. , ReplacePart can be used on SparseArray objects. See pages 235 and 288.
See also: Part, Extract, MapAt, FlattenAt, Insert, Delete, Sequence, StringReplacePart . New in Version 2;
modified in Version 3.
ReplaceRepeated
expr //. rules repeatedly performs replacements until expr no longer changes.
expr //. rules effectively applies /. repeatedly, until the results it gets no longer change. It performs one
complete pass over the expression using /., then carries out the next pass. You should be very careful to avoid
infinite loops when you use the //. operator. The command x //. x -> x + 1 will, for example, lead to an infinite
loop. ReplaceRepeated takes the option MaxIterations, which specifies the maximum number of times it will
try to apply the rules you give. The default setting is MaxIterations -> 65536. With MaxIterations -> Infinity
there is no limit. See page 300. See also: ReplaceAll, Rule, Set, FixedPoint. New in Version 1.
ResetDirectory Resultant
1264
ResetDirectory
ResetDirectory[ ] resets the current working directory to its previous value.
Successive calls to ResetDirectory yield earlier and earlier current directories. ResetDirectory uses the
directory stack given by DirectoryStack[ ]. ResetDirectory removes the last element from the directory stack,
and makes the second-to-last element current. See page 636. See also: SetDirectory, Directory, $Path. New
in Version 2.
Residue
Residue[expr, {x, x }] finds the residue of expr at the point x x .
The residue is defined as the coefficient of (x - x )^-1 in the Laurent expansion of expr. Mathematica can usually
find residues at a point only when it can evaluate power series at that point. See page 895. See also: Series,
Limit, PrincipalValue . Related package: Algebra`RootIsolation` . New in Version 2.
,
Resolve
Resolve[expr] attempts to resolve expr into a form that eliminates ForAll and Exists
quantifiers.
Resolve[expr, dom] works over the domain dom. Common choices of dom are Complexes ,
Reals and Booleans .
Resolve is in effect automatically applied by Reduce. expr can contain equations, inequalities, domain
specifications and quantifiers, in the same form as in Reduce. The result of Resolve[expr] always describes
exactly the same mathematical set as expr, but without quantifiers. Resolve[expr] assumes by default that
quantities appearing algebraically in inequalities are real, while all other quantities are complex. When a
quantifier such as ForAll[x, . . . ] is eliminated the result will contain no mention of the localized variable x.
Resolve[expr] can in principle always eliminate quantifiers if expr contains only polynomial equations and
inequalities over the reals or complexes. See page 848. Implementation notes: see page 1070. See also: Reduce,
FindInstance, Exists, ForAll. New in Version 5.0.
Rest
Rest[expr] gives expr with the first element removed.
Example: Rest[{a, b, c}] # b, c . Rest[expr] is equivalent to Drop[expr, 1].
Most, Drop, First, Part, Take. New in Version 1.
See also:
Resultant
Resultant[poly , poly , var] computes the resultant of the polynomials poly and poly with
respect to the variable var.
Resultant[poly , poly , var, Modulus->p] computes the resultant modulo the prime p.
The resultant of two polynomials a and b, both with leading coefficient one, is the product of all the differences
ai bj between roots of the polynomials. The resultant is always a number or a polynomial. See page 803. See
also: Subresultants, PolynomialGCD , Eliminate. New in Version 1.
Return Root
1265
Return
Return[expr] returns the value expr from a function.
Return[ ] returns the value Null.
Return[expr] exits control structures within the definition of a function, and gives the value expr for the whole
function. Return takes effect as soon as it is evaluated, even if it appears inside other functions. Return can be
used inside functions like Scan. See page 353. See also: Break, Throw, Abort. New in Version 1.
Reverse
Reverse[expr] reverses the order of the elements in expr.
Example: Reverse[{a, b, c}] # c, b, a . , Reverse works on SparseArray objects, reversing the elements
in the corresponding ordinary array. See page 127. See also: Permutations, RotateLeft, RotateRight,
StringReverse. New in Version 1.
RGBColor
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.
Red, green and blue color intensities outside the range 0 to 1 will be clipped. On monochrome displays, a gray
level based on the average of the color intensities is used. See page 499. See also: Hue, GrayLevel, CMYKColor,
ColorOutput. Related package: Graphics`Colors` . New in Version 1.
RiemannSiegelTheta
RiemannSiegelTheta[t] gives the Riemann-Siegel function it.
Mathematical function (see Section A.3.10). it Imelog
i t t log f for real t. it arises in the study of
the Riemann zeta function on the critical line. It is closely related to the number of zeros of iu for ) u ) t.
it is an analytic function of t except for branch cuts on the imaginary axis running from Mi to Mi. See
page 772. See also: RiemannSiegelZ , Zeta. New in Version 2.
RiemannSiegelZ
RiemannSiegelZ[t] gives the Riemann-Siegel function Zt.
Mathematical function (see Section A.3.10). Zt e ii t it, where i is the Riemann-Siegel theta function, and
is the Riemann zeta function. Zt it for real t. Zt is an analytic function of t except for branch
cuts on the imaginary axis running from Mi to Mi. See page 772. See also: RiemannSiegelTheta , Zeta.
New in Version 2.
Root
Root[f, k] represents the kth root of the polynomial equation f [x] == 0.
f must be a Function object such as (#^5 - 2 # + 1)&. Root[f, k] is automatically reduced so that f has the
smallest possible degree and smallest integer coefficients. The ordering used by Root takes real roots to come
before complex ones, and takes complex conjugate pairs of roots to be adjacent. The coefficients in the polynomial
f [x] can involve symbolic parameters. For linear and quadratic polynomials f [x], Root[f, k] is automatically
reduced to explicit rational or radical form. N finds the approximate numerical value of a Root object. Operations
such as Abs, Re, Round and Less can be used on Root objects. Root[f, k] is treated as a numeric quantity if f
contains no symbolic parameters. Root by default isolates the roots of a polynomial using approximate numerical
methods. No cases are known where this approach fails. SetOptions[Root, ExactRootIsolation->True] will
however make Root use much slower but fully rigorous methods. See page 821. See also: Solve, RootReduce,
ToRadicals, RootSum, Extension, Algebraics. Related package: Algebra`RootIsolation` . New in Version 3.
RootReduce RotateLeft
1266
RootReduce
RootReduce[expr] attempts to reduce expr to a single Root object.
If expr consists only of integers and Root objects combined using algebraic operations, then the result from
RootReduce[expr] will always be a single Root object. Simple Root objects may in turn automatically evaluate to
rational expressions or combinations of radicals. See page 826. See also: FullSimplify, Solve, ToRadicals.
Related package: NumberTheory`PrimitiveElement` . New in Version 3.
Roots
Roots[lhs==rhs, var] yields a disjunction of equations which represent the roots of a
polynomial equation.
Roots uses Factor and Decompose in trying to find roots.
applying N. Roots can take the following options:
Cubics
EquatedTo
Modulus
Multiplicity
Quartics
Using
True
Null
0
1
True
True
Roots is generated when Solve and related functions cannot produce explicit solutions. Options are often given
in such cases. Roots gives several identical equations when roots with multiplicity greater than one occur. See
page 819. See also: Solve, NSolve, FindRoot, Reduce, ToRules, Root, Factor, Decompose,
InterpolatingPolynomial . Related package: Algebra`RootIsolation` . New in Version 1.
RootSum
RootSum[f, form] represents the sum of form[x] for all x that satisfy the polynomial equation
f [x] == 0.
f must be a Function object such as (#^5 - 2 # + 1)&. form need not correspond to a polynomial function.
Normal[expr] expands RootSum objects into explicit sums involving Root objects. f and form can contain
symbolic parameters. RootSum[f, form] is automatically simplified whenever form is a rational function. RootSum
is often generated in computing integrals of rational functions. See page 827. See also: Root. Related package:
Algebra`SymmetricPolynomials` . New in Version 3.
RotateLabel
RotateLabel is an option for two-dimensional graphics functions which specifies whether
labels on vertical frame axes should be rotated to be vertical.
For frame labels, the default is RotateLabel -> True. With RotateLabel -> True, vertical frame axes labels read
from bottom to top. See page 514. See also: Text, ImageRotated. New in Version 2.
RotateLeft
RotateLeft[expr, n] cycles the elements in expr n positions to the left.
RotateLeft[expr] cycles one position to the left.
RotateLeft[expr, {n , n , ... }] cycles elements at successive levels ni positions to the left.
Example: RotateLeft[{a, b, c}, 1] # b, c, a . RotateLeft[expr, -n] rotates n positions to the right.
, RotateLeft can be used on SparseArray objects.
See pages 127 and 130. See also: RotateRight, Reverse,
PadLeft. New in Version 1.
RotateRight RowBox
1267
RotateRight
RotateRight[expr, n] cycles the elements in expr n positions to the right.
RotateRight[expr] cycles one position to the right.
RotateRight[expr, {n , n , ... }] cycles elements at successive levels ni positions to the
right.
Example: RotateRight[{a, b, c}, 1] # c, a, b . RotateRight[expr, -n] rotates n positions to the left.
, RotateRight can be used on SparseArray objects.
See pages 127 and 130. See also: RotateLeft, Reverse,
PadRight. New in Version 1.
Round
Round[x] gives the integer closest to x.
Mathematical function (see Section A.3.10). Examples: Round[2.4] # 2 ; Round[2.6] # 3 ;
Round[-2.4] # 2 ; Round[-2.6] # 3 . Round rounds numbers of the form x.5 toward the nearest even
integer. Round[x] returns an integer when x is any numeric quantity, whether or not it is an explicit number.
Example: Round[Pi^2] # 10 . For exact numeric quantities, Round internally uses numerical approximations to
establish its result. This process can be affected by the setting of the global variable $MaxExtraPrecision . See
page 745. See also: IntegerPart, Floor, Ceiling, Chop. New in Version 1; modified in Version 3.
RowAlignments
RowAlignments is an option for GridBox which specifies how entries in each row should be
aligned.
The following settings can be given:
Center
Top
Bottom
Baseline
Axis
{pos , pos , . . . }
centered
tops aligned
bottoms aligned
baselines aligned (default)
axes aligned
separate settings for each row in the grid
Lists of settings are used cyclically if there are more rows in the grid than elements in the list.
See also: ColumnAlignments, RowsEqual, RowMinHeight, TableAlignments. New in Version 3.
RowBox
RowBox[{box , box , ... }] represents a row of boxes or strings in input and output.
RowBox objects are generated automatically to correspond to each operator and its operands in input given as
\(input\). The default arrangement of RowBox objects in \(input\) is based on operator precedence. Additional
\( . . . \) can be inserted like parentheses to specify different arrangements of RowBox objects. The boxes or strings
in a RowBox are output in a row with their baselines aligned. In InputForm, RowBox objects are output using
\( . . . \). In StandardForm, explicit RowBox objects are output literally. You can use DisplayForm to see the
display form of such objects. See page 445. See also: SequenceForm, GridBox, AdjustmentBox . New in
Version 3.
RowLines RowSpacings
1268
RowLines
RowLines is an option for GridBox which specifies whether lines should be drawn between
adjacent rows.
The default setting is RowLines->False . RowLines->{v , v
, . . . } specifies whether lines should be drawn
between successive pairs of rows. The vij can be True or False. If there are more rows than entries in the list,
the last element is used repeatedly for remaining pairs of rows. Lines can be drawn around the outside of a
GridBox using FrameBox. See page 446. See also: ColumnLines, FrameBox, GridLines. New in Version 3.
RowMinHeight
RowMinHeight is an option for GridBox which specifies the minimum total height in units of
font size that should be allowed for each row.
The default setting RowMinHeight->1 forces each row to have a total height which at least accommodates all the
characters in the current font. RowMinHeight->0 reduces the total height of each entry as much as possible,
allowing entries containing characters such as x and X to be different heights. See page 449. See also:
RowSpacings, RowAlignments , RowsEqual, ButtonMinHeight . New in Version 3.
RowReduce
RowReduce[m] gives the row-reduced form of the matrix m.
Example: RowReduce[{{3, 1, a}, {2, 1, b}}] # 1, 0, a b, 0, 1, 2 a 3 b . RowReduce performs a
version of Gaussian elimination, adding multiples of rows together so as to produce zero elements when possible.
The final matrix is in reduced row echelon form. If m is a non-degenerate square matrix, RowReduce[m] is
IdentityMatrix[Length[m]] . If m is a sufficiently non-degenerate rectangular matrix with k rows and more than
k columns, then the first k columns of RowReduce[m] will form an identity matrix. RowReduce works on both
numerical and symbolic matrices. RowReduce[m, Modulus -> n] performs row reduction modulo n.
RowReduce[m, ZeroTest -> test] evaluates test[ m[[i, j]] ] to determine whether matrix elements are zero.
See page 907. Implementation notes: see page 1069. See also: LinearSolve, Inverse, NullSpace,
GroebnerBasis. New in Version 1; modified in Version 3.
RowsEqual
RowsEqual is an option for GridBox which specifies whether all rows in the grid should be
assigned equal total height.
The default setting RowsEqual->False determines the total height of each row from the entry in that row with the
largest total height. RowsEqual->True makes all rows the same total height, with the total height determined by
the entry with the largest total height in the whole GridBox. See page 449. See also: RowAlignments ,
RowSpacings, RowMinHeight , ColumnsEqual, MatrixForm. New in Version 3.
RowSpacings
RowSpacings is an option for GridBox which specifies the spaces in x-heights that should be
inserted between successive rows.
The default setting is RowSpacings->1.0. RowSpacings effectively specifies the minimum distance between entries
in successive rows; individual entries will often not fill their rows and will therefore be further apart.
RowSpacings->n uses a column spacing equal to n times the height of an x character in the current font.
RowSpacings->{s , s
, . . . } can be used to specify different spacings between different rows. If there are more
rows than entries in this list, then the last element of the list is used repeatedly for the remaining rows. See
page 449. See also: RowAlignments, RowMinHeight, RowsEqual, ColumnSpacings , TableSpacing. New in
Version 3.
RSolve Run
1269
RSolve
RSolve[eqn, a[n], n] solves a recurrence equation for a[n].
RSolve[{eqn , eqn , ... }, {a [n], a [n], ... }, n] solves a system of recurrence equations.
RSolve[eqn, a[n , n , ... ], {n , n , ... }] solves a partial recurrence equation.
RSolve[eqn, a, n] gives solutions for a as pure functions. The equations can involve objects of the form a[n+i]
where i is any fixed integer, or objects of the form a[q^i n]. Equations such as a[0]==val can be given to specify
end conditions. If not enough end conditions are specified, RSolve will give general solutions in which
undetermined constants are introduced. The constants introduced by RSolve are indexed by successive integers.
The option GeneratedParameters specifies the function to apply to each index. The default is
GeneratedParameters->C , which yields constants C[1], C[2], . . . . GeneratedParameters->(Module[{C}, C]&)
guarantees that the constants of integration are unique, even across different invocations of RSolve. For partial
recurrence equations, RSolve generates arbitrary functions C[n][. . . ]. Solutions given by RSolve sometimes
include sums that cannot be carried out explicitly by Sum. Dummy variables with local names are used in such
sums. RSolve sometimes gives implicit solutions in terms of Solve. RSolve handles both ordinary difference
equations and q-difference equations. RSolve handles difference-algebraic equations as well as ordinary difference
equations. RSolve can solve linear recurrence equations of any order with constant coefficients. It can also solve
many linear equations up to second order with non-constant coefficients, as well as many nonlinear equations.
See page 891. Implementation notes: see page 1071. See also: Sum, ZTransform, DSolve. New in Version 5.0.
Rule
lhs -> rhs or lhs rhs represents a rule that transforms lhs to rhs.
The character can be entered as , -> , or \[Rule]. lhs -> rhs evaluates rhs immediately. You can apply rules
using Replace. The assignment lhs = rhs specifies that the rule lhs -> rhs should be used whenever it applies.
lhs rhs can be entered as lhs \[Rule] rhs or lhs H -> H rhs. In StandardForm, Rule is printed using . Rule
is a scoping construct (see Section A.3.8). Symbols that occur as pattern names in lhs are treated as local to the
rule. This is true when the symbols appear on the right-hand side of /; conditions in lhs, and when the symbols
appear anywhere in rhs, even inside other scoping constructs. See pages 299 and 1052. Implementation notes:
see page 1066. See also: Replace, Set, RuleDelayed, PolynomialReduce . Related package:
Utilities`FilterOptions` . New in Version 1; modified in Version 3.
RuleDelayed
lhs :> rhs or lhs
rhs represents a rule that transforms lhs to rhs, evaluating rhs only after the
rule is used.
The character
can be entered as , :> , or \[RuleDelayed] . RuleDelayed has the attribute HoldRest. You can
apply rules using Replace. The assignment lhs := rhs specifies that the rule lhs :> rhs should be used whenever
it applies. You can use Condition to specify when a particular rule applies. lhs
rhs can be entered as
lhs \[RuleDelayed] rhs or lhs H :> H rhs. In StandardForm, RuleDelayed is printed using
. See notes for Rule.
See pages 299 and 1052. See also: Replace, SetDelayed, Rule. New in Version 1; modified in Version 3.
Run
Run[expr , expr , ... ] generates the printed form of the expressions expri , separated by spaces,
and runs it as an external, operating system, command.
Run is not available on all computer systems. Run prints the expri in InputForm format. Run returns an integer
which corresponds, when possible, to the exit code for the command returned by the operating system. The
command executed by Run cannot usually require interactive input. On most computer systems, it can, however,
generate textual output. You can enter the input line !command to execute an external command. See page 629.
See also: Put, Splice. New in Version 1.
RunThrough SampleRate
1270
RunThrough
RunThrough["command", expr] executes an external command, giving the printed form of expr
as input, and taking the output, reading it as Mathematica input, and returning the result.
RunThrough is not available on all computer systems. RunThrough writes the InputForm of expr on the standard
input for command, then reads its standard output, and feeds it into Mathematica. RunThrough starts command, then
gives input to command, then terminates the input. See page 630. See also: Install, Put, Get, Splice. New in
Version 1.
SameQ
lhs === rhs yields True if the expression lhs is identical to rhs, and yields False otherwise.
SameQ requires exact correspondence between expressions, except that it considers Real numbers equal if their
difference is less than the uncertainty of either of them. 2 === 2. gives False. e === e === e
gives True if
all the ei are identical. See page 268. See also: UnsameQ, Equal, Order. New in Version 1.
SampleDepth
SampleDepth is an option for sound primitives which specifies how many bits should be used
to encode sound amplitude levels.
The default setting is SampleDepth -> 8. With the default setting, 256 distinct sound amplitudes are allowed.
See page 566. See also: PlayRange, SampleRate. New in Version 2.
SampledSoundFunction
SampledSoundFunction[f, n, r] is a sound primitive, which represents a sound whose
amplitude sampled r times a second is generated by applying the function f to successive
integers from 1 to n.
SampledSoundFunction[{f , f , . . . }, n, r] yields sound on several channels. SampledSoundFunction is
generated by Play. SampledSoundFunction primitives can appear inside Sound, Graphics and Graphics3D
objects. See page 566. New in Version 2.
SampledSoundList
SampledSoundList[{a , a , ... }, r] is a sound primitive, which represents a sound whose
amplitude has levels ai sampled r times a second.
SampledSoundList[{list , list , . . . }, r] yields sound on several channels. If the lists are of different lengths,
silence is inserted at the ends of shorter lists. SampledSoundList is generated by ListPlay. SampledSoundList
primitives can appear inside Sound, Graphics and Graphics3D objects. See page 566. New in Version 2.
SampleRate
SampleRate is an option for sound primitives which specifies the number of samples per
second to generate for sounds.
The default setting is SampleRate -> 8192. The highest frequency in hertz that can be present in a particular
sound is equal to half the setting for SampleRate. See page 172. See also: SampleDepth. New in Version 2.
Save SchurDecomposition
1271
Save
Save["filename", symbol] appends definitions associated with the specified symbol to a file.
Save["filename", "form"] appends definitions associated with all symbols whose names match
the string pattern form.
Save["filename", "context`"] appends definitions associated with all symbols in the specified
context.
Save["filename", {object , object , ... }] appends definitions associated with several objects.
Save uses FullDefinition to include subsidiary definitions. Save writes out definitions in InputForm. Save
uses Names to find symbols whose names match a given string pattern. You can use Save["filename", "s"] to
write out the definition for the value of a symbol s itself. See pages 204 and 625. See also: PutAppend, Get,
DumpSave. New in Version 1; modified in Version 3.
Scaled
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 ordinary
coordinates {x , y , ... }, then moving by a scaled offset {dx, dy, ... }.
Scaled can be used to specify scaled coordinates in any two- or three-dimensional graphics primitive. You can
use Scaled to represent objects that occupy a fixed region in a plot, independent of the specific range of
coordinates in the plot. See pages 505 and 531. See also: PlotRange, PlotRegion, Offset. New in Version 1.
Scan
Scan[f, expr] evaluates f applied to each element of expr in turn.
Scan[f, expr, levelspec] applies f to parts of expr specified by levelspec.
Scan[f, expr] discards the results of applying f to the subexpressions in expr. Unlike Map, Scan does not build up a
new expression to return. You can use Return to exit from Scan. Return[ret] causes the final value of Scan to be
ret. If no explicit return values are specified, the final result from Scan is Null. You can also use Throw to exit
from Scan. Scan is useful in carrying out an operation on parts of expressions where the operation has a side
effect, such as making an assignment. Level specifications are described on page 1041. The default value for
levelspec in Scan is {1}. , If expr is a SparseArray object, Scan[f, expr] applies f only to the values or subarrays
that explicitly appear in expr. See page 247. See also: Apply, Map, Level, Sow. New in Version 1; modified in
Version 3.
-
SchurDecomposition
SchurDecomposition[m] yields the Schur decomposition for a numerical matrix m. The result
is a list {q, t} where q is an orthonormal matrix and t is a block upper triangular matrix.
SchurDecomposition[{m, a}] gives the generalized Schur decomposition of m with respect
to a.
1272
ScientificForm ScriptSizeMultipliers
ScientificForm
ScientificForm[expr] prints with all real numbers in expr given in scientific notation.
ScientificForm[expr, n] prints with numbers given to n-digit precision.
ScientificForm takes the same options as NumberForm, but uses a different default function for
ExponentFunction . You can mix ScientificForm and BaseForm. ScientificForm acts as a wrapper, which
affects printing, but not evaluation. See page 435. See also: EngineeringForm , NumberForm. New in Version 1.
ScreenStyleEnvironment
ScreenStyleEnvironment is an option for notebooks which specifies the style environment to
be used in displaying a notebook on the screen.
Style environments provided in typical style sheets include:
environment
environment
environment
environment
"Condensed"
"Presentation"
"Printout"
"Working"
See page 197.
for
for
for
for
New in Version 3.
ScriptBaselineShifts
ScriptBaselineShifts is an option for StyleBox which specifies the minimum distance in
x-heights to shift subscripts and superscripts.
The setting ScriptBaselineShifts->{sub, sup} uses shift sub for subscripts and sup for superscripts. A typical
setting is ScriptBaselineShifts->{0.6, 0.9}. The default setting
ScriptBaselineShifts->{Automatic, Automatic} shifts subscripts and superscripts by a distance which depends
on their height. See page 457. See also: AdjustmentBox , RowMinHeight, ScriptMinSize. New in Version 3.
ScriptMinSize
ScriptMinSize is an option for StyleBox which specifies the minimum font size to use in
rendering subscripts, etc.
Settings for ScriptMinSize are in units of printers points. ScriptMinSize is used for characters that appear in
constructs such as subscripts, superscripts, underscripts, overscripts and built-up fractions. ScriptMinSize is
typically set larger in styles used for screen display than in those used for printing. See page 457. See also:
ScriptSizeMultipliers , FontSize, ScriptBaselineShifts . New in Version 3.
ScriptSizeMultipliers
ScriptSizeMultipliers is an option for StyleBox which specifies how much smaller to
render each successive level of subscripts, etc.
ScriptSizeMultipliers is applied to FontSize for characters that appear in constructs such as subscripts,
superscripts, underscripts, overscripts and built-up fractions. The default setting for ScriptSizeMultipliers is
0.71, yielding approximately a factor 2 reduction in character area at each level.
ScriptSizeMultipliers -> {s , s , . . . , sn } uses multiplier si for level i, and multiplier sn for levels n and
beyond. See page 457. See also: ScriptMinSize, ScriptBaselineShifts . New in Version 3.
Sec SelectedNotebook
1273
Sec
Sec[z] gives the secant of z.
Mathematical function (see Section A.3.10). The argument of Sec is assumed to be in radians. (Multiply by Degree
to convert from degrees.) secz cosz. 1/Cos[z] is automatically converted to Sec[z]. TrigFactorList[expr]
does decomposition. See page 761. See also: ArcSec, TrigToExp, TrigExpand. New in Version 1.
Sech
Sech[z] gives the hyperbolic secant of z.
Mathematical function (see Section A.3.10). sechz coshz. 1/Cosh[z] is automatically converted to Sech[z].
TrigFactorList[expr] does decomposition. See page 761. See also: ArcSech, TrigToExp, TrigExpand. New in
Version 1; modified in Version 3.
SeedRandom
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.
You can use SeedRandom[n] to make sure you get the same sequence of pseudorandom numbers on different
occasions. You can also use SeedRandom["string"] , although the seed set in this way may be different on different
computer systems. See page 747. See also: Random, $RandomState . New in Version 1.
Select
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.
Example: Select[{1,4,2,7,6}, EvenQ] # 4, 2, 6 . The object list can have any head, not necessarily List.
, Select can be used on SparseArray objects.
See page 251. See also: Cases, Take, Drop. Related package:
Statistics`DataManipulation` . New in Version 1.
Selectable
Selectable is an option for boxes, cells and notebooks which specifies whether their contents
can be selected interactively using the front end.
Even with the setting Selectable->False , an object can be selected as a whole. With Selectable->False set at
the notebook level, no cells in the notebook can be selected. See pages 448 and 607. See also: Editable,
WindowClickSelect , StructuredSelection , ShowSelection. New in Version 3.
SelectedNotebook
SelectedNotebook[ ] gives the currently selected notebook in the front end.
SelectedNotebook returns a NotebookObject. The currently selected notebook will normally have its title bar
highlighted. The currently selected notebook is the one to which notebook-oriented menu commands in the front
end will be directed. Textual commands are however directed to the input notebook. A palette window can be a
currently selected notebook but cannot normally be an input notebook. See page 579. See also:
SetSelectedNotebook , Notebooks, InputNotebook , EvaluationNotebook , ButtonNotebook. New in Version 3.
1274
SelectionAnimate SelectionEvaluateCreateCell
SelectionAnimate
SelectionAnimate[notebook] animates graphics in the current selection in a notebook.
SelectionAnimate[notebook, t] animates graphics for t seconds.
The first argument of SelectionAnimate is a NotebookObject. The current selection for SelectionAnimate will
typically be a cell group. SelectionAnimate stops the animation as soon as you do any interactive operation in
the front end, such as pressing a key or clicking the mouse. The timing in SelectionAnimate does not count
setup or initial rendering of frames. See page 588. See also: AnimationDisplayTime , SelectionEvaluate . New
in Version 3.
SelectionCreateCell
SelectionCreateCell[notebook] copies the contents of the current selection in a notebook into
a new cell.
SelectionCreateCell[notebook, sel] sets the current selection after the copy to be as specified
by sel.
The first argument of SelectionCreateCell is a NotebookObject . If the current selection is a cell group, then
SelectionCreateCell will create a new cell group. Possible settings for sel are as in NotebookWrite. The
default for sel is After. SelectionCreateCell[notebook, All] sets the current selection to be the whole of the
newly created cell. See page 588. See also: SelectionEvaluateCreateCell , NotebookRead, NotebookWrite .
New in Version 3.
SelectionEvaluate
SelectionEvaluate[notebook] replaces the current selection in a notebook with the result
obtained by evaluating the contents of the selection in the kernel.
SelectionEvaluate[notebook, sel] sets the current selection after the evaluation to be as
specified by sel.
The first argument of SelectionEvaluate is a NotebookObject. Possible settings for sel are as in NotebookWrite.
The default for sel is After. Unless sel is None, the current selection after evaluation is complete will always be
as specified by sel, even if you moved the selection interactively in the front end during the course of the
evaluation. See page 588. See also: SelectionEvaluateCreateCell , NotebookRead, NotebookWrite,
ButtonEvaluator , SelectionAnimate . New in Version 3.
SelectionEvaluateCreateCell
SelectionEvaluateCreateCell[notebook] takes the current selection in a notebook and
creates a new cell containing the result obtained by evaluating the contents of the selection
using the kernel.
SelectionEvaluateCreateCell[notebook, sel] sets the current selection after the evaluation to
be as specified by sel.
The first argument of SelectionEvaluateCreateCell is a NotebookObject. Possible settings for sel are as in
NotebookWrite. The default for sel is After. SelectionEvaluateCreateCell[notebook, All] sets the current
selection to be the cell corresponding the result from the evaluation. SelectionEvaluateCreateCell performs the
same underlying operation as typing SHIFT-ENTER in the front end. It does not, however, have side effects such as
incrementing $Line. See page 588. See also: SelectionEvaluate , SelectionCreateCell , NotebookRead,
NotebookWrite. New in Version 3.
SelectionMove SequenceForm
1275
SelectionMove
SelectionMove[obj, dir, unit] moves the current selection in an open notebook in the front
end in the direction dir by the specified unit.
SelectionMove[obj, dir, unit, n] repeats the move n times.
The first argument of SelectionMove must be a NotebookObject.
Next
Previous
After
Before
All
make
make
make
make
make
the
the
the
the
the
selection
selection
selection
selection
selection
be
be
be
be
be
Character
Word
Expression
TextLine
CellContents
Cell
CellGroup
EvaluationCell
ButtonCell
GeneratedCell
Notebook
individual character
word or other token
complete subexpression
line of text
the contents of the cell
complete cell
cell group
cell associated with the current evaluation
cell associated with any button that initiated the evaluation
cell generated by the current evaluation
complete notebook
Unless the option setting AutoScroll->False is given, the front end will scroll a notebook so that the result of
SelectionMove is visible. The front end will also usually highlight the region corresponding to the result. With
direction specifications After and Before, SelectionMove will usually make the current selection be an insertion
point between two units of the specified type. SelectionMove returns $Failed if it cannot move the selection in
the way you request. The EvaluationCell defines the point after which output from the current evaluation will
by default be placed. A GeneratedCell corresponds to an element of the output. See page 582. See also:
NotebookSelection , NotebookWrite, NotebookRead. New in Version 3.
Sequence
Sequence[expr , expr , ... ] represents a sequence of arguments to be spliced automatically
into any function.
Example: f[a, Sequence[b, c]] # f
a, b, c . Sequence objects will automatically be flattened out in all
functions except those with attribute SequenceHold or HoldAllComplete. See page 258. See also: FlattenAt,
BlankSequence, SlotSequence, List, Listable. New in Version 3.
SequenceForm
SequenceForm[expr , expr , ... ] prints as the textual concatenation of the printed forms of
the expri .
Expressions printed by SequenceForm have their baselines aligned. SequenceForm acts as a wrapper, which
affects printing, but not evaluation. See page 434. See also: RowBox, ColumnForm, TableForm. New in Version 1.
SequenceHold SeriesData
1276
SequenceHold
SequenceHold is an attribute which specifies that Sequence objects appearing in the arguments
of a function should not automatically be flattened out.
The attribute HoldAllComplete prevents Sequence objects from being flattened out.
also: HoldAll, HoldAllComplete . New in Version 3.
See
Series
Series[f, {x, x , n}] generates a power series expansion for f about the point x x to order
x x n .
Series[f, {x, x , nx }, {y, y , ny }] successively finds series expansions with respect to y,
then x.
Series can construct standard Taylor series, as well as certain expansions involving negative powers, fractional
powers and logarithms. Series detects certain essential singularities. Series can expand about the point x .
Series[f, {x, 0, n}] constructs Taylor series for any function f according to the formula
f f $ x f $$ x f n xn nd. Series effectively evaluates partial derivatives using D. It assumes that
different variables are independent. The result of Series is usually a SeriesData object, which you can
manipulate with other functions. Normal[series] truncates a power series and converts it to a normal expression.
SeriesCoefficient[series, n] finds the coefficient of the nth order term. See page 883. Implementation notes:
see page 1071. See also: InverseSeries, ComposeSeries, Limit, Normal, InverseZTransform , RSolve. Related
packages: Calculus`Pade` , NumericalMath`Approximations` , NumericalMath`NSeries` . New in Version 1;
modified in Version 3.
SeriesCoefficient
SeriesCoefficient[series, n] finds the coefficient of the nth order term in a power series.
SeriesCoefficient[series, {n , n , ... }] finds a coefficient in a multivariate series.
See page 889.
New in Version 3.
SeriesData
SeriesData[x, x , {a , a , ... }, nmin, nmax, den] represents a power series in the variable
x about the point x . The ai are the coefficients in the power series. The powers of (x-x ) that
appear are nmin/den, (nmin+1)/den, ... , nmax/den.
SeriesData objects are generated by Series. SeriesData objects are printed as sums of the coefficients ai ,
multiplied by powers of x - x . A SeriesData object representing a power series is printed with O[x - x ]^p
added, to represent omitted higher-order terms. When you apply certain mathematical operations to SeriesData
objects, new SeriesData objects truncated to the appropriate order are produced. The operations you can perform
on SeriesData objects include arithmetic ones, mathematical functions with built-in derivatives, and integration and
differentiation. Normal[expr] converts a SeriesData object into a normal expression, truncating omitted
higher-order terms. If the variable in a SeriesData object is itself a SeriesData object, then the composition of
the SeriesData objects is computed. Substituting one series into another series with the same expansion parameter
therefore automatically leads to composition of the series. Composition is only possible if the first term of the inner
series involves a positive power of the variable. InverseSeries can be applied to SeriesData objects to give
series for inverse functions. See page 885. New in Version 1.
SessionTime SetAttributes
1277
SessionTime
SessionTime[ ] gives the total number of seconds of real time that have elapsed since the
beginning of your Mathematica session.
SessionTime starts counting time as soon as your operating system considers your Mathematica process to be
executing. SessionTime is accurate only down to a granularity of at least $TimeUnit seconds. See page 710.
See also: TimeUsed, AbsoluteTime , Date. New in Version 2.
Set
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.
{l , l , ... } = {r , r , ... } evaluates the ri , and assigns the results to be the values of the
corresponding li .
lhs can be any expression, including a pattern. f[x_] = x^2 is a typical assignment for a pattern. Notice the
presence of _ on the left-hand side, but not the right-hand side. An assignment of the form f [args] = rhs sets up
a transformation rule associated with the symbol f. Different rules associated with a particular symbol are usually
placed in the order that you give them. If a new rule that you give is determined to be more specific than existing
rules, it is, however, placed before them. When the rules are used, they are tested in order. New assignments
with identical lhs overwrite old ones. You can see all the assignments associated with a symbol f using ?f or
Definition[f]. If you make assignments for functions that have attributes like Flat and Orderless, you must
make sure to set these attributes before you make assignments for the functions. Set has attribute HoldFirst. If
lhs is of the form f [args], then args are evaluated. There are some special functions for which an assignment to
s[f [args]] is automatically associated with f rather than s. These functions include: Attributes, Default, Format,
MessageName, Messages, N and Options. When it appears in an unevaluated symbolic form, Set is treated as a
scoping construct (see Section A.3.8). lhs = rhs returns rhs even if for some reason the assignment specified cannot
be performed. Some global variables such as $RecursionLimit can only be assigned a certain range or class of
values. See pages 311 and 1051. See also: TagSet, Unset, Clear, HoldPattern, DownValues. New in Version 1.
SetAccuracy
SetAccuracy[expr, a] yields a version of expr in which all numbers have been set to have
accuracy a.
When SetAccuracy is used to increase the accuracy of a number, the number is padded with zeros. The zeros are
taken to be in base 2. In base 10, the additional digits are usually not zero. SetAccuracy returns an
arbitrary-precision number even if the number of significant digits obtained will be less than $MachinePrecision .
When expr contains machine-precision numbers, SetAccuracy[expr, a] can give results which differ from one
computer system to another. SetAccuracy will first expose any hidden extra digits in the internal binary
representation of a number, and only after these are exhausted add trailing zeros. 0.004``25 generates a number
with all trailing digits zero and accuracy 25 on any computer system. SetAccuracy[expr, a] does not modify
expr itself. See page 736. See also: N, Accuracy, SetPrecision. New in Version 2.
SetAttributes
SetAttributes[s, attr] adds attr to the list of attributes of the symbol s.
SetAttributes modifies Attributes[s]. SetAttributes[s, {attr , attr , . . . }] sets several attributes at a time.
SetAttributes[{s , s , . . . }, attrs] sets attributes of several symbols at a time. SetAttributes has the
attribute HoldFirst. See page 328. See also: ClearAttributes , Protect. New in Version 1.
SetDelayed SetPrecision
1278
SetDelayed
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.
See notes for Set. SetDelayed has attribute HoldAll, rather than HoldFirst. You can make assignments of the
form lhs := rhs /; test, where test gives conditions for the applicability of each transformation rule. You can make
several assignments with the same lhs but different forms of test. lhs := rhs returns Null if the assignment
specified can be performed, and returns $Failed otherwise. See pages 311 and 1051. See also: TagSetDelayed ,
Unset, Clear. New in Version 1.
SetDirectory
SetDirectory["dir"] sets the current working directory.
SetDirectory sets the current working directory, then returns its full name. SetDirectory prepends the current
working directory to the directory stack given by DirectoryStack[ ]. See page 636. See also: ResetDirectory ,
Directory, DirectoryName, $Path. New in Version 2.
SetFileDate
SetFileDate["file"] sets the modification date for a file to be the current date.
SetFileDate["file", date] sets the modification date to be the specified date. The date must be given in the
{year, month, day, hour, minute, second} format used by Date. See page 641. See also: FileDate. Related
package: Miscellaneous`Calendar` . New in Version 2.
SetOptions
SetOptions[s, name ->value , name ->value , ... ] sets the specified default options for a
symbol s.
SetOptions[stream, ... ] or SetOptions["name", ... ] sets options associated with a
particular stream.
SetOptions[object, ... ] sets options associated with an external object such as a
NotebookObject .
SetOptions is equivalent to an assignment which redefines certain elements of the list Options[s] of default
options. SetOptions can be used on Protected symbols. SetOptions returns the new form of Options[s].
You can use SetOptions on InputStream and OutputStream objects. If there is only one stream with a particular
name, you can give the name as a string as the argument of Options. SetOptions can be used on a list of
streams, such as the value of $Output. If you use SetOptions[NotebookObject[. . . ], . . . ] the kernel will send a
request to the front end which will immediately make the change specified. See pages 144 and 1040. New in
Version 1; modified in Version 3.
-
SetPrecision
SetPrecision[expr, p] yields a version of expr in which all numbers have been set to have
precision p.
When SetPrecision is used to increase the precision of a number, the number is padded with zeros. The zeros are
taken to be in base 2. In base 10, the additional digits are usually not zero. SetPrecision returns an
arbitrary-precision number, even if the precision requested is less than $MachinePrecision .
, SetPrecision[expr, MachinePrecision] converts all numbers in expr to machine precision.
If expr contains
machine-precision numbers, SetPrecision[expr, p] can give results which differ from one computer system to
another. SetPrecision will first expose any hidden extra digits in the internal binary representation of a number,
and only after these are exhausted add trailing zeros. 0.004`25 generates a number with all trailing digits zero
and precision 25 on any computer system. SetPrecision[expr, p] does not modify expr itself. See page 736.
See also: N, Precision, Chop, SetAccuracy, $MinPrecision , $NumberMarks. New in Version 2; modified in
Version 5.0.
SetSelectedNotebook Share
1279
SetSelectedNotebook
SetSelectedNotebook[notebook] makes the specified notebook be the currently selected one in
the front end.
SetSelectedNotebook takes a NotebookObject as its argument. Setting a particular notebook to be the currently
selected one typically makes it the top notebook displayed on the screen. Making a notebook the currently
selected one does not affect the current selection within that notebook, or within other notebooks. See page 591.
See also: SelectedNotebook, Notebooks, WindowClickSelect . New in Version 3.
SetStreamPosition
SetStreamPosition[stream, n] sets the current point in an open stream.
The integer n given to SetStreamPosition should usually be a value obtained from StreamPosition.
SetStreamPosition[stream, 0] sets the current point to the beginning of a stream.
SetStreamPosition[stream, Infinity] sets the current point to the end of a stream. See page 653.
Version 2.
New in
Shading
Shading is an option for SurfaceGraphics that specifies whether the surfaces should be
shaded.
With Shading -> False, the surface will be white all over. So long as Mesh -> True, however, mesh lines will still
be drawn. When Shading -> True, the actual shading used can either be determined by the height, or, when
Lighting -> True, from simulated illumination. See page 151. See also: HiddenSurface, ClipFill. New in
Version 1.
Shallow
Shallow[expr]
Shallow[expr,
form.
Shallow[expr,
skeleton form.
Shallow[expr,
pattern form.
{depth, length}] also gives parts whose lengths are above the specified limit in
{depth, length}, form] uses skeleton form for any parts which match the
Omitted sequences of elements are given as Skeleton objects, which print in the form :k;. In StandardForm,
the characters used for this output are \[LeftSkeleton] and \[RightSkeleton]. Depth and length can be
specified as Infinity. Shallow[expr] is equivalent to Shallow[expr, {4, 10}]. Shallow acts as a wrapper,
which affects printing, but not evaluation. Trying to feed :k; as obtained from Shallow back as input to
Mathematica in StandardForm will generate an error. See page 431. See also: Short. New in Version 2; modified
in Version 3.
Share
Share[expr] changes the way expr is stored internally, to try and minimize the amount of
memory used.
Share[ ] tries to minimize the memory used to store all expressions.
Share works by sharing the storage of common subexpressions between different parts of an expression, or
different expressions. Using Share will never affect the results you get from Mathematica. It may, however, reduce
the amount of memory used, and in many cases also the amount of time taken. See page 714. See also:
MemoryInUse, ByteCount. Related package: Utilities`MemoryConserve` . New in Version 1.
Short ShowCellTags
1280
Short
Short[expr] prints as a short form of expr, less than about one line long.
Short[expr, n] prints as a form of expr about n lines long.
Short[expr] gives a skeleton form of expr, with omitted sequences of k elements indicated by :k;. In
StandardForm, the characters used for this output are \[LeftSkeleton] and \[RightSkeleton] . Omitted
sequences of elements are printed as Skeleton objects. Short prints long strings in skeleton form. The number
of lines specified need not be an integer. Short can be used with InputForm and other formats as well as
OutputForm. Short acts as a wrapper, which affects printing, but not evaluation. Trying to feed :k; as
obtained from Short back as input to Mathematica in StandardForm will generate an error. Short is used to limit
the length of output in standard Mathematica warning and other messages. See page 431. See also: Shallow,
Format. New in Version 1; modified in Version 3.
Show
Show[graphics, options] displays two- and three-dimensional graphics, using the options
specified.
Show[g , g , ... ] shows several plots combined.
Show can be used with Graphics, Graphics3D, SurfaceGraphics , ContourGraphics , DensityGraphics and
GraphicsArray. Options explicitly specified in Show override those included in the graphics expression. When
plots are combined, their lists of non-default options are concatenated. Show is effectively the analog of Print for
graphics. The option DisplayFunction determines the actual output mechanism used. Functions like Plot
automatically apply Show to the graphics expressions they generate. See pages 139 and 487. See also: Plot, etc.,
and Display. New in Version 1.
ShowAutoStyles
ShowAutoStyles is an option for Cell which specifies whether styles that are specified to be
automatically used for various syntactic and other constructs should be shown.
The default setting is ShowAutoStyles -> True. Details of automatic styles can be specified in the setting for
AutoStyleOptions . For example, unmatched delimiters such as brackets are by default shown in purple. See
page 613. See also: StyleBox, DelimiterFlashTime , ShowCursorTracker . New in Version 4.
ShowCellBracket
ShowCellBracket is an option for Cell which specifies whether to display the bracket that
indicates the extent of the cell.
ShowCellBracket is often set for styles of cells or whole notebooks instead of individual cells.
See also: CellFrame, ShowSelection. New in Version 3.
ShowCellLabel
ShowCellLabel is an option for Cell which specifies whether to display the label for a cell.
ShowCellLabel is more often set for styles of cells than for individual cells. With the setting
CellLabelAutoDelete->True , the label for a cell is automatically deleted if the cell is modified.
See also: CellLabel, ShowCellTags. New in Version 3.
ShowCellTags
ShowCellTags is an option for Cell which specifies whether to display tags for a cell.
ShowCellTags is more often set for styles of cells than for individual cells.
New in Version 3.
ShowCursorTracker Sign
1281
ShowCursorTracker
ShowCursorTracker is an option for Cell which specifies whether an elliptical spot should
appear momentarily to guide the eye if the cursor position jumps.
The default setting is ShowCursorTracker -> True. Line breaking is normally set up so that small changes to
expressions in input cells rarely cause large-scale reformatting; the cursor tracker appears whenever reformatting is
required that makes the cursor position jump. The cursor tracker is intended to be sufficiently eye-catching to
make the low-level human visual system cause an immediate shift in gaze. See page 613. See also:
DelimiterFlashTime , ShowAutoStyles . New in Version 4.
ShowPageBreaks
ShowPageBreaks is an option for Notebook which specifies whether to indicate in the
on-screen display of a notebook where page breaks would occur if the notebook were printed.
ShowPageBreaks is often set using a menu item in the notebook front end.
ScreenStyleEnvironment . New in Version 3.
ShowSelection
ShowSelection is an option for Cell which specifies whether to show the current selection
highlighted.
ShowSelection is often set for styles of cells or whole notebooks instead of individual cells. Settings for
ShowSelection affect only how the selection is displayed, not where it is or how it works. Setting
ShowSelection->False is convenient if you want notebook operations to be performed invisibly. See page 619.
See also: Selectable. New in Version 4.
ShowSpecialCharacters
ShowSpecialCharacters is an option for Cell which specifies whether to replace \[Name],
\:nnnn, etc. by explicit special characters.
With ShowSpecialCharacters->False special characters are always displayed by name when possible.
ShowSpecialCharacters is more often set at the level of styles or notebooks than at the level of individual cells.
See also: ShowStringCharacters , CharacterEncoding . New in Version 3.
ShowStringCharacters
ShowStringCharacters is an option for Cell which specifies whether to display " when a
string is entered.
ShowStringCharacters is typically set to False for output cells and True for input cells. ShowStringCharacters
is usually set at the level of styles or notebooks rather than at the level of individual cells. See also:
ShowSpecialCharacters . New in Version 3.
Sign
Sign[x] gives -1, 0 or 1 depending on whether x is negative, zero, or positive.
For non-zero complex numbers z, Sign[z] is defined as z/Abs[z]. Sign tries simple transformations in trying to
determine the sign of symbolic expressions. For exact numeric quantities, Sign internally uses numerical
approximations to establish its result. This process can be affected by the setting of the global variable
$MaxExtraPrecision . See page 745. See also: Abs, UnitStep, Positive, Negative, NonNegative, Greater,
Simplify, Assumptions. New in Version 1; modified in Version 3.
Signature Sin
1282
Signature
Signature[list] gives the signature of the permutation needed to place the elements of list in
canonical order.
Examples: Signature[{a,b,c}] # 1 ; Signature[{a,c,b}] # 1 . The signature of the permutation is n ,
where n is the number of transpositions of pairs of elements that must be composed to build up the permutation.
If any two elements of list are the same, Signature[list] gives 0. See pages 757 and 920. See also: Order,
Sort, Cross, Minors, Det, KroneckerDelta. Related package: DiscreteMath`Combinatorica` . New in Version 1.
SignPadding
SignPadding is an option for NumberForm and related functions which specifies whether
padding should be inserted after signs.
SignPadding -> True specifies that any padding that is needed should be inserted between the sign and the digits
in a number. SignPadding -> False specifies that the padding should be inserted before the sign. See
page 436. See also: NumberPadding. New in Version 2.
-
Simplify
Simplify[expr] performs a sequence of algebraic and other transformations on expr, and
returns the simplest form it finds.
$Assumptions
Automatic
300
Automatic
True
Assumptions can consist of equations, inequalities, domain specifications such as x Integers, and logical
combinations of these. Example: Simplify[Sqrt[x^2], x Reals] # Abs
x . Simplify can be used on
equations, inequalities and domain specifications. Example: Simplify[x^2 > 3, x > 2] # True . - Quantities
that appear algebraically in inequalities are always assumed to be real. Example:
Simplify[x Reals, x > 0] # True . FullSimplify does more extensive simplification than Simplify.
, You can specify default assumptions for Simplify using Assuming.
See pages 68, 72 and 813. Implementation
notes: see page 1070. See also: FullSimplify, Refine, Factor, Expand, TrigExpand, PowerExpand,
ComplexExpand, Element, FunctionExpand, Reduce, Assuming. New in Version 1; modified in Version 5.0.
Sin
Sin[z] gives the sine of z.
Mathematical function (see Section A.3.10). The argument of Sin is assumed to be in radians. (Multiply by
Degree to convert from degrees.) Sin is automatically evaluated when its argument is a simple rational multiple
of ; for more complicated rational multiples, FunctionExpand can sometimes be used. See page 761. See also:
ArcSin, Csc, TrigToExp, TrigExpand. New in Version 1.
SingleLetterItalics Sinh
1283
SingleLetterItalics
SingleLetterItalics is an option for Cell which specifies whether single-letter names
should be displayed in italics.
SingleLetterItalics->True is typically set for cells that contain TraditionalForm expressions.
See also: AutoItalicWords, StyleBox. New in Version 3.
,
SingularValueDecomposition
SingularValueDecomposition[m] gives the singular value decomposition for a numerical
matrix m. The result is a list of matrices {u, w, v}, where w is a diagonal matrix, and m can
be written as u . w . Conjugate[Transpose[v]] .
SingularValueDecomposition[{m, a}] gives the generalized singular value decomposition of
m with respect to a.
SingularValueDecomposition[m, k] gives the singular value decomposition associated with
the k largest singular values of m.
The matrix m may be rectangular. The diagonal elements of w are the singular values of m.
SingularValueDecomposition sets to zero any singular values that would be dropped by SingularValueList .
The option Tolerance can be used as in SingularValueList to determine which singular values will be
considered to be zero. u and v are column orthonormal matrices, whose transposes can be considered as lists of
orthonormal vectors. SingularValueDecomposition[{m, a}] gives a list of matrices {{u, ua}, {w, wa}, v}
such that m can be written as u . w . Conjugate[Transpose[v]] and a can be written as
ua . wa . Conjugate[Transpose[v]] . See page 914. Implementation notes: see page 1069. See also:
SingularValueList , Norm, PseudoInverse , QRDecomposition . Related packages:
Statistics`LinearRegression` . New in Version 5.0.
SingularValueList
SingularValueList[m] gives a list of the non-zero singular values of a numerical matrix m.
SingularValueList[{m, a}] gives the generalized singular values of m with respect to a.
SingularValueList[m, k] gives the k largest singular values of m.
Singular values are sorted from largest to smallest. Repeated singular values appear with their appropriate
multiplicity. By default, singular values are kept only when they are larger than 100 times p , where p is
Precision[m]. SingularValueList[m, Tolerance->t] keeps only singular values that are at least t times the
largest singular value. SingularValueList[m, Tolerance->0] returns all singular values. The matrix m can be
rectangular; the total number of singular values is always Min[Dimensions[m]] . The singular values can be
obtained from Sqrt[Eigenvalues[Conjugate[Transpose[m]] . m]]. See page 913. See also:
SingularValueDecomposition , Norm, PseudoInverse, Eigenvalues, QRDecomposition , SchurDecomposition .
Related packages: Statistics`LinearRegression` . New in Version 5.0.
Sinh
Sinh[z] gives the hyperbolic sine of z.
Mathematical function (see Section A.3.10).
New in Version 1.
SinhIntegral Slot
1284
SinhIntegral
SinhIntegral[z] gives the hyperbolic sine integral function Shiz.
Mathematical function (see Section A.3.10).
with no branch cut discontinuities.
SinIntegral
SinIntegral[z] gives the sine integral function Siz.
z
Mathematical function (see Section A.3.10). Siz sintt dt. SinIntegral[z] is an entire function of z with
no branch cut discontinuities. See page 774. See also: CosIntegral, ExpIntegralE, ExpIntegralEi, FresnelS.
New in Version 2.
SixJSymbol
SixJSymbol[{j , j , j
}, {j
, j , j }] gives the values of the Racah 6-j symbol.
The 6-j symbols vanish except when certain triples of the ji satisfy triangle inequalities. The parameters of
SixJSymbol can be integers, half-integers or symbolic expressions. See page 760. See also: ThreeJSymbol,
ClebschGordan. New in Version 2.
Skeleton
Skeleton[n] represents a sequence of n omitted elements in an expression printed with Short
or Shallow.
The standard print form for Skeleton is :n;.
In StandardForm, Skeleton is by default printed using \[LeftSkeleton] and \[RightSkeleton] characters. You
can reset the print form of Skeleton. :n; indicates the presence of missing information, and so generates an
error if you try to interpret it as Mathematica kernel input. See also: Short, StringSkeleton , Shallow,
TotalWidth. New in Version 1; modified in Version 3.
Skip
Skip[stream, type] skips one object of the specified type in an input stream.
Skip[stream, type, n] skips n objects of the specified type.
Skip behaves like Read, except that it returns Null when it succeeds in skipping the specified objects, and $Failed
otherwise. See notes for Read. See page 649. See also: SetStreamPosition , Find. New in Version 2.
Slot
# represents the first argument supplied to a pure function.
#n represents the nth argument.
# is used to represent arguments or formal parameters in pure functions of the form body& or Function[body].
# is equivalent to Slot[1]. #n is equivalent to Slot[n]. n must be a non-negative integer. #0 gives the head
of the function, i.e., the pure function itself. See page 249. New in Version 1.
SlotSequence SolveAlways
1285
SlotSequence
## represents the sequence of arguments supplied to a pure function.
##n represents the sequence of arguments supplied to a pure function, starting with the nth
argument.
## is used to represent sequences of arguments in pure functions of the form body& or Function[body]. ## is
equivalent to SlotSequence[ ] or SlotSequence[1]. ##n is equivalent to SlotSequence[n]. n must be a positive
integer. A sequence of arguments supplied to a pure function is spliced into the body of the function wherever
## and so on appear. See page 249. See also: Sequence. New in Version 1.
Solve
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.
Equations are given in the form lhs == rhs. Simultaneous equations can be combined either in a list or with &&.
A single variable or a list of variables can be specified. Solve[eqns] tries to solve for all variables in eqns.
Example: Solve[3 x + 9 == 0, x]. Solve gives solutions in terms of rules of the form x -> sol. When there
are several variables, the solution is given in terms of lists of rules: {x -> sx , y -> sy , . . . }. When there are
several solutions, Solve gives a list of them. When a particular root has multiplicity greater than one, Solve gives
several copies of the corresponding solution. Solve deals primarily with linear and polynomial equations. The
option InverseFunctions specifies whether Solve should use inverse functions to try and find solutions to more
general equations. The default is InverseFunctions->Automatic . In this case, Solve can use inverse functions, but
prints a warning message. See notes on InverseFunctions. Solve gives generic solutions only. It discards
solutions that are valid only when the parameters satisfy special conditions. Reduce gives the complete set of
solutions. Solve will not always be able to get explicit solutions to equations. It will give the explicit solutions it
can, then give a symbolic representation of the remaining solutions in terms of Root objects. If there are sufficiently
few symbolic parameters, you can then use N to get numerical approximations to the solutions. Solve gives {} if
there are no possible solutions to the equations. , Solve gives {{}} if all variables can have all possible values.
Solve[eqns, . . . , Mode->Modular] solves equations with equality required only modulo an integer. You can
specify a particular modulus to use by including the equation Modulus==p. If you do not include such an equation,
Solve will attempt to solve for the possible moduli. Solve uses special efficient techniques for handling sparse
systems of linear equations with approximate numerical coefficients. See page 829. Implementation notes: see
page 1070. See also: Reduce, FindInstance, Eliminate, SolveAlways, Roots, NSolve, FindRoot, LinearSolve,
RowReduce, GroebnerBasis, DSolve, Root, RSolve. Related packages: Algebra`RootIsolation` ,
Graphics`ImplicitPlot` , Algebra`AlgebraicInequalities . New in Version 1; modified in Version 3.
SolveAlways
SolveAlways[eqns, vars] gives the values of parameters that make the equations eqns valid for
all values of the variables vars.
Equations are given in the form lhs == rhs. Simultaneous equations can be combined either in a list or with &&.
A single variable or a list of variables can be specified. Example:
SolveAlways[a x + b == 0, x] # a 0, b 0 . SolveAlways works primarily with linear and
polynomial equations. SolveAlways produces relations between parameters that appear in eqns, but are not in the
list of variables vars. SolveAlways[eqns, vars] is equivalent to Solve[!Eliminate[!eqns, vars]]. See page 833.
See also: Eliminate, Solve, Reduce, PolynomialReduce, ForAll. New in Version 1.
Sort SparseArray
1286
Sort
Sort[list] sorts the elements of list into canonical order.
Sort[list, p] sorts using the ordering function p.
Example: Sort[{b, c, a}] # a, b, c . The canonical ordering used by Mathematica is described on
page 1043. Sort[list, p] applies the function p to pairs of elements in list to determine whether they are in order.
The default function p is OrderedQ[{#1, #2}]&. Example: Sort[{4, 1, 3}, Greater] # 4, 3, 1 . Sort
can be used on expressions with any head, not only List. See pages 127, 129 and 254. See also: Ordering,
Order, OrderedQ, Orderless, Median, Quantile. New in Version 1.
Sound
Sound[primitives] represents a sound.
Any number of sound primitives or lists of sound primitives can be given. They are played in sequence.
can be played using Show. The following primitives can be used:
SampledSoundFunction[f, n, r]
SampledSoundList[{a , a , . . . }, r]
The standard print form for Sound[. . . ] is -Sound-. InputForm prints the explicit list of primitives.
page 565. Related packages: Miscellaneous`Audio` , Miscellaneous`Music` . New in Version 2.
,
Sound
See
Sow
Sow[e] specifies that e should be collected by the nearest enclosing Reap.
Sow[e, tag] specifies that e should be collected by the nearest enclosing Reap whose pattern
matches tag.
Sow[e, {tag , tag , ... }] specifies that e should be collected once for each pattern that
matches a tagi .
Sow[e, . . . ] returns e. By having several identical tagi , a single expression can be made to appear multiple times
in a list returned by Reap. Sow[e] is equivalent to Sow[e, None]. Sow[e, {{tag}}] sows an expression with tag
{tag}. See page 355. See also: Reap, Throw, AppendTo, EvaluationMonitor , StepMonitor, Scan. New in
Version 5.0.
SparseArray
SparseArray[{pos ->val , pos ->val , ... }] yields a sparse array in which values vali appear
at positions posi .
SparseArray[{pos , pos , ... }->{val , val , ... }] yields the same sparse array.
SparseArray[list] yields a sparse array version of list.
SparseArray[data, {d , d , ... }] yields a sparse array representing a d d array.
SparseArray[data, dims, val] yields a sparse array in which unspecified elements are taken to
have value val.
(continued)
SparseArray
1287
(continued)
SpellingCorrection
SpellingCorrection is an option for StringMatchQ , Names and related functions which
specifies whether strings should be considered to match even when a small fraction of the
characters in them are different.
The default setting SpellingCorrection -> False requires exact matching. ?name effectively uses
SpellingCorrection -> True when it cannot find an exact match for name. See page 412. See also:
IgnoreCase. New in Version 2.
SphericalHarmonicY
SphericalHarmonicY[l, m, , ] gives the spherical harmonic Ylm .
Mathematical function (see Section A.3.10). The spherical harmonics are orthogonal with respect to integration
over the surface of the unit sphere. For l ! , Ylm l
l mdl mdPm
coseim where Pm
is
l
l
m
the associated Legendre function. For l * , Ylm Yl
. See page 766. See also: LegendreP,
ClebschGordan. New in Version 1.
SphericalRegion
SphericalRegion is an option for three-dimensional graphics functions which specifies
whether the final image should be scaled so that a sphere drawn around the three-dimensional
bounding box would fit in the display area specified.
SphericalRegion -> False scales three-dimensional images to be as large as possible, given the display area
specified. SphericalRegion -> True scales three-dimensional images so that a sphere drawn around the
three-dimensional bounding box always fits in the display area specified. The center of the sphere is taken to be
at the center of the bounding box. The radius of the sphere is chosen so that the bounding box just fits within the
sphere. With SphericalRegion -> True, the image of a particular object remains consistent in size, regardless of
the orientation of the object. SphericalRegion -> True overrides any setting given for ViewCenter. See
page 536. See also: PlotRegion, ViewPoint. New in Version 2.
Splice SqrtBox
1288
Splice
Splice["file"] splices Mathematica output into an external file. It takes text enclosed between
<* and *> in the file, evaluates the text as Mathematica input, and replaces the text with the
resulting Mathematica output.
Splice["infile", "outfile"] processes text from the file infile, and writes output into outfile. Splice["file"] takes
files with names of the form name.mx and writes output in files with names name.x. Text in the input file not
enclosed between <* and *> is copied without change to the output file. The default format for Mathematica
output is determined by the extension of the input file name:
name.mc
CForm
name.mf
FortranForm
name.mtex
TeXForm
The following options for Splice can be used:
Delimiters
FormatType
PageWidth
{"<*", "*>"}
Automatic
78
You can use pipes instead of files for input and output to Splice.
in Version 1.
New
Split
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.
Example: Split[{a, a, b, b, a, a, b}] # a, a, b, b, a, a, b . The default function used to test
whether elements are identical is SameQ. Split can be used to perform run-length encoding. See page 292.
See also: Partition, Union, Flatten, ReplaceList. New in Version 3.
Sqrt
Sqrt[z] or
z gives the square root of z.
SqrtBox
SqrtBox[x] represents
x in input and output.
Inside \( . . . \) SqrtBox[x] can be input as \@ x. In a notebook a SqrtBox can be created using 2 or @ .
moves out from under the square root sign. In StandardForm and InputForm, SqrtBox[x] is interpreted
on input as Sqrt[x]. The baseline of SqrtBox[x] is taken to be the baseline of x. If SqrtBox[x] does not fit on
a single line, it is output as x^(1/2). In StandardForm, explicit SqrtBox objects are output literally. You can use
DisplayForm to see the display form of such objects. See page 445. See also: RadicalBox, OverscriptBox.
New in Version 3.
Stack StandardForm
1289
Stack
Stack[ ] shows the current evaluation stack, giving a list of the tags associated with
evaluations that are currently being done.
Stack[pattern] gives a list of expressions currently being evaluated which match the pattern.
Stack[_] shows all expressions currently being evaluated. You can call Stack from inside a dialog to see how
the dialog was reached. In the list returned by Stack[pattern], each expression is wrapped with HoldForm. The
maximum length of Stack[ ] is limited by $RecursionLimit . Stack has attribute HoldFirst. See page 367.
See also: Trace. New in Version 2.
StackBegin
StackBegin[expr] evaluates expr, starting a fresh evaluation stack.
You can use StackBegin to prevent outer evaluations from appearing in the evaluation stack when you call
Stack. StackBegin has attribute HoldFirst. A StackBegin is automatically done when the evaluation of each
input line begins in an interactive Mathematica session. See page 368. See also: StackInhibit. New in
Version 2.
StackComplete
StackComplete[expr] evaluates expr with intermediate expressions in evaluation chains
included on the stack.
Mathematica normally includes only the latest expression on each evaluation chain involved in the evaluation of a
particular expression. Inside StackComplete, however, all preceding expressions on the evaluation chains are
included. StackComplete typically increases significantly the number of expressions kept on the evaluation stack.
See page 368. See also: TraceBackward, TraceAbove. New in Version 2.
StackInhibit
StackInhibit[expr] evaluates expr without modifying the evaluation stack.
You can use StackInhibit to prevent innermost evaluations from appearing in the evaluation stack when you
look at it with Stack. StackInhibit has attribute HoldFirst. See page 368. See also: StackBegin. New in
Version 2.
,
StandardDeviation
StandardDeviation[list] gives the standard deviation of the elements in list.
StandardDeviation[list] is equivalent to Sqrt[Variance[list]] . StandardDeviation handles both numerical and
symbolic data. StandardDeviation[{{x , y , . . . }, {x , y , . . . }, . . . }] gives
{StandardDeviation[{x , x , . . . }], StandardDeviation[{y , y , . . . }]}. StandardDeviation works with
SparseArray objects. See pages 794 and 924. See also: Variance, Mean, Quantile. Related packages:
Statistics`DescriptiveStatistics` , Statistics`MultiDescriptiveStatistics` . New in Version 5.0.
StandardForm
StandardForm[expr] prints as the standard Mathematica two-dimensional representation of
expr.
StandardForm generates output that gives a unique and unambiguous representation of Mathematica expressions,
suitable for use as input. StandardForm incorporates many aspects of traditional mathematical notation.
StandardForm is the standard format type used for both input and output of Mathematica expressions in
notebooks. StandardForm can be edited in the notebook front end. StandardForm uses special characters as well
as ordinary keyboard characters. StandardForm is based on boxes. The notebook front end contains menu items
for conversion to and from StandardForm . See page 424. See also: TraditionalForm , OutputForm, InputForm,
MakeExpression, ToBoxes. New in Version 3.
StepMonitor String
1290
StepMonitor
StepMonitor is an option for iterative numerical computation functions that gives an
expression to evaluate whenever a step is taken by the numerical method used.
The option setting is normally given as StepMonitor :> expr. The :> is used instead of -> to avoid expr being
immediately evaluated. Whenever expr is evaluated, all variables in the numerical computation are assigned their
current values. Block[{var = val , . . . }, expr] is effectively used. See page 977. See also:
EvaluationMonitor , Sow, Print. New in Version 5.0.
StieltjesGamma
StieltjesGamma[n] gives the Stieltjes constant n .
Mathematical function (see Section A.3.10). n nd is the coefficient of sn in the Laurent expansion of s
about the point s . The n are generalizations of Eulers constant; . See page 772. Implementation
notes: see page 1068. See also: Zeta, EulerGamma. New in Version 3.
StirlingS1
StirlingS1[n, m] gives the Stirling number of the first kind Sm
n .
Integer mathematical function (see Section A.3.10). nm Sm
gives the number of permutations of n elements
n
which contain exactly m cycles. See page 757. See also: StirlingS2. New in Version 1.
StirlingS2
StirlingS2[n, m] gives the Stirling number of the second kind m
n .
Integer mathematical function (see Section A.3.10). m
gives the number of ways of partitioning a set of n
n
elements into m non-empty subsets. See page 757. See also: StirlingS1. New in Version 1.
StreamPosition
StreamPosition[stream] returns an integer which specifies the position of the current point in
an open stream.
On most computer systems, the integer returned by StreamPosition gives the position counting from the
beginning of the file in bytes. See page 653. See also: SetStreamPosition . New in Version 2.
Streams
Streams[ ] gives a list of all streams that are currently open.
Streams["name"] lists only streams with the specified name.
The list returned by Streams can contain InputStream and OutputStream objects.
Links, OpenRead, OpenWrite, $Input, Options, SetOptions. New in Version 2.
See also:
String
String is the head of a character string "text".
Strings can contain any sequence of ordinary or special characters. x_String can be used as a pattern that
represents a string. String is used as a tag to indicate strings in Read, terminated by RecordSeparators
characters. In InputForm, special characters in strings are given as \[Name] or \:code. Except when they are
enclosed between \< and \>, newlines and any tabs which follow them are ignored when strings are input. See
page 406. See also: ToExpression, ToString, SyntaxQ, Characters. New in Version 1; modified in Version 3.
StringDrop StringLength
1291
StringDrop
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 nth character dropped.
StringDrop["string", {m, n}] gives "string" with characters m through n dropped.
StringDrop uses the standard sequence specification (see page 1040). Example:
StringDrop["abcdefgh", 2] # cdefgh . StringDrop["string", {m, n, s}] drops characters m through n in
steps of s. See page 407. See also: Drop, StringTake, StringPosition, StringReplacePart . New in Version 2;
modified in Version 4.
-
StringForm
StringForm["controlstring", expr , ... ] prints as the text of the controlstring, with the printed
forms of the expri embedded.
`i` in the control string indicates a point at which to print expri . `` includes the next expri not yet printed.
, `.` prints a raw ` in the output string.
StringForm acts as a wrapper, which affects printing, but not
evaluation. You can use StringForm to set up formatted output. Messages given as values for objects of the
form s::t are used as control strings for StringForm. See page 433. See also: SequenceForm, ToString,
Message. New in Version 1; modified in Version 5.0.
StringInsert
StringInsert["string", "snew", n] yields a string with "snew" inserted starting at position n
in "string".
StringInsert["string", "snew", -n] inserts at position n from the end of "string".
StringInsert["string", "snew", {n , n , ... }] inserts a copy of "snew" at each of the
positions ni .
Example: StringInsert["abcdefg", "XYZ", 2] # aXYZbcdefg . StringInsert["string", "snew", n] makes
the first character of snew the nth character in the new string. StringInsert["string", "snew", -n] makes the
last character of snew the nth character from the end of the new string. In
StringInsert["string", "snew", {n , n , . . . }] the ni are taken to refer to positions in "string" before any
insertion is done. See page 408. See also: StringReplacePart , Insert, StringPosition . New in Version 2;
modified in Version 3.
StringJoin
"s " <> "s " <> ... , StringJoin["s ", "s ", ... ] or StringJoin[{"s ", "s ", ... }] yields a
string consisting of a concatenation of the si .
Example: "the" <> " " <> "cat" # the cat . StringJoin has attribute Flat. When arguments are not
strings, StringJoin is left in symbolic form. See pages 407 and 412. See also: Join, Characters, StringInsert,
StringReplacePart . New in Version 1.
StringLength
StringLength["string"] gives the number of characters in a string.
Example: StringLength["tiger"] # 5 . StringLength counts special characters such as as single characters,
even if their full names involve many characters. See page 407. See also: Length, Characters. New in
Version 1; modified in Version 3.
StringMatchQ StringReplacePart
1292
StringMatchQ
StringMatchQ["string", "pattern"] yields True if string matches the specified string pattern,
and yields False otherwise.
The pattern string can contain literal characters, together with the metacharacters * and @ specified on page 1044.
Example: StringMatchQ["apppbb", "a*b"] # True . Setting the option IgnoreCase -> True makes
StringMatchQ treat lower- and upper-case letters as equivalent. Setting the option SpellingCorrection -> True
makes StringMatchQ allow strings to match even if a small fraction of their characters are different. See
page 411. See also: StringPosition, Equal, Names, MatchQ. New in Version 1.
StringPosition
StringPosition["string", "sub"] gives a list of the starting and ending character positions at
which "sub" appears as a substring of "string".
StringPosition["string", "sub", k] includes only the first k occurrences of "sub".
StringPosition["string", {"sub ", "sub ", ... }] gives positions of all the "subi ".
Example: StringPosition["abbaabbaa", "bb"] # 2, 3, 6, 7 . With the default option setting
Overlaps -> True, StringPosition includes substrings that overlap. With the setting Overlaps -> False such
substrings are excluded. Setting the option IgnoreCase -> True makes StringPosition treat lower- and
upper-case letters as equivalent. Example:
StringPosition["abAB", "a", IgnoreCase -> True] # 1, 1, 3, 3 . StringPosition returns sequence
specifications in the form used by StringTake, StringDrop and StringReplacePart . See page 409. See also:
Position, Characters, FindList, ReplaceList. New in Version 2.
StringReplace
StringReplace["string", "s " -> "sp "] or
StringReplace["string", {"s " -> "sp ", "s " -> "sp ", ... }] replaces the "si " by "spi "
whenever they appear as substrings of "string".
StringReplace goes through a string, testing substrings that start at each successive character position. On each
substring, it tries in turn each of the transformation rules you have specified. If any of the rules apply, it replaces
the substring, then continues to go through the string, starting at the character position after the end of the
substring. Delayed replacements of the form "s" :> expr can be given, so long as expr evaluates to a string every
time the replacement is used. Setting the option IgnoreCase -> True makes StringReplace treat lower- and
upper-case letters as equivalent. See page 410. See also: Replace, StringReplacePart , StringPosition,
ToLowerCase, ToUpperCase. New in Version 2; modified in Version 4.
StringReplacePart
StringReplacePart["string", "snew", {m, n}] replaces the characters at positions m through
n in "string" by "snew".
StringReplacePart["string", "snew", {{m , n }, {m , n }, ... }] inserts copies of "snew"
at several positions.
StringReplacePart["string", {"snew ", "snew ", ... }, {{m , n }, {m , n }, ... }]
replaces characters at positions mi through ni in "string" by "snewi ".
StringReplacePart uses position specifications in the form returned by StringPosition . When a list of "snewi "
is given, its length must be the same as the length of the list of positions. When multiple positions are given, all
refer to the original "string", before any replacements have been done. StringReplacePart[s, "", . . . ] can be
used to delete substrings. See page 409. See also: StringInsert, StringDrop, StringReplace, StringJoin,
ReplacePart. New in Version 3.
StringReverse StruveL
1293
StringReverse
StringReverse["string"] reverses the order of the characters in "string".
Example: StringReverse["abcde"] # edcba .
New in Version 2.
StringSkeleton
StringSkeleton[n] represents a sequence of n omitted characters in a string printed with
Short.
The standard print form for StringSkeleton is an ellipsis.
You can reset the print form of StringSkeleton.
New in Version 1.
StringTake
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 in "string".
StringTake uses the standard sequence specification (see page 1040). Example:
StringTake["abcdefg", 3] # abc . StringTake["string", {m, n, s}] gives characters m through n in steps
of s. See page 407. See also: Take, StringDrop, StringPosition. New in Version 2; modified in Version 4.
StringToStream
StringToStream["string"] opens an input stream for reading from a string.
StringToStream yields a stream of the form InputStream[String, n]. Operations like Read and Find work on
streams returned by StringToStream . You must use Close to close streams created by StringToStream . See
page 654. See also: Characters. New in Version 2.
StructuredSelection
StructuredSelection is an option for Cell which specifies whether to allow only complete
subexpressions in the cell to be selected interactively using the front end.
StructuredSelection is more often set at a global level than at the level of individual cells.
also: Selectable, DragAndDrop. New in Version 3.
See
StruveH
StruveH[n, z] gives the Struve function Hn z.
Mathematical function (see Section A.3.10).
z y$$
zy$
z
from to .
n y
zn
ndd .
See page 775.
StruveL
StruveL[n, z] gives the modified Struve function Ln z.
Mathematical function (see Section A.3.10). Ln z for integer n is related to the ordinary Struve function by
Ln iz iein Hn z. StruveL[n, z] has a branch cut discontinuity in the complex z plane running from to
. See page 775. See also: StruveH, BesselJ. New in Version 4.
Stub StyleDefinitions
1294
Stub
Stub is an attribute which specifies that if a symbol is ever used, Needs should automatically
be called on the context of the symbol.
Symbols with the Stub attribute are created by DeclarePackage. A symbol is considered used if its name
appears explicitly, not in the form of a string. Names["nameform"] and Attributes["nameform"] do not constitute
uses of a symbol. See pages 329 and 402. New in Version 2.
StyleBox
StyleBox[boxes, options] represents output in which boxes are shown with the specified option
settings.
StyleBox[boxes, "style"] uses the option setting for the specified style in the current
notebook.
You can use font options such as FontSize, FontWeight, FontSlant, FontFamily, FontColor and Background in
StyleBox. The following additional options can be given:
AutoSpacing
LineIndent
LineIndentMaxFraction
ScriptMinSize
ScriptSizeMultipliers
ShowContents
SpanLineThickness
SpanMaxSize
SpanMinSize
SpanSymmetric
True
1.0
0.5
4.0
0.71
True
Automatic
Automatic
Automatic
True
In StandardForm and InputForm input, StyleBox is by default ignored, so that StyleBox[box, spec] is
interpreted just as box would be. When StyleBox objects are nested, the options of the innermost one control the
display of particular boxes. In StandardForm, explicit StyleBox objects are output literally. You can use
DisplayForm to see the display form of such objects. See page 446. See also: StyleForm, AdjustmentBox,
FrameBox, Cell, ShowAutoStyles . New in Version 3.
StyleDefinitions
StyleDefinitions is an option for notebooks which gives definitions for the styles that can be
used in a notebook.
StyleDefinitions->"name.nb" specifies that style definitions from the notebook name.nb should be used. The
standard notebook front end comes with a selection of style definition notebooks containing styles appropriate for
particular purposes. StyleDefinitions->Notebook[. . . ] allows style definitions to be given explicitly. The
definition for a style named "s" is specified by the options for the first cell whose contents is StyleData["s"].
See page 603. See also: ScreenStyleEnvironment , PrintingStyleEnvironment . New in Version 3.
StyleForm SubscriptBox
1295
StyleForm
StyleForm[expr, options] prints using the specified style options.
StyleForm[expr, "style"] prints using the specified cell style in the current notebook.
You can use font options such as FontSize, FontWeight, FontSlant, FontFamily, FontColor and Background in
StyleForm. Additional options can be given as in StyleBox. StyleForm acts as a wrapper, which affects
printing, but not evaluation. StyleForm can be used to specify the style for text in graphics.
StyleForm[expr, "style"] will work only if the notebook front end is being used; StyleForm[expr, options] for
many options will work in all cases. When StyleForm objects are nested, the options of the innermost one
control the printing of a particular expression. See pages 443 and 558. See also: StylePrint, StyleBox,
TextStyle, $TextStyle, FormatType, Cell. New in Version 3.
StylePrint
StylePrint[expr, "style"] creates a new cell in the current notebook with the specified style,
and prints expr into it.
StylePrint[expr] uses the default style for the current notebook.
StylePrint creates a new cell immediately after the cell that is currently being evaluated.
StylePrint[expr, "style", opts] can be used to specify options for the cell that is created. StylePrint is a
special case of NotebookWrite. With a text-based front end, StylePrint does the same as Print. Cells
generated by StylePrint by default have GeneratedCell->True and CellAutoOverwrite->True .
StylePrint[expr, "style"] generates a whole cell with the specified style; Print[StyleForm[expr, "style"]]
generates a cell with the default style but containing a StyleBox object. See pages 477 and 575. See also:
CellPrint, Print, NotebookWrite, NotebookPrint, StyleForm. New in Version 3.
-
Subresultants
Subresultants[poly , poly , var] generates a list of the principal subresultant coefficients of
the polynomials poly and poly with respect to the variable var.
The first k subresultants of two polynomials a and b, both with leading coefficient one, are zero when a and b have
k common roots. Subresultants returns a list whose length is
Min[Exponent[poly , var], Exponent[poly , var]] + 1. See page 803. See also: Resultant, PolynomialGCD,
Eliminate, Minors. New in Version 4.
SubscriptBox
SubscriptBox[x, y] represents xy in input and output.
Inside \( . . . \) SubscriptBox[x, y] can be input as x \_ y. In a notebook a SubscriptBox can be created using
- or @ . moves out of the subscript. In StandardForm and InputForm, SubscriptBox[x, y] is
interpreted on input as Subscript[x, y]. The baseline of SubscriptBox[x, y] is taken to be the baseline of x.
SubscriptBox[x, y] is usually output with y in a smaller font than x. In StandardForm, explicit SubscriptBox
objects are output literally. You can use DisplayForm to see the display form of such objects. See page 445. See
also: SuperscriptBox, SubsuperscriptBox , UnderscriptBox , ScriptSizeMultipliers . New in Version 3.
SubsuperscriptBox SuperscriptBox
1296
SubsuperscriptBox
SubsuperscriptBox[x, y, z] represents xzy .
SubsuperscriptBox[x, y, z] can be input as x \_ y \% z when inside \( . . . \). In a notebook a
SubsuperscriptBox can be created by using - or @ to move to the subscript, then % to move to the
superscript. moves out of the subscript or superscript position. In StandardForm and InputForm,
SubsuperscriptBox[x, y, z] is interpreted on input as Power[Subscript[x, y], z]. The baseline of
SubsuperscriptBox[x, y, z] is taken to be the baseline of x. SubsuperscriptBox[x, y, z] is usually output
with y and z in a smaller font than x. In StandardForm, explicit SubsuperscriptBox objects are output literally.
You can use DisplayForm to see the display form of such objects. See page 445. See also: SubscriptBox ,
SuperscriptBox , UnderoverscriptBox . New in Version 3.
Subtract
x - y is equivalent to x + (-1 * y).
x - y is converted to x + (-1 * y) on input.
New in Version 1.
SubtractFrom
x -= dx subtracts dx from x and returns the new value of x.
SubtractFrom has the attribute HoldFirst. x -= dx is equivalent to x = x - dx.
Decrement, PreDecrement, Set. New in Version 1.
See also:
Sum
Sum[f, {i, imax}] evaluates the sum imax
i f .
Sum[f, {i, imin, imax}] starts with i = imin. Sum[f, {i, imin, imax, di}] uses steps di.
jmax
Sum[f, {i, imin, imax}, {j, jmin, jmax}, ... ] evaluates the multiple sum imax
iimin jjmin f.
Sum[f, {i, imax}] can be entered as )imax
f.
i
imax
can be entered as )i=imin f . The limits should be underscripts and overscripts of ) in normal input, and
subscripts and superscripts when embedded in other text. Sum evaluates its arguments in a non-standard way (see
page 1046). Sum uses the standard Mathematica iteration specification. The iteration variable i is treated as local.
In multiple sums, the range of the outermost variable is given first. The limits of summation need not be
numbers. They can be Infinity or symbolic expressions. If a sum cannot be carried out explicitly by adding up
a finite number of terms, Sum will attempt to find a symbolic result. In this case, f is first evaluated symbolically.
Sum can do essentially all sums that are given in standard books of tables. Sum is output in StandardForm using
). See pages 83 and 890. Implementation notes: see page 1071. See also: Do, Product, Table, NSum,
ZTransform, Total, RSolve. New in Version 1; modified in Version 3.
SuperscriptBox
SuperscriptBox[x, y] represents xy in input and output.
Inside \( . . . \) SuperscriptBox[x, y] can be input as x \^ y. In a notebook a SuperscriptBox can be created
using 6 or ^ . moves out of the superscript. In StandardForm and InputForm,
SuperscriptBox[x, y] is interpreted on input as Power[x, y]. The baseline of SuperscriptBox[x, y] is taken
to be the baseline of x. SuperscriptBox[x, y] is usually output with y in a smaller font than x. In
StandardForm, explicit SuperscriptBox objects are output literally. You can use DisplayForm to see the display
form of such objects. See page 445. See also: SubscriptBox, SubsuperscriptBox , OverscriptBox ,
ScriptSizeMultipliers . New in Version 3.
SurfaceColor SurfaceGraphics
1297
SurfaceColor
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.
SurfaceColor directives give surface properties which determine the effect of simulated illumination on polygons.
SurfaceColor directives can appear inside FaceForm directives. If no SurfaceColor directive is given, polygons
are assumed to be white diffuse reflectors of light, obeying Lamberts law of reflection, so that the intensity of
reflected light is cos times the intensity of incident light, where is the angle between the direction of the
incident light and the polygon normal. When c , there is no reflected light. SurfaceColor[GrayLevel[a]]
specifies that polygons should act as diffuse reflectors, but with albedo a. The intensity of reflected light is therefore
a times the intensity of the incident light, multiplied by cos, and is of the same color.
SurfaceColor[RGBColor[r, g, b]] specifies that the red, green and blue components of the reflected light should
be respectively r, g and b times those of the incident light, multiplied by cos. The second element in
SurfaceColor[dcol, scol] specifies a specular reflection component. scol must be a GrayLevel, Hue or RGBColor
specification. The color components of scol give the fractions of each color component in the incident intensity
which are reflected in a specular way by the surface. The parameter n gives the specular exponent. The intensity
of specularly reflected light at angle from the mirror-reflection direction falls off like cosn as increases. It is
zero when c . For real materials, n is typically between about 1 and a few hundred. With a coarse polygonal
mesh, however, values of n below 10 are usually most appropriate. The default value for n is 1. Mathematica
implements a version of the Phong lighting model, in which the intensity of reflected light is given schematically
by Iin d cos s cosn . The intensity of light from diffuse and specular reflection is added linearly for each
color component. The final color shown for a particular polygon is the sum of contributions from each light source,
and from ambient light. See page 546. See also: Lighting, LightSources , AmbientLight. New in Version 2.
SurfaceGraphics
SurfaceGraphics[array] is a representation of a three-dimensional plot of a surface, with
heights of each point on a grid specified by values in array.
SurfaceGraphics[array, shades] represents a surface, whose parts are shaded according to the
array shades.
SurfaceGraphics can be displayed using Show.
following additions:
ClipFill
ColorFunction
ColorFunctionScaling
HiddenSurface
Mesh
MeshRange
MeshStyle
Automatic
Automatic
True
True
True
Automatic
Automatic
SurfaceGraphics does not support the options PolygonIntersections and RenderAll available for Graphics3D.
For SurfaceGraphics , the default setting for BoxRatios is BoxRatios -> {1, 1, 0.4}. array should be a
rectangular array of real numbers, representing z values. There will be holes in the surface corresponding to any
array elements that are not real numbers. If array has dimensions m n, then shades must have dimensions
m n . The elements of shades must be GrayLevel, Hue or RGBColor directives, or SurfaceColor objects.
Graphics3D[SurfaceGraphics[ . . . ]] can be used to convert a SurfaceGraphics object into the more general
Graphics3D representation. SurfaceGraphics is generated by Plot3D and ListPlot3D. See page 537. See also:
ListPlot3D, Plot3D, ContourGraphics , DensityGraphics. New in Version 1.
Switch Table
1298
Switch
Switch[expr, form , value , form , value , ... ] evaluates expr, then compares it with each of
the formi in turn, evaluating and returning the valuei corresponding to the first match found.
Only the valuei corresponding to the first formi that matches expr is evaluated. Each formi is evaluated only when
the match is tried. If the last formi is the pattern _, then the corresponding valuei is always returned if this case is
reached. If none of the formi match expr, the Switch is returned unevaluated. Switch has attribute HoldRest.
You can use Break, Return and Throw in Switch. See page 345. See also: If, Condition, Which. New in
Version 1.
Symbol
Symbol["name"] refers to a symbol with the specified name.
All symbols, whether explicitly entered using Symbol or not, have head Symbol. x_Symbol can be used as a
pattern to represent any symbol. The string "name" in Symbol["name"] must be an appropriate name for a
symbol. It can contain any letters, letter-like forms, or digits, but cannot start with a digit. Symbol["name"]
creates a new symbol if none exists with the specified name. A symbol such as x has a name "x". If
Symbol["name"] creates a new symbol, it does so in the context specified by $Context. See page 1016. See also:
SymbolName, ToExpression, Unique, Remove. New in Version 1.
SymbolName
SymbolName[symbol] gives the name of the specified symbol.
Example: SymbolName[x] # "x" . SymbolName evaluates its input.
page 402. See also: ToString, Symbol. New in Version 3.
See
SyntaxLength
SyntaxLength["string"] finds the number of characters starting at the beginning of a string
that correspond to syntactically correct input for a single Mathematica expression.
SyntaxLength effectively returns the position of a syntax error, if one exists. If SyntaxLength returns a position
past the end of the string, it indicates that the string is syntactically correct as far as it goes, but needs to be
continued in order to correspond to input for a complete Mathematica expression. See page 466. See also:
SyntaxQ, $SyntaxHandler. New in Version 2.
SyntaxQ
SyntaxQ["string"] returns True if the string corresponds to syntactically correct input for a
single Mathematica expression, and returns False otherwise.
If SyntaxQ returns False, you can find the position of a syntax error using SyntaxLength. See page 466.
also: ToExpression, SyntaxLength, $SyntaxHandler, DelimiterFlashTime . New in Version 2.
See
Table
Table[expr, {imax}] generates a list of imax 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.
(continued)
Table
1299
(continued)
Table evaluates its arguments in a non-standard way (see page 1046). Example:
Table[f[i], {i, 4}] # f
1, f
2, f
3, f
4 . Table uses the standard Mathematica iteration
specification. Example: Table[i-j, {i, 2}, {j, 2}] # 0, 1, 1, 0 . You can use Table to build up
vectors, matrices and tensors. See page 115. See also: Range, DiagonalMatrix , IdentityMatrix , Array, Do, Sum,
Product, FunctionInterpolation , NestList, NestWhileList , SparseArray. Related package:
LinearAlgebra`MatrixManipulation` . New in Version 1.
TableAlignments
TableAlignments is an option for TableForm and MatrixForm which specifies how entries in
each dimension should be aligned.
TableAlignments -> {a , a , . . . } specifies alignments for successive dimensions. For dimensions that are given
as columns, possible alignments are Left, Center and Right. For dimensions that are given as rows, possible
alignments are Bottom, Center and Top. The default setting TableAlignments -> Automatic uses Left for
column alignment, and Bottom for row alignment. See page 442. See also: TableDirections , RowAlignments,
ColumnAlignments. New in Version 2.
TableDepth
TableDepth is an option for TableForm and MatrixForm which specifies the maximum
number of levels to be printed in tabular or matrix format.
TableForm[list, TableDepth -> n] prints elements in list below level n as ordinary lists, rather than arranging
them in tabular form. With the default setting TableDepth -> Infinity, as many levels as possible are printed in
tabular form. In TableForm, the levels printed need not consist of elements with the same list structure. In
MatrixForm, they must. See page 442. See also: ArrayDepth. New in Version 2.
TableDirections
TableDirections is an option for TableForm and MatrixForm which specifies whether
successive dimensions should be arranged as rows or columns.
TableDirections -> Column specifies that successive dimensions should be arranged alternately as columns and
rows, with the first dimension arranged as columns. TableDirections -> Row takes the first dimension to be
arranged as rows. TableDirections -> {dir , dir , . . . } specifies explicitly whether each dimension should be
arranged with Column or Row. See page 441. See also: TableSpacing. New in Version 2.
TableForm
TableForm[list] prints with the elements of list arranged in an array of rectangular cells.
The height of each row and the width of each column are determined by the maximum size of an element in the
row or column. TableForm prints a single-level list in a column. It prints a two-level list as a two-dimensional
table. More deeply nested lists are by default printed with successive dimensions alternating between rows and
columns. Arrays in which all sublists at a particular level are not of the same length display as ragged tables.
The following options can be given:
TableAlignments
TableDepth
TableDirections
TableHeadings
TableSpacing
Automatic
Infinity
Column
None
Automatic
See also:
TableHeadings TagSetDelayed
1300
TableHeadings
TableHeadings is an option for TableForm and MatrixForm which gives the labels to be
printed for entries in each dimension of a table or matrix.
TableHeadings -> None gives no labels in any dimension. TableHeadings -> Automatic gives successive integer
labels for each entry in each dimension. TableHeadings -> {{lab , lab , . . . }, . . . } gives explicit labels for
each entry. The labels can be strings or other Mathematica expressions. The labels are placed as headings for
rows or columns. See page 442. New in Version 2.
TableSpacing
TableSpacing is an option for TableForm and MatrixForm which specifies how many spaces
should be left between each successive row or column.
TableSpacing -> {s , s , . . . } specifies that si spaces should be left in dimension i. For columns, the spaces are
rendered as space characters. For rows, the spaces are rendered as blank lines. For TableForm,
TableSpacing -> Automatic yields spacings {1, 3, 0, 1, 0, 1, . . . }. See page 442. See also: RowSpacings,
ColumnSpacings , GraphicsSpacing . New in Version 2.
TagBox
TagBox[boxes, tag] displays as boxes but maintains tag to guide the interpretation of boxes on
input.
TagBox provides a way to store hidden information in Mathematica output. TagBox is generated sometimes in
StandardForm output, and often in TraditionalForm output. By convention, tag is typically a symbol that
corresponds to the head of the interpreted form of boxes. The following options can be given:
AutoDelete
DeletionWarning
Editable
Selectable
StripWrapperBoxes
False
False
True
True
False
whether
whether
whether
whether
whether
to
to
to
to
to
If you modify the displayed form of TagBox[boxes, tag] only boxes will be modified, and there is no guarantee
that correct correspondence with expr will be maintained. See page 447. See also: InterpretationBox , FormBox,
ToExpression. New in Version 3.
TagSet
f/: lhs = rhs assigns rhs to be the value of lhs, and associates the assignment with the symbol f.
TagSet defines upvalues or downvalues as appropriate. The symbol f in f/: lhs = rhs must appear in lhs as the
head of lhs, the head of the head, one of the elements of lhs, or the head of one of the elements. A common case
is f/: h[f [args]] = rhs. You can see all the rules associated with a particular symbol by typing ?symbol. If f
appears several times in lhs, then f/: lhs = rhs associates the assignment with each occurrence. When it appears
in symbolic form, TagSet is treated as a scoping construct (see Section A.3.8). See pages 319 and 1051. See also:
Set, UpSet. New in Version 1.
TagSetDelayed
f/: lhs := rhs assigns rhs to be the delayed value of lhs, and associates the assignment with the
symbol f.
See notes for TagSet and SetDelayed.
New in Version 1.
TagUnset Temporary
1301
TagUnset
f/: lhs =. removes any rules defined for lhs, associated with the symbol f.
Rules are removed only when their left-hand side is identical to lhs, and the tests in Condition given on the
right-hand side are also identical. See pages 1029 and 1052. See also: Clear, Unset. New in Version 1.
Take
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.
Take[list, {m, n, s}] gives elements m through n in steps of s.
Take[list, seq , seq , ... ] gives a nested list in which elements specified by seqi are taken at
level i in list.
Take uses the standard sequence specification (see page 1040). Examples: Take[{a,b,c,d,e}, 3] # a, b, c .
Take[{a,b,c,d,e}, -2] # d, e . Take[Range[15], {3, 12, 4}] # 3, 7, 11 . Take can be used on
an object with any head, not necessarily List. Take[list, seq , seq ] effectively extracts a submatrix from list.
Example: Take[{{a,b,c},{d,e,f}}, -1, 2] # d, e . , Applying Take to a SparseArray object normally
yields another SparseArray object. See pages 123 and 287. See also: Part, Drop, StringTake, Select, Cases,
Partition, PadLeft. Related package: LinearAlgebra`MatrixManipulation` . New in Version 1; modified in
Version 4.
Tan
Tan[z] gives the tangent of z.
Mathematical function (see Section A.3.10). The argument of Tan is assumed to be in radians. (Multiply by
Degree to convert from degrees.) Sin[z]/Cos[z] is automatically converted to Tan[z]. TrigFactorList[expr]
does decomposition. Tan is automatically evaluated when its argument is a simple rational multiple of ; for
more complicated rational multiples, FunctionExpand can sometimes be used. See page 761. See also: ArcTan,
Cot, TrigToExp, TrigExpand. New in Version 1.
Tanh
Tanh[z] gives the hyperbolic tangent of z.
Mathematical function (see Section A.3.10). Sinh[z]/Cosh[z] is automatically converted to Tanh[z].
TrigFactorList[expr] does decomposition. See page 761. See also: ArcTanh, Coth, TrigToExp, TrigExpand.
New in Version 1.
Temporary
Temporary is an attribute assigned to symbols which are created as local variables by Module.
Symbols with attribute Temporary are automatically removed when they are no longer needed.
attribute Temporary conventionally have names of the form aaa$nnn. See pages 329 and 383.
Unique. New in Version 2.
Symbols with
See also: Module,
TeXForm Text
1302
TeXForm
TeXForm[expr] prints as a TEX version of expr.
TeXForm produces plain TEX. Its output should be suitable for both LATEX and AMSTEX. TeXForm acts as a
wrapper, which affects printing, but not evaluation. TeXForm translates standard mathematical functions and
operations. Symbols with names like alpha and ALPHA that correspond to TEX symbols are translated into their
corresponding TEX symbols. Following standard mathematical conventions, single-character symbol names are
given in italic font, while multiple character names are given in roman font. All standard Mathematica box
structures are translated by TeXForm. Mathematica special characters are translated whenever possible to their TEX
equivalents. See pages 210 and 425. See also: TeXSave, StandardForm, TraditionalForm , MathMLForm. New in
Version 1; modified in Version 3.
TeXSave
TeXSave["file.tex"] saves a TEX version of the currently selected notebook in the front end.
TeXSave["file.tex", "source.nb"] saves a TEX version of the notebook from the file source.nb.
TeXSave["file.tex", notebook] saves a TEX version of the notebook corresponding to the
specified notebook object.
TeXSave has options for specifying such features as how to include graphics, what TEX style to use, and how each
notebook style should be rendered in TEX. TeXSave can often be accessed from an item in the Save As Special
menu in the notebook front end. See notes for TeXForm. See page 210. See also: TeXForm, MathMLForm. New
in Version 3.
Text
Text[expr, coords] is a graphics primitive that represents text corresponding to the printed
form of expr, centered at the point specified by coords.
The text is printed by default in OutputForm. Text can be used in both two- and three-dimensional graphics.
The coordinates can be specified either as {x, y, . . . } or as Scaled[{x, y, . . . }]. In two dimensions,
coordinates can also be specified using Offset. Text[expr, coords, offset] specifies an offset for the block of text
relative to the coordinates given. Giving an offset {sdx, sdy} specifies that the point {x, y} should lie at relative
coordinates {sdx, sdy} within the bounding rectangle that encloses the text. Each relative coordinate runs from -1
to +1 across the bounding rectangle. The offsets specified need not be in the range to . Here are sample
offsets to use in two-dimensional graphics:
{0, 0}
{-1, 0}
{1, 0}
{0, -1}
{0, 1}
Text[expr, coords, offset, dir] specifies the orientation of the text is given by the direction vector dir. Possible
values of dir are:
{1, 0}
ordinary horizontal text
{0, 1}
vertical text reading from bottom to top
{0, -1} vertical text reading from top to bottom
{-1, 0} horizontal upside-down text
(continued)
Text
1303
(continued)
Text in three-dimensional graphics is placed at a position that corresponds to the projection of the point
{x, y, z} specified. Text is drawn in front of all other objects. The font or style for text can be specified using
StyleForm or using the TextStyle option. If no such specifications are given, the font is determined from the
setting for TextStyle for the whole plot, which is in turn by default given by the global variable $TextStyle.
You can specify the color of text using CMYKColor, GrayLevel, Hue and RGBColor directives. The option
CharacterEncoding for Display can be used to specify what raw character encoding to use for character strings in
Text objects. The following options can be given:
Background
FormatType
TextStyle
None
StandardForm
Automatic
background color
format type
style specification
TextAlignment
TextAlignment is an option for Cell which specifies how successive lines of text should be
aligned.
Possible settings are:
Left or -1
Right or +1
Center or 0
x
TextAlignment can be used both for ordinary text and for Mathematica expressions.
TextJustification , ColumnAlignments , PageWidth. New in Version 3.
See also:
TextJustification
TextJustification is an option for Cell which specifies how much lines of text can be
stretched in order to make them be the same length.
TextJustification->0 does no stretching, and leads to ragged text boundaries. TextJustification->1 does full
justification, and forces all complete lines to be the same length. No stretching is done on lines that end with
explicit RETURN characters. With settings for TextJustification between 0 and 1, partial justification is done.
With TextJustification->s, Mathematica will take the amount by which each broken line is shorter than
PageWidth, and then insert within the line a total amount of space equal to s times this. If TextJustification is
not 0, the standard Mathematica front end will dynamically adjust the lengths of lines as you enter text. See
page 609. See also: TextAlignment , Hyphenation, PageWidth, AutoSpacing, ButtonExpandable . New in
Version 3.
TextStyle
TextStyle is an option for graphics functions and for Text which specifies the default style
and font options with which text should be rendered.
The following forms of settings can be used:
"style"
{opt ->val , . . . }
{"style", opt ->val , . . . }
The options that can be given are as in StyleForm. "style" settings can only be used when a notebook front
end is present. The default setting is TextStyle :> $TextStyle. The style specified by TextStyle in a graphics
object is used by default for all text, including labels and tick marks. See page 556. See also: StyleForm,
$TextStyle, PlotStyle, FormatType. New in Version 3.
Thickness Throw
1304
Thickness
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.
Thickness can be used in both two- and three-dimensional graphics. The initial default is Thickness[0.004] for
two-dimensional graphics, and Thickness[0.001] for three-dimensional graphics See page 501. See also:
AbsoluteThickness , PointSize, Dashing, PlotStyle. New in Version 1.
Thread
Thread[f [args]]
Thread[f [args],
Thread[f [args],
Thread[f [args],
Thread[f [args],
Example: Thread[f[{a,b}, c, {d,e}]] # f
a, c, d, f
b, c, e . Functions with attribute Listable are
automatically threaded over lists. All the elements in the specified args whose heads are h must be of the same
length. Arguments that do not have head h are copied as many times as there are elements in the arguments that
do have head h. Thread uses the standard sequence specification (see page 1040). See page 256. See also:
Distribute, Map, Inner, MapThread. New in Version 1.
ThreeJSymbol
ThreeJSymbol[{j , m }, {j , m }, {j
, m
}] gives the values of the Wigner 3-j symbol.
The 3-j symbols vanish except when m m m
and the ji satisfy a triangle inequality. The parameters of
ThreeJSymbol can be integers, half-integers or symbolic expressions. The Clebsch-Gordan coefficients and 3-j
!
j
j
j
j j j
symbols in Mathematica satisfy the relation Cm m
m m
j j j
. See page 760. See
m m m
also: ClebschGordan, SixJSymbol, SphericalHarmonicY . New in Version 2.
Through
Through[p[f , f ][x]] gives p[f [x], f [x]].
Through[expr, h] performs the transformation wherever h occurs in the head of expr.
Example: Through[(f + g)[x, y]] # f
x, y g
x, y . Through distributes operators that appear inside the
heads of expressions. See page 254. See also: Operate. New in Version 1.
Throw
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.
You can use Throw and Catch to exit functions such as Nest, Fold, FixedPoint and Scan. tag can be any
expression. tag in Throw[value, tag] is re-evaluated every time it is compared to form in Catch[expr, form]. An
error is generated and an unevaluated Throw is returned if there is no appropriate enclosing Catch to catch the
Throw. See page 350. See also: Return, Goto, Interrupt, Abort, Sow. New in Version 1; modified in Version 3.
Ticks TimeConstraint
1305
Ticks
Ticks is an option for graphics functions that specifies tick marks for axes.
The following settings can be given for Ticks:
None
Automatic
{xticks, yticks, . . . }
With the Automatic setting, tick marks are usually placed at points whose coordinates have the minimum
number of digits in their decimal representation. For each axis, the following tick mark options can be given:
None
Automatic
{x , x , . . . }
{{x , label }, {x , label }, . . . }
{{x , label , len },. . . }
{{x , label , {plen , mlen }}, . . . }
{{x , label , len , style }, . . . }
func
If no explicit labels are given, the tick mark labels are given as the numerical values of the tick mark positions.
Any expression can be given as a tick mark label. The expressions are formatted in OutputForm. Tick mark
lengths are given as a fraction of the distance across the whole plot. Tick mark styles can involve graphics
directives such as RGBColor and Thickness. The tick mark function func[xmin, xmax] may return any other tick
mark option. Ticks can be used in both two- and three-dimensional graphics. AbsoluteOptions gives the
explicit form of Ticks specifications when Automatic settings are given. See pages 512 and 552. See also: Axes,
AxesLabel, FrameTicks, GridLines, MeshRange. New in Version 1.
TimeConstrained
TimeConstrained[expr, t] evaluates expr, stopping after t seconds.
TimeConstrained[expr, t, failexpr] returns failexpr if the time constraint is not met.
TimeConstrained generates an interrupt to abort the evaluation of expr if the evaluation is not completed within
the specified time. TimeConstrained evaluates failexpr only if the evaluation is aborted. TimeConstrained
returns $Aborted if the evaluation is aborted and no failexpr is specified. TimeConstrained is accurate only down
to a granularity of at least $TimeUnit seconds. Aborts generated by TimeConstrained are treated just like those
generated by Abort, and can thus be overruled by AbortProtect. See page 712. See also: MemoryConstrained ,
AbsoluteTiming, Timing, $IterationLimit , $RecursionLimit , Pause, Abort, TimeConstraint. New in Version 1.
TimeConstraint
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.
The default setting for TimeConstraint is 300 (corresponding to 5 minutes) in Simplify and Infinity in
FullSimplify. Settings for TimeConstraint give only the maximum time to be spent in doing a particular
transformation on a particular subpart; the total time spent in processing the whole expression may be considerably
larger. Changing the setting for TimeConstraint will never affect the validity of a result obtained from Simplify
or FullSimplify, but smaller settings may prevent the simplest possible form from being found. Since different
computer systems run at different speeds, the same setting for TimeConstraint can lead to different results on
different systems. See page 814. See also: ExcludedForms, TimeConstrained, AbsoluteTiming. New in
Version 3.
Times Timing
1306
Times
x*y*z, xyz or x y z represents a product of terms.
The character is entered as , * , or \[Times]. It is not the same as \[Cross]. Times has attributes Flat,
Orderless and OneIdentity. The default value for arguments of Times, as used in x_. patterns, is 1. Times[ ]
is taken to be 1. Times[x] is x. 0 x evaluates to 0, but 0.0 x is left unchanged. Unlike other functions, Times
applies built-in rules before user-defined ones. As a result, it is not possible to make definitions such as 2*2=5.
See page 29. See also: Divide, NonCommutativeMultiply , Dot. New in Version 1; modified in Version 3.
TimesBy
x *= c multiplies x by c and returns the new value of x.
TimesBy has the attribute HoldFirst.
AddTo, Set. New in Version 1.
x *= c is equivalent to x = x*c.
TimeUsed
TimeUsed[ ] gives the total number of seconds of CPU time used so far in the current
Mathematica session.
TimeUsed records only CPU time actually used by the Mathematica kernel. It does not include time used by external
processes called by the kernel. It also does not include time during pauses produced by Pause. TimeUsed is
accurate only down to a granularity of at least $TimeUnit seconds. See page 710. See also: Timing,
SessionTime. New in Version 2.
TimeZone
TimeZone[ ] gives the time zone set for your computer system.
The time zone gives the number of hours which must be added to Greenwich mean time (GMT) to obtain local
time. U.S. eastern standard time (EST) corresponds to time zone . Daylight saving time corrections must be
included in the time zone, so U.S. eastern daylight time (EDT) corresponds to time zone
. See page 709. See
also: Date, AbsoluteTime. Related package: Miscellaneous`CityData` . New in Version 2.
Timing
Timing[expr] evaluates expr, and returns a list of time used, together with the result obtained.
Timing gives the CPU time in seconds, multiplied by the symbol Second. Timing has attribute HoldAll.
Timing[expr;] will give {timing, Null}. First[Timing[expr;]] /. Second->1 yields just the number of
seconds required for the evaluation of expr. Timing is accurate only down to a granularity of at least $TimeUnit
seconds. Timing includes only CPU time spent in the Mathematica kernel. It does not include time spent in
external processes connected via MathLink or otherwise. Nor does it include time spent in the Mathematica front
end. Timing[expr] includes only time spent in the evaluation of expr, and not, for example, in the formatting or
printing of the result. Timing should give accurate results on all operating systems where the running of
processes is specifically scheduled by the operating system. On early versions of Microsoft Windows and Mac OS
where Mathematica must explicitly yield in order for other processes to run, Timing may substantially overestimate
the time used within Mathematica. See page 711. See also: AbsoluteTiming , TimeUsed, TimeConstrained ,
SessionTime, AbsoluteTime . New in Version 1.
ToBoxes ToExpression
1307
ToBoxes
ToBoxes[expr] generates boxes corresponding to the printed form of expr in StandardForm .
ToBoxes[expr, form] gives the boxes corresponding to output in the specified form.
ToBoxes uses any relevant definitions given for Format and MakeBoxes. You can see how box structures
generated by ToBoxes would be displayed by using DisplayForm. See page 428. See also: ToString,
ToExpression, MakeBoxes, HoldForm, DisplayForm. New in Version 3.
ToCharacterCode
ToCharacterCode["string"] gives a list of the integer codes corresponding to the characters in
a string.
ToCharacterCode["string", "encoding"] gives integer codes according to the specified
encoding.
ToCharacterCode handles both ordinary and special characters. ToCharacterCode["string"] returns standard
internal character codes used by Mathematica, which are the same on all computer systems. For characters on an
ordinary American English keyboard, the character codes follow the ASCII standard. For common European
languages, they follow the ISO Latin-1 standard. For other characters, they follow the Unicode standard.
Mathematica defines various additional characters in private Unicode space, with character codes between 64256
and 64300. Character codes returned by ToCharacterCode["string"] lie between 0 and 65535. Encodings
supported in ToCharacterCode["string", "encoding"] are listed in the notes for $CharacterEncoding . If a
particular character has no character code in a given encoding, ToCharacterCode returns None in place of a
character code. ToCharacterCode[{"s ", "s ", . . . }] gives a list of the lists of integer codes for each of the si .
See page 417. See also: FromCharacterCode , Characters, CharacterRange, $CharacterEncoding , DigitQ,
LetterQ, InputForm. New in Version 2; modified in Version 3.
ToDate
ToDate[time] converts an absolute time in seconds since the beginning of January 1, 1900 to a
date of the form {y, m, d, h, m, s}.
ToDate converts between the forms returned by AbsoluteTime and Date.
time and the date are to be given in the same time zone. See page 710.
Miscellaneous`Calendar` . New in Version 2.
-
ToExpression
ToExpression[input] gives the expression obtained by interpreting strings or boxes as
Mathematica input.
ToExpression[input, form] uses interpretation rules corresponding to the specified form.
ToExpression[input, form, h] wraps the head h around the expression produced before
evaluating it.
Example: ToExpression["1 + 1"] # 2 . - form can be InputForm, StandardForm, TraditionalForm or
MathMLForm. ToExpression["string"] uses InputForm interpretation rules. ToExpression[boxes] uses
StandardForm interpretation rules. ToExpression prints a message and returns $Failed if it finds a syntax error.
ToExpression does not call $SyntaxHandler. The input given in ToExpression can correspond to multiple
Mathematica expressions. ToExpression processes each one in turn, just like Get.
ToExpression[input, form, Hold] can be used to convert input to an expression, but with the expression
wrapped in Hold to prevent evaluation. ToExpression uses any relevant definitions given for MakeExpression.
See page 428. See also: Symbol, MakeExpression , ToString, ToBoxes, SyntaxQ, SyntaxLength, Read, Get. New
in Version 1; modified in Version 4.1.
ToFileName ToRadicals
1308
ToFileName
ToFileName["directory", "name"] assembles a full file name from a directory name and a file
name.
ToFileName[{dir , dir , ... }, name] assembles a full file name from a hierarchy of directory
names.
ToFileName[{dir , dir , ... }] assembles a single directory name from a hierarchy of directory
names.
ToFileName works differently on different computer systems. ToFileName just creates a file name; it does not
actually search for the file specified. ToFileName["", "name"] gives "name". See page 639. See also:
DirectoryName, Get, $Input. New in Version 3.
Together
Together[expr] puts terms in a sum over a common denominator, and cancels factors in the
result.
1
Together makes a sum of terms into a single rational
1 x x
function. The denominator of the result of Together is typically the lowest common multiple of the denominators
of each of the terms in the sum. Together avoids expanding out denominators unless it is necessary. Together
is effectively the inverse of Apart. Together[expr, Modulus->p] generates a result modulo p.
Together[expr, Extension->Automatic] allows operations to be performed on algebraic numbers in expr.
Together[expr, Trig -> True] treats trigonometric functions as rational functions of exponentials, and
manipulates them accordingly. See page 802. See also: Cancel, Collect, Factor, PolynomialGCD. New in
Example: Together[1/x + 1/(1-x)] # .
TokenWords
TokenWords is an option for Read and related functions which gives a list of token words to be
used to delimit words.
The setting for TokenWords is a list of strings which are used as delimiters for words to be read. The delimiters
specified by TokenWords are themselves returned as words. See page 646. See also: WordSeparators . New in
Version 2.
ToLowerCase
ToLowerCase[string] yields a string in which all letters have been converted to lower case.
ToLowerCase handles both ordinary and special characters. Variant upper-case characters such as
\[CurlyCapitalUpsilon] are converted to their non-variant lower-case forms. See page 413. See also:
LowerCaseQ, ToUpperCase, StringReplace, IgnoreCase. New in Version 2; modified in Version 3.
ToRadicals
ToRadicals[expr] attempts to express all Root objects in expr in terms of radicals.
ToRadicals can always give expressions in terms of radicals when the highest degree of the polynomial that
appears in any Root object is four. There are some cases in which expressions involving radicals can in principle
be given, but ToRadicals cannot find them. , If Root objects in expr contain parameters, ToRadicals[expr] may
yield a result that is not equal to expr for all values of the parameters. See page 826. See also: Solve, NSolve,
RootReduce, Roots. New in Version 3.
ToRules ToUpperCase
1309
ToRules
ToRules[eqns] takes logical combinations of equations, in the form generated by Roots and
Reduce, and converts them to lists of rules, of the form produced by Solve.
Example: {ToRules[x==1 || x==2]} # x 1, x 2 . ToRules discards nonequalities (!=), and thus
gives only generic solutions. See page 820. New in Version 1.
ToString
ToString[expr] gives a string corresponding to the printed form of expr in OutputForm .
ToString[expr, form] gives the string corresponding to output in the specified form.
ToString supports the same set of options as OpenAppend, with default settings FormatType -> OutputForm,
PageWidth -> Infinity, TotalWidth -> Infinity. ToString uses any relevant definitions given for Format and
MakeBoxes. See page 428. See also: ToBoxes, ToExpression, HoldForm, WriteString, SymbolName. New in
Version 1; modified in Version 3.
,
Total
Total[list] gives the total of the elements in list.
Total[list, n] totals all elements down to level n.
Total[list] is equivalent to Apply[Plus, list]. Total[f[e , e , . . . ], 1] gives the sum of the ei for any head f.
Total is defined so that Total[{{x , y , . . . }, {x , y , . . . }, . . . }] gives
{Total[{x , x , . . . }], Total[{y , y , . . . }]}. Total[list, Method->"CompensatedSummation"] uses
compensated summation to reduce numerical error in the result. Total works with SparseArray objects. See
pages 109 and 924. See also: Plus, Tr, Mean, Count, Norm, Sum, Max. New in Version 5.0.
TotalWidth
TotalWidth is an option which can be set for output streams to specify the maximum total
number of characters of text that should be printed for each output expression. Short forms of
expressions are given if the number of characters needed to print the whole expression is too
large.
TotalWidth bounds the actual numbers of characters generated. Line breaks are not counted.
TotalWidth -> Infinity allows expressions of any length to be printed.
SetOptions[stream, TotalWidth -> n] resets the total width allowed for an open stream. See also: Short,
Skeleton, PageWidth. New in Version 1.
ToUpperCase
ToUpperCase[string] yields a string in which all letters have been converted to upper case.
ToUpperCase handles both ordinary and special characters. Variant lower-case characters such as \[CurlyPhi] are
converted to their non-variant upper-case forms. See page 413. See also: UpperCaseQ, ToLowerCase,
StringReplace, IgnoreCase. New in Version 2; modified in Version 3.
Tr TraceAbove
1310
Tr
Tr[list] finds the trace of the matrix or tensor list.
Tr[list, f] finds a generalized trace, combining terms with f instead of Plus.
Tr[list, f, n] goes down to level n in list.
Tr[list] sums the diagonal elements list[[i, i, . . . ]]. Tr works for rectangular as well as square matrices and
tensors. , Tr can be used on SparseArray objects. See page 905. See also: Total, Transpose, Det,
DiagonalMatrix , Eigenvalues. New in Version 4.
Trace
Trace[expr] generates a list of all expressions used in the evaluation of expr.
Trace[expr, form] includes only those expressions which match form.
Trace[expr, s] includes all evaluations which use transformation rules associated with the
symbol s.
In general, form in Trace[expr, form] is compared both with each complete expression that is evaluated, and with
the tag associated with any transformation rule used in the evaluation. Trace[expr, lhs -> rhs] picks out
expressions which match lhs, then replaces them with rhs in the list returned. All expressions in the list returned
by Trace are wrapped in HoldForm. Trace returns a set of nested lists. Each individual list corresponds to a
single evaluation chain, which contains the sequence of forms found for a particular expression. The list has sublists
which give the histories of subsidiary evaluations. Example: Trace[2 3 + 4] # 2 3, 6, 6 4, 10 . The
following options can be given:
MatchLocalNames
TraceAbove
TraceBackward
TraceDepth
TraceForward
TraceOff
TraceOn
TraceOriginal
True
False
False
Infinity
False
None
_
False
During the execution of Trace, the settings for the form argument, and for the options TraceOn and TraceOff, can
be modified by resetting the values of the global variables $TracePattern, $TraceOn and $TraceOff, respectively.
See page 356. See also: TraceDialog, TracePrint, TraceScan, EvaluationMonitor . New in Version 2.
TraceAbove
TraceAbove is an option for Trace and related functions which specifies whether to include
evaluation chains which contain the evaluation chain containing the pattern form sought.
TraceAbove -> True includes the first and last expressions in all evaluation chains within which the evaluation
chain containing form occurs. TraceAbove -> All includes all expressions in these evaluation chains.
TraceAbove -> {backward, forward} allows you to specify separately which expressions to include in the
backward and forward directions. Using TraceAbove, you can see the complete paths by which expressions
matching form arose during an evaluation. See page 363. See also: StackComplete. New in Version 2.
TraceBackward TraceOff
1311
TraceBackward
TraceBackward is an option for Trace and related functions which specifies whether to
include preceding expressions on the evaluation chain that contains the pattern form sought.
TraceBackward -> True includes the first expression on the evaluation chain that contains form.
TraceBackward -> All includes all expressions before form on the evaluation chain that contains form.
TraceBackward allows you to see the previous forms that an expression had during an evaluation. See
page 363. See also: StackComplete . New in Version 2.
TraceDepth
TraceDepth is an option for Trace and related functions which specifies the maximum nesting
of evaluation chains that are to be included.
Setting TraceDepth -> n keeps only parts down to level n in nested lists generated by Trace. By setting
TraceDepth, you can make Trace and related functions skip over inner parts of a computation, making their
operation more efficient. See page 362. See also: TraceOff. New in Version 2.
TraceDialog
TraceDialog[expr] initiates a dialog for every expression used in the evaluation of expr.
TraceDialog[expr, form] initiates a dialog only for expressions which match form.
TraceDialog[expr, s] initiates dialogs only for expressions whose evaluations use
transformation rules associated with the symbol s.
See notes for Trace. The expression to be evaluated when a dialog is called is given as Out[$Line] of the dialog,
wrapped in HoldForm. The expression can be seen by asking for % when the dialog is first started. Any value
returned from the dialog is discarded. TraceDialog[expr] returns the result of evaluating expr. See page 366.
New in Version 2.
TraceForward
TraceForward is an option for Trace and related functions which specifies whether to include
later expressions on the evaluation chain that contains the pattern form sought.
TraceForward -> True includes the final expression on the evaluation chain that contains form.
TraceForward -> All includes all expressions after form on the evaluation chain that contains form.
TraceForward allows you to see the transformations performed on an expression generated during an evaluation.
See page 362. New in Version 2.
TraceOff
TraceOff is an option for Trace and related functions which specifies forms inside which
tracing should be switched off.
The setting for TraceOff gives a pattern which is compared with expressions to be evaluated. If the pattern
matches the expression, then tracing will be switched off while that expression is being evaluated. The pattern is
also tested against tags associated with the evaluation. You can use TraceOff to avoid tracing inner parts of a
computation. The default setting TraceOff -> None never switches off tracing. TraceOn will not work inside
TraceOff. During the execution of Trace, the settings for TraceOn and TraceOff can be modified by resetting
the values of the global variables $TraceOn and $TraceOff. See page 360. See also: TraceDepth, TraceOn.
New in Version 2.
TraceOn TraceScan
1312
TraceOn
TraceOn is an option for Trace and related functions which specifies when tracing should be
switched on.
With the setting TraceOn -> patt, Trace and related functions do not start tracing until they encounter expressions
to evaluate which match the pattern patt. This pattern is also tested against tags associated with the evaluation.
TraceOff can be used within tracing switched on by TraceOn. Once tracing has been switched off by
TraceOff, however, TraceOn will not switch it on again. During the execution of Trace, the settings for TraceOn
and TraceOff can be modified by resetting the values of the global variables $TraceOn and $TraceOff. See
page 360. See also: TraceOff. New in Version 2.
TraceOriginal
TraceOriginal is an option for Trace and related functions which specifies whether to test
the form of each expression before its head and arguments are evaluated.
With the default TraceOriginal -> False, the forms of expressions generated during an evaluation are tested only
after their head and arguments have been evaluated. In addition, evaluation chains for expressions which do not
change under evaluation are not included. With TraceOriginal -> True, the forms before evaluation of the head
and arguments are also tested, and evaluation chains for expressions which do not change under evaluation are
included. See page 364. New in Version 2.
TracePrint
TracePrint[expr] prints all expressions used in the evaluation of expr.
TracePrint[expr, form] includes only those expressions which match form.
TracePrint[expr, s] includes all evaluations which use transformation rules associated with
the symbol s.
See notes for Trace. TracePrint indents its output in correspondence with the nesting levels for lists generated
by Trace. The indentation is done using the print form defined for the object Indent[d]. TracePrint prints the
forms of expressions before any of their elements are evaluated. TracePrint does not support the TraceBackward
option of Trace. TracePrint yields only the forward part of the output specified by the option setting
TraceAbove -> All. TracePrint[expr] returns the result of evaluating expr. See page 365. New in Version 2.
TraceScan
TraceScan[f, expr] applies f to all expressions used in the evaluation of expr.
TraceScan[f, expr, form] includes only those expressions which match form.
TraceScan[f, expr, s] includes all evaluations which use transformation rules associated with
the symbol s.
TraceScan[f, expr, form, fp] applies f before evaluation and fp after evaluation to expressions
used in the evaluation of expr.
See notes for Trace. All expressions are wrapped in HoldForm to prevent evaluation before f or fp are applied to
them. The function fp is given as arguments both the form before evaluation and the form after evaluation.
TraceScan[f, expr] returns the result of evaluating expr. See page 366. New in Version 2.
TraditionalForm TrigExpand
1313
TraditionalForm
TraditionalForm[expr] prints as an approximation to the traditional mathematical notation
for expr.
Output from TraditionalForm cannot necessarily be given as unique and unambiguous input to Mathematica.
TraditionalForm inserts invisible TagBox and InterpretationBox constructs into the box form of output it
generates, to allow unique interpretation. TraditionalForm can be edited in the notebook front end.
TraditionalForm uses special characters as well as ordinary keyboard characters. TraditionalForm incorporates
a large collection of rules for approximating traditional mathematical notation. TraditionalForm prints functions
in Global` context in the form f(x). ToExpression[boxes, TraditionalForm] will attempt to convert from
TraditionalForm. The notebook front end contains menu items for conversion to and from TraditionalForm.
See page 425. See also: StandardForm, TeXForm, MakeExpression , ToBoxes, MathMLForm. New in Version 3.
TransformationFunctions
TransformationFunctions is an option for Simplify and FullSimplify which gives the list
of functions to apply to try to transform parts of an expression.
The default setting TransformationFunctions->Automatic uses a built-in collection of transformation functions.
TransformationFunctions->{f , f , . . . } uses only the functions fi .
TransformationFunctions->{Automatic, f , f , . . . } uses built-in transformation functions together with the
functions fi . See page 815. See also: Simplify, FullSimplify , ReplaceAll, ExcludedForms , FunctionExpand .
New in Version 4.
Transpose
Transpose[list] transposes the first two levels in list.
Transpose[list, {n , n , ... }] transposes list so that the kth level in list is the nk th level in the
result.
Example: Transpose[{{a,b},{c,d}}] # a, c, b, d . Transpose gives the usual transpose of a matrix.
Acting on a tensor Ti i i
Transpose gives the tensor Ti i i
. Transpose[list, {n , n , . . . }] gives the tensor
Tin in . So long as the lengths of the lists at particular levels are the same, the specifications nk do not
necessarily have to be distinct. Example:
Transpose[Array[a, {3, 3}], {1, 1}] # a
1, 1, a
2, 2, a
3, 3 . , Transpose works on SparseArray
objects. See page 905. See also: Flatten, Thread, Tr. Related package: LinearAlgebra`MatrixManipulation` .
New in Version 1.
TreeForm
TreeForm[expr] prints with different levels in expr shown at different depths.
See pages 236 and 237.
Version 1.
New in
TrigExpand
TrigExpand[expr] expands out trigonometric functions in expr.
TrigExpand operates on both circular and hyperbolic functions. TrigExpand splits up sums and integer multiples
that appear in arguments of trigonometric functions, and then expands out products of trigonometric functions into
sums of powers, using trigonometric identities when possible. See page 811. See also: TrigFactor, TrigReduce,
TrigToExp, Expand, FunctionExpand , Simplify, FullSimplify. New in Version 3.
TrigFactor UnderoverscriptBox
1314
TrigFactor
TrigFactor[expr] factors trigonometric functions in expr.
TrigFactor operates on both circular and hyperbolic functions. TrigFactor splits up sums and integer multiples
that appear in arguments of trigonometric functions, and then factors resulting polynomials in trigonometric
functions, using trigonometric identities when possible. See page 811. See also: TrigExpand, TrigReduce,
TrigToExp, Factor, Simplify, FullSimplify. New in Version 3.
TrigFactorList
TrigFactorList[expr] factors trigonometric functions in expr, yielding a list of lists containing
trigonometric monomials and exponents.
See notes for TrigFactor. TrigFactorList tries to give results in terms of powers of Sin, Cos, Sinh and Cosh,
explicitly decomposing functions like Tan. See page 811. See also: FactorList, TrigToExp. New in Version 3.
TrigReduce
TrigReduce[expr] rewrites products and powers of trigonometric functions in expr in terms of
trigonometric functions with combined arguments.
TrigReduce operates on both circular and hyperbolic functions. Given a trigonometric polynomial, TrigReduce
typically yields a linear expression involving trigonometric functions with more complicated arguments. See
page 811. See also: TrigExpand, TrigFactor, TrigToExp, Simplify, FullSimplify . New in Version 3.
TrigToExp
TrigToExp[expr] converts trigonometric functions in expr to exponentials.
TrigToExp operates on both circular and hyperbolic functions, and their inverses.
ExpToTrig, TrigReduce, ComplexExpand . New in Version 3.
See also:
True
True is the symbol for the Boolean value true.
See page 85.
New in Version 1.
TrueQ
TrueQ[expr] yields True if expr is True, and yields False otherwise.
Example: TrueQ[x==y] # False . You can use TrueQ to assume that a test fails when its outcome is not clear.
TrueQ[expr] is equivalent to If[expr, True, False, False]. See page 346. See also: If, Condition, SameQ.
New in Version 1.
UnderoverscriptBox
z
New
UnderscriptBox Union
1315
UnderscriptBox
UnderscriptBox[x, y] represents x in input and output.
y
baseline of x. UnderscriptBox[
x, y] is usually output with y in a smaller font than x. With the option setting
LimitsPositioning->True y is placed in an underscript position when the whole UnderscriptBox is displayed
large, and in a subscript position when it is displayed smaller. In StandardForm , explicit UnderscriptBox objects
are output literally. You can use DisplayForm to see the display form of such objects. See page 445. See also:
OverscriptBox, UnderoverscriptBox , SubscriptBox, GridBox, ScriptSizeMultipliers . New in Version 3.
Unequal
lhs != rhs or lhs rhs returns False if lhs and rhs are identical.
x y can be entered as x \[NotEqual] y or x H != H y. lhs rhs returns True if lhs and rhs are determined to be
unequal by comparisons between numbers or other raw data, such as strings. Approximate numbers are
considered unequal if they differ beyond their last two decimal digits. e e e
. . . gives True only if none
of the ei are equal. 2 3 2 # False . lhs rhs represents a symbolic condition that can be generated and
manipulated by functions like Reduce and LogicalExpand . Unequal[e] gives True. For exact numeric
quantities, Unequal internally uses numerical approximations to establish inequality. This process can be affected by
the setting of the global variable $MaxExtraPrecision . In StandardForm, Unequal is printed using . See
page 86. See also: Equal, UnsameQ, Order. New in Version 1; modified in Version 3.
Unevaluated
Unevaluated[expr] represents the unevaluated form of expr when it appears as the argument
to a function.
f [Unevaluated[expr]] effectively works by temporarily setting attributes so that f holds its argument unevaluated,
then evaluating f [expr]. Example: Length[Unevaluated[5+6]] # 2 . See page 339. See also: Hold,
HoldFirst, ReplacePart. New in Version 2.
Uninstall
Uninstall[link] terminates an external program started by Install, and removes Mathematica
definitions set up by it.
The argument of Uninstall is a LinkObject representing a MathLink link as returned by Install. Uninstall
calls Unset to remove definitions set up by Install. See page 659. See also: Install, LinkClose, Close. New
in Version 2; modified in Version 3.
Union
Union[list , list , ... ] gives a sorted list of all the distinct elements that appear in any of the
listi .
Union[list] gives a sorted version of a list, in which all duplicated elements have been
dropped.
If the listi are considered as sets, Union gives their union. Union[list , list , . . . ] can be input in StandardForm
and InputForm as list list . . . . The character can be entered as , un , or \[Union]. The listi must have the
same head, but it need not be List. Union[list , . . . , SameTest->test] applies test to each pair of elements in the
listi to determine whether they should be considered the same. See page 127. See also: Join, Intersection,
Complement, Split. New in Version 1; modified in Version 3.
Unique Unset
1316
Unique
Unique[ ] generates a new symbol, whose name is of the form $nnn.
Unique[x] generates a new symbol, with a name of the form x$nnn.
Unique[{x, y, ... }] generates a list of new symbols.
Unique["xxx"] generates a new symbol, with a name of the form xxxnnn.
Unique[x] numbers the symbols it creates using $ModuleNumber, and increments $ModuleNumber every time it is
called. Unique["xxx"] numbers the symbols it creates sequentially, starting at 1 for each string xxx.
Unique[name, {attr , attr , . . . }] generates a symbol which has the attributes attri . See page 382. See also:
Symbol, ToExpression, Names, GeneratedParameters , Module, CharacterRange. New in Version 1.
UnitStep
UnitStep[x] represents the unit step function, equal to 0 for x ) and 1 for x ! .
UnitStep[x , x , ... ] represents the multidimensional unit step function which is 1 only if
none of the xi are negative.
Some transformations are done automatically when UnitStep appears in a product of terms. UnitStep provides a
convenient way to represent piecewise continuous functions. UnitStep has attribute Orderless. For exact
numeric quantities, UnitStep internally uses numerical approximations to establish its result. This process can be
affected by the setting of the global variable $MaxExtraPrecision . See page 879. See also: Sign, Positive,
DiracDelta, DiscreteDelta , KroneckerDelta . New in Version 4.
Unprotect
Unprotect[s , s , ... ] removes the attribute Protected for the symbols si .
Unprotect["form ", "form ", ... ] unprotects all symbols whose names textually match any
of the formi .
A typical sequence in adding your own rules for built-in functions is Unprotect[f]; definition; Protect[f].
notes for Protect. See pages 321 and 1044. See also: Protect, Locked, SetOptions. New in Version 1.
See
UnsameQ
lhs =!= rhs yields True if the expression lhs is not identical to rhs, and yields False otherwise.
See notes for SameQ. e =!= e =!= e
gives True if no two of the ei are identical.
Equal, Order. New in Version 2.
See also:
Unset
lhs =. removes any rules defined for lhs.
Rules are removed only when their left-hand sides are identical to lhs, and the tests in Condition given on the
right-hand side are also identical. See pages 304 and 1052. See also: Clear, TagUnset. New in Version 1.
Update ValueQ
1317
Update
Update[symbol] tells Mathematica that hidden changes have been made which could affect
values associated with a symbol.
Update[ ] specifies that the value of any symbol could be affected.
Update manipulates internal optimization features of Mathematica. It should not need to be called except under
special circumstances that rarely occur in practice. One special circumstance is that changes in the value of one
symbol can affect the value of another symbol by changing the outcome of Condition tests. In such cases, you
may need to use Update on the symbol you think may be affected. Using Update will never give you incorrect
results, although it will slow down the operation of the system. See page 370. New in Version 1.
UpperCaseQ
UpperCaseQ[string] yields True if all the characters in the string are upper-case letters, and
yields False otherwise.
UpperCaseQ treats both ordinary and special characters. See page 413. See also: LowerCaseQ, LetterQ,
ToUpperCase, ToCharacterCode . New in Version 2; modified in Version 3.
UpSet
lhs^=rhs assigns rhs to be the value of lhs, and associates the assignment with symbols that
occur at level one in lhs.
f [g[x]]=value makes an assignment associated with f. f [g[x]]^=value makes an assignment associated instead with
g. UpSet associates an assignment with all the distinct symbols that occur either directly as arguments of lhs, or
as the heads of arguments of lhs. See pages 318 and 1051. See also: TagSet, UpValues. New in Version 1.
UpSetDelayed
lhs^:=rhs assigns rhs to be the delayed value of lhs, and associates the assignment with
symbols that occur at level one in lhs.
See notes for UpSet and SetDelayed.
New in Version 1.
UpValues
UpValues[f] gives a list of transformation rules corresponding to all upvalues defined for the
symbol f.
You can specify the upvalues for f by making an assignment of the form UpValues[f] = list. The list returned by
UpValues has elements of the form HoldPattern[lhs] :> rhs. See page 322. See also: Set, DownValues,
HoldAllComplete. New in Version 2; modified in Version 3.
ValueQ
ValueQ[expr] gives True if a value has been defined for expr, and gives False otherwise.
ValueQ has attribute HoldFirst. ValueQ gives False only if expr would not change if it were to be entered as
Mathematica input. See page 268. See also: Information. New in Version 1.
Variables ViewPoint
1318
Variables
Variables[poly] gives a list of all independent variables in a polynomial.
See page 799.
,
New in Version 1.
Variance
Variance[list] gives the statistical variance of the elements in list.
Variance[list] gives the unbiased estimate of variance. Variance[list] is equivalent to
Total[(list-Mean[list])^2]/(Length[list]-1) . Variance handles both numerical and symbolic data.
Variance[{{x , y , . . . }, {x , y , . . . }, . . . }] gives {Variance[{x , x , . . . }], Variance[{y , y , . . . }]}.
Variance works with SparseArray objects. See pages 794 and 924. See also: StandardDeviation , Mean,
Quantile. Related packages: Statistics`DescriptiveStatistics` , Statistics`MultiDescriptiveStatistics` .
New in Version 5.0.
VectorQ
VectorQ[expr] gives True if expr is a list or a one-dimensional SparseArray object, 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.
VectorQ[expr, NumberQ] tests whether expr is a vector of numbers.
ArrayDepth. New in Version 1; modified in Version 2.
Verbatim
Verbatim[expr] represents expr in pattern matching, requiring that expr be matched exactly as
it appears, with no substitutions for blanks or other transformations.
Verbatim[x_] will match only the actual expression x_. Verbatim is useful in setting up rules for transforming
other transformation rules. Verbatim[expr] does not maintain expr in an unevaluated form. See page 278. See
also: HoldPattern. New in Version 3.
ViewCenter
ViewCenter is an option for Graphics3D and SurfaceGraphics which gives the scaled
coordinates of the point which appears at the center of the display area in the final plot.
With the default setting ViewCenter -> Automatic, the whole bounding box is centered in the final image area.
With the setting ViewCenter -> {1/2, 1/2, 1/2}, the center of the three-dimensional bounding box will be
placed at the center of the final display area. The setting for ViewCenter is given in scaled coordinates, which
run from 0 to 1 across each dimension of the bounding box. With SphericalRegion -> True, the circumscribing
sphere is always centered, regardless of the setting for ViewCenter. See page 533. New in Version 2.
ViewPoint
ViewPoint is an option for Graphics3D and SurfaceGraphics which gives the point in space
from which the objects plotted are to be viewed.
ViewPoint -> {x, y, z} gives the position of the view point relative to the center of the three-dimensional box
that contains the object being plotted. The view point is given in a special scaled coordinate system in which the
longest side of the bounding box has length 1. The center of the bounding box is taken to have coordinates
{0, 0, 0}.
(continued)
ViewPoint
1319
(continued)
{1.3, -2.4, 2}
{0, -2, 0}
{0, -2, 2}
{0, -2, -2}
{-2, -2, 0}
{2, -2, 0}
{0, 0, 2}
default setting
directly in front
in front and up
in front and down
left-hand corner
right-hand corner
directly above
Choosing ViewPoint further away from the object reduces the distortion associated with perspective. The view
point must lie outside the bounding box. The coordinates of the corners of the bounding box in the special
coordinate system used for ViewPoint are determined by the setting for the BoxRatios option. See page 532.
See also: ViewCenter, ViewVertical, SphericalRegion . Related package: Geometry`Rotations` . New in
Version 1.
ViewVertical
ViewVertical is an option for Graphics3D and SurfaceGraphics which specifies what
direction in scaled coordinates should be vertical in the final image.
The default setting is ViewVertical -> {0, 0, 1}, which specifies that the z axis in your original coordinate
system should end up vertical in the final image. The setting for ViewVertical is given in scaled coordinates,
which run from 0 to 1 across each dimension of the bounding box. Only the direction of the vector specified by
ViewVertical is important; its magnitude is irrelevant. See page 533. New in Version 2.
Visible
Visible is an option for Notebook which specifies whether the notebook should be explicitly
displayed on the screen.
With Visible->False a notebook can still be manipulated from the kernel, but will not explicitly be displayed on
the screen. NotebookCreate[Visible->False] creates a new invisible window. See page 620. See also:
Selectable, WindowFloating, CellOpen. New in Version 3.
WeierstrassHalfPeriods
WeierstrassHalfPeriods[{g , g
}] gives the half-periods $ for Weierstrass elliptic
functions corresponding to the invariants {g , g
}.
Mathematical function (see Section A.3.10). The half-periods $ define the fundamental period parallelogram
for the Weierstrass elliptic functions. WeierstrassHalfPeriods is the inverse of WeierstrassInvariants . See
page 782. See also: WeierstrassP , InverseWeierstrassP , ModularLambda. New in Version 3.
WeierstrassInvariants
WeierstrassInvariants[{, $ }] gives the invariants {g , g
} for Weierstrass elliptic
functions corresponding to the half-periods {, $ }.
Mathematical function (see Section A.3.10). WeierstrassInvariants is the inverse of WeierstrassHalfPeriods .
See page 782. See also: WeierstrassP, InverseWeierstrassP , KleinInvariantJ . New in Version 3.
WeierstrassP While
1320
WeierstrassP
WeierstrassP[u, {g , g
}] gives the Weierstrass elliptic function jug g g
.
x
Mathematical function (see Section A.3.10). jug g g
gives the value of x for which u
t
g t g
dt.
See page 782 for a discussion of argument conventions for elliptic functions. See pages 785 and 787. See also:
InverseWeierstrassP . New in Version 1; modified in Version 3.
WeierstrassPPrime
WeierstrassPPrime[u, {g , g
}] gives the derivative of the Weierstrass elliptic function
jug g g
.
Mathematical function (see Section A.3.10).
argument conventions for elliptic functions.
WeierstrassSigma
WeierstrassSigma[u, {g , g
}] gives the Weierstrass sigma function ug g g
.
Mathematical function (see Section A.3.10). Related to WeierstrassZeta by the differential equation
$ zg g g
zg g g
zg g g
. WeierstrassSigma is not periodic and is therefore not strictly an elliptic
function. See page 782 for a discussion of argument conventions for elliptic and related functions. See page 785.
See also: WeierstrassZeta . New in Version 3.
WeierstrassZeta
WeierstrassZeta[u, {g , g
}] gives the Weierstrass zeta function ug g g
.
Mathematical function (see Section A.3.10). Related to WeierstrassP by the differential equation
$ zg g g
jzg g g
. WeierstrassZeta is not periodic and is therefore not strictly an elliptic function. See
page 782 for a discussion of argument conventions for elliptic and related functions. See page 785. See also:
WeierstrassSigma . New in Version 3.
Which
Which[test , value , test , value , ... ] evaluates each of the testi in turn, returning the value
of the valuei corresponding to the first one that yields True.
Example: Which[1==2, x, 1==1, y] # y . Which has attribute HoldAll. If any of the testi evaluated by Which
give neither True nor False, then a Which object containing these remaining elements is returned unevaluated.
You can make Which return a default value by taking the last testi to be True. If all the testi evaluate to
False, Which returns Null. See page 345. See also: Switch, If. New in Version 1.
While
While[test, body] evaluates test, then body, repetitively, until test first fails to give True.
While[test] does the loop with a null body. If Break[ ] is generated in the evaluation of body, the While loop
exits. Continue[ ] exits the evaluation of body, and continues the loop. Unless Return[ ] or Throw[ ] are
generated, the final value returned by While is Null. Example: i=0; While[i < 0, tot += f[i]; i++]. Note that
the roles of ; and , are reversed relative to the C programming language. See page 352. See also: Do, For,
NestWhile, Nest, Fold, Select, Throw. New in Version 1.
WindowClickSelect WindowFrame
1321
WindowClickSelect
WindowClickSelect is an option for Notebook which specifies whether the window for the
notebook should become selected if you click on it.
With WindowClickSelect->True , clicking on the window corresponding to a notebook makes that notebook the
currently selected one. WindowClickSelect affects selection of a window as a whole; Selectable affects only
selection of the contents of a window. See page 620. See also: WindowFloating , SetSelectedNotebook . New in
Version 3.
WindowElements
WindowElements is an option for Notebook which specifies the elements to include in the
window used to display the notebook on the screen.
WindowElements is typically set to a list containing elements such as "HorizontalScrollBar" ,
"MagnificationPopUp" , "StatusArea" and "VerticalScrollBar" . The details of particular elements may differ
from one computer system to another. See page 620. See also: WindowToolbars, WindowTitle, WindowFrame.
New in Version 3.
WindowFloating
WindowFloating is an option for Notebook which specifies whether the window for the
notebook should float on top of other windows when it is displayed on the screen.
WindowFloating->True is often used for palettes. If there are several floating windows the most recently selected
one goes on top. See page 620. See also: WindowClickSelect , Visible. New in Version 3.
WindowFrame
WindowFrame is an option for Notebook which specifies the type of frame to draw around the
window in which the notebook is displayed on the screen.
Typical possible settings are:
"Frameless"
"Generic"
"ModalDialog"
"ModelessDialog"
"MovableModalDialog"
"Normal"
"Palette"
"ThinFrame"
The details of how particular types of frames are rendered may differ from one computer system to another.
Settings for WindowFrame affect only the appearance of a window, and not any of its other characteristics. See
page 620. See also: WindowTitle, WindowElements, WindowToolbars. New in Version 3.
WindowMargins WindowTitle
1322
WindowMargins
WindowMargins is an option for Notebook which specifies what margins to leave around the
window that is used to display the notebook on the screen.
WindowMargins->{{left, right}, {bottom, top}} specifies the distances from each edge of your screen to each edge
of the window. Typically only two distances are given explicitly; the others are Automatic, indicating that they
should be determined from the size of the window. Explicit distances are given in printers points. Negative
values represent edges that are off the screen. The settings for WindowMargins change whenever you move a
window around interactively using the front end. Window edges closer to the edges of the screen are typically
assigned explicit margin distances; the others are set to Automatic. This allows the same setting for WindowMargins
to work on screens of different sizes. With WindowSize->{Automatic, Automatic} all four margin distances must
be given explicitly. With the default setting WindowMargins->Automatic , new windows are placed on your screen
in such a way as to make as many window title bars as possible visible. See page 620. See also: WindowSize,
WindowMovable. New in Version 3.
WindowMovable
WindowMovable is an option for Notebook which specifies whether to allow the window for
the notebook to be moved around interactively on the screen.
WindowMovable affects only interactive operations in the front end. Even with WindowMovable->False , the
WindowMargins option can still be reset from the kernel or option inspector menu. See page 620. See also:
WindowMargins, Selectable. New in Version 3.
WindowSize
WindowSize is an option for Notebook which specifies the size of window that should be used
to display a notebook on the screen.
WindowSize->{w, h} gives the width and height of the window in printers points. Setting either width or height
to Automatic causes the size of the window to be determined from the setting for WindowMargins and the size of
your screen. The setting for WindowSize changes whenever you resize a window interactively in the front end.
On most computer systems, the front end does not allow window sizes below a certain minimum value. See
page 620. See also: WindowMargins. New in Version 3.
WindowTitle
WindowTitle is an option for Notebook which specifies the title to give for the window used
to display the notebook.
WindowTitle->Automatic makes the title be the name of the file in which the notebook is stored.
WindowTitle->None displays no title. The title given for the window need have no connection with the name
of the file in which the window is stored. Not all settings for WindowFrame leave room for a title to be displayed.
See page 620. See also: WindowElements . New in Version 3.
WindowToolbars WordSeparators
1323
WindowToolbars
WindowToolbars is an option for Notebook which specifies the toolbars to include at the top of
the window used to display the notebook on the screen.
WindowToolbars gives a list of toolbars to include. Typical possible elements are:
"RulerBar"
"EditBar"
"LinksBar"
The detailed appearance and operation of toolbars differ from one computer system to another. Toolbars are
always shown inside the main frame of the window. See page 620. See also: WindowElements, WindowFrame.
New in Version 3.
With
With[{x = x , y = y , ... }, expr] specifies that in expr occurrences of the symbols x, y, ...
should be replaced by x , y , ... .
With allows you to define local constants. With replaces symbols in expr only when they do not occur as local
variables inside scoping constructs. You can use With[{vars}, body /; cond] as the right-hand side of a
transformation rule with a condition attached. With has attribute HoldAll. With is a scoping construct (see
Section A.3.8). With constructs can be nested in any way. With implements read-only lexical variables. See
page 380. See also: Module, Block, ReplaceAll. New in Version 2.
Word
Word represents a word in Read, Find and related functions.
Words are defined to be sequences of characters that lie between separators. The separators are strings given as the
settings for WordSeparators and RecordSeparators . The default is for words to be delimited by white space
consisting of spaces, tabs and newlines. See page 646. See also: Record. New in Version 2.
WordSearch
WordSearch is an option for Find and FindList which specifies whether the text searched for
must appear as a word.
With the setting WordSearch -> True, the text must appear as a word, delimited by word or record separators, as
specified by WordSeparators or RecordSeparators . See page 651. See also: AnchoredSearch. New in
Version 2.
WordSeparators
WordSeparators is an option for Read, Find and related functions which specifies the list of
strings to be taken as delimiters for words.
The default setting is WordSeparators -> {" ", "\t"}. Strings used as word separators may contain several
characters. With the option setting NullWords -> False, any number of word separators may appear between
any two successive words. WordSeparators -> {{lsep , . . . }, {rsep , . . . }} specifies different left and right
separators for words. Words must have a left separator at the beginning, and a right separator at the end, and
cannot contain any separators. Strings given as record separators are automatically taken as word separators.
See page 646. See also: RecordSeparators , TokenWords. New in Version 2.
WorkingPrecision Zeta
1324
WorkingPrecision
WorkingPrecision is an option for various numerical operations which specifies how many
digits of precision should be maintained in internal computations.
WorkingPrecision is an option for such functions as NIntegrate and FindRoot. Setting WorkingPrecision->n
causes all internal computations to be done to at most n-digit precision. , Setting
WorkingPrecision->MachinePrecision causes all internal computations to be done with machine numbers. Even
if internal computations are done to n-digit precision, the final results you get may have much lower precision.
See page 956. See also: AccuracyGoal , Precision, Accuracy, N. New in Version 1; modified in Version 5.0.
Write
Write[channel, expr , expr , ... ] writes the expressions expri in sequence, followed by a
newline, to the specified output channel.
The output channel can be a single file or pipe, or list of them, each specified by a string giving their name, or by
an OutputStream object. Write is the basic Mathematica output function. Print and Message are defined in terms
of it. If any of the specified files or pipes are not already open, Write calls OpenWrite to open them. Write
does not close files and pipes after it finishes writing to them. By default, Write generates output in the form
specified by the setting of the FormatType option for the output stream used. See page 632. See also: Print,
Export, Display, Message, Read, LinkWrite. New in Version 1.
-
WriteString
WriteString[channel, expr , expr , ... ] converts the expri to strings, and then writes them in
sequence to the specified output channel.
WriteString uses the OutputForm of the expri . - WriteString allows you to create files which are effectively just
streams of bytes. The files need to be opened with the options CharacterEncoding -> {} and
DOSTextFormat -> False. WriteString does not put a newline at the end of the output it generates. See notes
for Write. See page 632. New in Version 1; modified in Version 5.0.
Xor
Xor[e , e , ... ] is the logical XOR (exclusive OR) function.
It gives True if an odd number of the ei are True, and the rest are False. It gives False if an
even number of the ei are True, and the rest are False.
Xor[e , e , . . . ] can be input in StandardForm and InputForm as e e . . . . The character can be entered
as , xor , or \[Xor]. Xor gives symbolic results when necessary, applying various simplification rules to them.
Unlike And and Nand, Or and Nor, Xor must always test all its arguments, and so is not a control structure, and
does not have attribute HoldAll. See page 87. See also: LogicalExpand , Mod. New in Version 1; modified in
Version 4.1.
,
Zeta
Zeta[s] gives the Riemann zeta function s.
Zeta[s, a] gives the generalized Riemann zeta function s a.
s
s
Mathematical function (see Section A.3.10). s
s a
k k .
k k a , where any term with k a
is excluded. Zeta[s] has no branch cut discontinuities. FullSimplify and FunctionExpand include
transformation rules for Zeta. See page 772. Implementation notes: see page 1068. See also: PolyLog,
HarmonicNumber , LerchPhi, RiemannSiegelZ, StieltjesGamma, Glaisher, PrimePi. Related package:
NumberTheory`Ramanujan` . New in Version 1.
ZTransform $BaseDirectory
1325
ZTransform
ZTransform[expr, n, z] gives the Z transform of expr.
n
The Z transform of a function fn is defined to be
n fnz .
LaplaceTransform, Sum, Series, RSolve. New in Version 4.
$Aborted
$Aborted is a special symbol that is returned as the result from a calculation that has been
aborted.
See page 371.
,
New in Version 2.
$Assumptions
$Assumptions is the default setting for the Assumptions option used in such functions as
Simplify, Refine and Integrate .
The value of $Assumptions can be modified using Assuming.
page 818. See also: Assuming, Block. New in Version 5.0.
See
$BaseDirectory
$BaseDirectory gives the base directory in which system-wide files to be loaded by
Mathematica are conventionally placed.
$BaseDirectory returns the full name of the directory as a string.
C:\DocumentsandSettings\AllUsers\ApplicationData\Mathematica
/Library/Mathematica
/usr/share/Mathematica
Windows
Macintosh
Unix
The value of $UserBaseDirectory can be specified by setting the MATHEMATICA_USERBASE operating system
environment variable when the Mathematica kernel is launched. It cannot be reset from inside the kernel. Typical
subdirectories of $BaseDirectory are:
Applications
Autoload
FrontEnd
Kernel
Licensing
SystemFiles
These subdirectories are, if possible, created automatically the first time Mathematica is run. Appropriate
subdirectories are automatically included on $Path. The subdirectories of $BaseDirectory are given in $Path
after the corresponding ones of $UserBaseDirectory . See pages 637 and 1064. See also: $UserBaseDirectory ,
$InstallationDirectory , $InitialDirectory , $HomeDirectory . New in Version 5.0.
$BatchInput $CharacterEncoding
1326
$BatchInput
$BatchInput is True if input in the current session is being fed directly to the Mathematica
kernel in batch mode.
$BatchInput is True if input is being taken from a file. $BatchInput can be reset during a Mathematica session.
When $BatchInput is True, Mathematica terminates if it ever receives an interrupt, does not discard input when
blank lines are given, and terminates when it receives end-of-file. See page 715. See also: $IgnoreEOF,
$BatchOutput, $Linked, $Notebooks. New in Version 2.
$BatchOutput
$BatchOutput is True if output in the current session is being sent in batch mode, suitable for
reading by other programs.
The initial value of $BatchOutput is typically determined by a command-line option when the Mathematica session
is started. $BatchOutput cannot be reset during a Mathematica session. When $BatchOutput is set to True,
Mathematica generates all output in InputForm, with the PageWidth option effectively set to Infinity, does not
give In and Out labels, and does not give any banner when it starts up. See page 715. See also: $BatchInput,
$Linked, $CommandLine. New in Version 2.
$ByteOrdering
$ByteOrdering gives the native ordering of bytes in binary data on your computer system.
Possible values of $ByteOrdering are +1 and -1. +1 corresponds to big endian (appropriate for 680x0 and many
other processors); -1 corresponds to little endian (appropriate for x86 processors). +1 corresponds to having the
most significant byte first; -1 to having the least significant byte first. +1 is the order obtained from
IntegerDigits[n, 256]. $ByteOrdering gives the default setting for the ByteOrdering option in Import and
Export. See page 717. See also: $ProcessorType. New in Version 4.
$CharacterEncoding
$CharacterEncoding specifies the default raw character encoding to use for input and output
functions.
The default setting for $CharacterEncoding is $SystemCharacterEncoding . The setting
$CharacterEncoding = None takes all special characters to be represented externally by printable ASCII sequences
such as \[Name] and \:xxxx. - Examples of other possible settings include:
"AdobeStandard"
"ASCII"
"EUC"
"ISOLatin1"
"ISOLatin2"
"ISOLatin3"
"ISOLatin4"
"ISOLatinCyrillic"
"MacintoshRoman"
"PrintableASCII"
"ShiftJIS"
(continued)
$CharacterEncoding
"Symbol"
"Unicode"
"UTF8"
"WindowsANSI"
"ZapfDingbats"
1327
(continued)
With $CharacterEncoding = "encoding" characters that are included in the encoding can be input in their raw 8or 16-bit form, and will be output in this form. Unencoded characters can be input and will be output in
standard \[Name] or \:xxxx form. When using a text-based interface, resetting the value of $CharacterEncoding
has an immediate effect on standard input and output in a Mathematica session. When using the notebook front
end, raw character encodings are normally handled automatically based on the fonts you use. Only raw 16-bit
Unicode is ever sent through the MathLink connection to the kernel. $CharacterEncoding can be set to a list of
the form {class, {{n , "c "}, {n , "c "}, . . . }}. The class defines the general form of encoding; the ni give
character codes for specific characters ci . Possible settings for class include:
"7Bit"
"8Bit"
"16Bit"
"ShiftJIS"
$CharacterEncoding affects the input and output of all characters, including those in symbol names and
comments. $CharacterEncoding also affects characters that appear in Text graphics primitives. See page 420.
See also: CharacterEncoding , FromCharacterCode , ToCharacterCode, $SystemCharacterEncoding ,
$ByteOrdering. New in Version 3.
$CommandLine
$CommandLine is a list of strings giving the elements of the original operating system
command line with which Mathematica was invoked.
See page 716.
in Version 1.
New
$Context
$Context is a global variable that gives the current context.
Contexts are specified by strings of the form "name`". $Context is modified by Begin, BeginPackage, End and
EndPackage. $Context is a rough analog for Mathematica symbols of the current working directory for files in
many operating systems. See page 393. See also: Context, $ContextPath. New in Version 1.
$ContextPath
$ContextPath is a global variable that gives a list of contexts, after $Context , to search in
trying to find a symbol that has been entered.
Each context is specified by a string of the form "name`". The elements of $ContextPath are tested in order to
try and find a context containing a particular symbol. $ContextPath is modified by Begin, BeginPackage, End
and EndPackage. $ContextPath is a rough analog for Mathematica symbols of the search path for files in many
operating systems. See page 394. New in Version 1.
$CreationDate $ExportFormats
1328
$CreationDate
$CreationDate gives the date and time at which the particular release of the Mathematica
kernel you are running was created.
$CreationDate is in the form {year, month, day, hour, minute, second} returned by Date. See page 717.
also: $VersionNumber, $ReleaseNumber , FileDate, $InstallationDate . New in Version 2.
See
$CurrentLink
$CurrentLink is the LinkObject representing the MathLink connection for an external
program currently being installed or being called.
$CurrentLink is temporarily set by Install and by ExternalCall. You can use $CurrentLink to distinguish
between several instances of an external program running at the same time. $CurrentLink can be included in
:Pattern: and :Arguments: MathLink template specifications, and will be evaluated at the time when Install is
called. See page 688. See also: $ParentLink, Links, $Input. New in Version 3.
$Display
$Display gives a list of files and pipes to be used with the default $DisplayFunction .
The initial setting of $Display is {}.
New in Version 1.
$DisplayFunction
$DisplayFunction gives the default setting for the option DisplayFunction in graphics
functions.
The initial setting of $DisplayFunction is Display[$Display, #]&. $DisplayFunction is typically set to a
procedure which performs the following: (1) open an output channel; (2) send a PostScript prolog to the output
channel; (3) use Display to send PostScript graphics; (4) send PostScript epilog; (5) close the output channel and
execute the external commands needed to produce actual display. See page 491. See also: Display, Put, Run,
$SoundDisplayFunction . New in Version 1.
$Echo
$Echo gives a list of files and pipes to which all input is echoed.
You can use $Echo to keep a file of all your input commands.
New in Version 1.
$Epilog
$Epilog is a symbol whose value, if any, is evaluated when a dialog or a Mathematica session
is terminated.
For Mathematica sessions, $Epilog is conventionally defined to read in a file named end.m.
also: Exit, Quit, Dialog. New in Version 1.
See
$ExportFormats
$ExportFormats gives a list of export formats currently supported in your Mathematica
system.
The strings that appear in $ExportFormats are the possible third arguments to Export.
$ImportFormats , Export, $Packages. New in Version 4.
See also:
$Failed $ImportFormats
1329
$Failed
$Failed is a special symbol returned by certain functions when they cannot do what they
were asked to do.
Get returns $Failed when it cannot find the file or other object that was specified.
Version 2.
New in
$FormatType
$FormatType gives the default format type to use for text that appears in graphics.
The default setting for the standard notebook front end is $FormatType = StandardForm. The default setting for
the text-based front end is $FormatType = OutputForm. A common alternative setting is TraditionalForm.
Box-based format types such as StandardForm and TraditionalForm can be used only when a notebook front
end is present. $FormatType gives the default value for the FormatType option in graphics. See page 556. See
also: $TextStyle, FormatType. New in Version 3.
$FrontEnd
$FrontEnd is a global variable that specifies to what front end object, if any, the kernel is
currently connected.
$FrontEnd is either a FrontEndObject, or Null. You can use Options and SetOptions on $FrontEnd to read
and set global options for the front end. See page 592. See also: $Notebooks. New in Version 3.
$HistoryLength
$HistoryLength specifies the number of previous lines of input and output to keep in a
Mathematica session.
The default setting for $HistoryLength is Infinity. Values of In[n] and Out[n] corresponding to lines before
those kept are explicitly cleared. Using smaller values of $HistoryLength can save substantial amounts of
memory in a Mathematica session. See page 703. See also: $Line. New in Version 3.
$HomeDirectory
$HomeDirectory gives your home directory.
$HomeDirectory returns the full name of the directory as a string. On multi-user operating systems,
$HomeDirectory gives the main directory for the current user. See page 637. See also: Directory,
ParentDirectory, $UserName, $UserBaseDirectory , $InstallationDirectory . New in Version 3.
$IgnoreEOF
$IgnoreEOF specifies whether Mathematica should terminate when it receives an end-of-file
character as input.
$IgnoreEOF defaults to False. $IgnoreEOF is assumed to be False if the input to Mathematica comes from a file,
rather than an interactive device. See pages 706 and 1057. See also: Exit, Quit, $BatchInput. New in
Version 1.
$ImportFormats
$ImportFormats gives a list of import formats currently supported in your Mathematica
system.
The strings that appear in $ImportFormats are the possible second arguments to Import.
also: $ExportFormats, Import, $Packages. New in Version 4.
See
$InitialDirectory $IterationLimit
1330
$InitialDirectory
$InitialDirectory gives the initial directory when the current Mathematica session was
started.
$InitialDirectory returns the full name of the directory as a string. , If Mathematica is started from a shell or
command line, $InitialDirectory gives the current operating system directory. , If Mathematica is started from a
menu or icon, $InitialDirectory typically gives the users home directory $HomeDirectory . See page 637. See
also: Directory, $CommandLine, $HomeDirectory , $BaseDirectory , $InstallationDirectory . New in Version 3;
modified in Version 5.0.
$Input
$Input is a global variable whose value is the name of the stream from which input to
Mathematica is currently being sought.
During the execution of <<file, $Input is set to "file". During interactive input, $Input is "". See pages 639
and 705. See also: Get, Streams, DirectoryName , ToFileName, $BatchInput, $ParentLink. New in Version 2.
$Inspector
$Inspector is a global variable which gives a function to apply when the inspector is invoked
from an interrupt menu.
The argument supplied is the number of nested invocations of the inspector that are in use.
$Inspector is Dialog[ ]&. See also: Interrupt. New in Version 2.
$InstallationDate
$InstallationDate gives the date and time at which the copy of the Mathematica kernel you
are running was installed.
$InstallationDate is in the form {year, month, day, hour, minute, second} returned by Date.
See also: $CreationDate, $InstallationDirectory . New in Version 3.
,
$InstallationDirectory
$InstallationDirectory gives the top-level directory in which your Mathematica installation
resides.
$InstallationDirectory returns the full name of the directory as a string.
C:\ProgramFiles\WolframResearch\Mathematica\5.0
/Applications/Mathematica5.0.app
/usr/local/mathematica
See page 637.
Version 5.0.
Windows
Macintosh
Unix
New in
$IterationLimit
$IterationLimit gives the maximum length of evaluation chain used in trying to evaluate
any expression.
$IterationLimit limits the number of times Mathematica tries to re-evaluate a particular expression.
$IterationLimit gives an upper limit on the length of any list that can be generated by Trace. See page 369.
See also: $RecursionLimit . New in Version 2.
$Language $MachineName
1331
$Language
$Language is a list of strings which give the names of languages to use for messages.
All language names are conventionally given in English, and are capitalized, as in "French". When a message
with a name s::tag is requested either internally or through the Message function, Mathematica searches for
messages with names s::tag::langi corresponding to the entries "langi " in the list $Language. Only if it fails to
find any of these messages will it use the message with the actual name s::tag. See pages 483 and 706. See
also: MessageName, LanguageCategory . New in Version 2.
$Line
$Line is a global variable that specifies the number of the current input line.
You can reset $Line.
New in Version 1.
$Linked
$Linked is True if the Mathematica kernel is being run through MathLink.
$Linked is True when Mathematica is being run with a front end. $Linked is typically False when Mathematica is
being run with a text-based interface. See also: $CommandLine, $BatchInput, $BatchOutput, $Notebooks. New
in Version 2.
$MachineDomain
$MachineDomain is a string which gives the name of the network domain for the computer on
which Mathematica is being run, if such a name is defined.
$MachineDomain is "" if no name is defined.
Version 3.
New in
$MachineEpsilon
$MachineEpsilon gives the smallest machine-precision number which can be added to 1.0 to
give a result that is distinguishable from 1.0.
$MachineEpsilon is typically n , where n is the number of binary bits used in the internal representation of
machine-precision floating-point numbers. $MachineEpsilon measures the granularity of machine-precision
numbers. See page 739. See also: $MachinePrecision , $MinMachineNumber , $MaxMachineNumber . Related
package: NumericalMath`ComputerArithmetic` . New in Version 2.
$MachineID
$MachineID is a string which gives, if possible, a unique identification code for the computer
on which Mathematica is being run.
On many computers, $MachineID is the MathID string printed by the external program mathinfo.
See also: $SystemID, $MachineName. New in Version 2.
$MachineName
$MachineName is a string which gives the assigned name of the computer on which
Mathematica is being run, if such a name is defined.
For many classes of computers, $MachineName is the network host name. $MachineName is "" if no name is
defined. See page 718. See also: $MachineDomain, $System, $MachineID. New in Version 2.
$MachinePrecision $MaxPrecision
1332
$MachinePrecision
$MachinePrecision gives the number of decimal digits of precision used for
machine-precision numbers.
A typical value of $MachinePrecision is
log or approximately 16. , $MachinePrecision is the
numerical value of MachinePrecision . See pages 728 and 739. See also: MachinePrecision , $MachineEpsilon,
$MinMachineNumber , $MaxMachineNumber . Related package: NumericalMath`ComputerArithmetic` . New in
Version 2; modified in Version 5.0.
-
$MachineType
$MachineType is a string giving the general type of computer on which Mathematica is being
run.
$MachineType is intended to reflect general families of hardware rather than specific models. Typical values are
"PC", "Macintosh", "Sun", "DEC" and "SGI". Computers with the same $MachineType may not be binary
compatible. See page 717. See also: $ProcessorType , $OperatingSystem , $System. New in Version 2.
$MaxExtraPrecision
$MaxExtraPrecision gives the maximum number of extra digits of precision to be used in
functions such as N.
The default value of $MaxExtraPrecision is 50. You can use Block[{$MaxExtraPrecision = n}, expr] to reset
the value of $MaxExtraPrecision temporarily during the evaluation of expr. $MaxExtraPrecision is used
implicitly in various exact numerical computations, including equality tests, comparisons and functions such as
Round and Sign. See page 733. See also: $MaxPrecision. New in Version 3.
$MaxMachineNumber
$MaxMachineNumber is the largest machine-precision number that can be used on a particular
computer system.
Numbers larger than $MaxMachineNumber are always represented in arbitrary-precision form. $MaxMachineNumber
is typically n , where n is the maximum exponent that can be used in the internal representation of
machine-precision numbers. See page 739. See also: $MinMachineNumber , $MachineEpsilon ,
$MachinePrecision . Related package: NumericalMath`ComputerArithmetic` . New in Version 2.
$MaxNumber
$MaxNumber gives the magnitude of the maximum arbitrary-precision number that can be
represented on a particular computer system.
A typical value for $MaxNumber is around
.
$MaxMachineNumber . New in Version 3.
-
$MaxPrecision
$MaxPrecision gives the maximum number of digits of precision to be allowed in
arbitrary-precision numbers.
The default value of $MaxPrecision is Infinity. $MaxPrecision = Infinity uses the maximum value
possible on a particular computer system, given roughly by Log[10, $MaxNumber]. $MaxPrecision is measured
in decimal digits, and need not be an integer. See page 736. See also: $MinPrecision, $MaxExtraPrecision .
New in Version 3; modified in Version 5.0.
$MessageList $ModuleNumber
1333
$MessageList
$MessageList is a global variable that gives a list of the names of messages generated during
the evaluation of the current input line.
Whenever a message is output, its name, wrapped with HoldForm is appended to $MessageList. With the
standard Mathematica main loop, $MessageList is reset to {} when the processing of a particular input line is
complete. You can reset $MessageList during a computation. See page 481. See also: MessageList, Check.
New in Version 2.
$MessagePrePrint
$MessagePrePrint is a global variable whose value, if set, is applied to expressions before
they are included in the text of messages.
The default value of $MessagePrePrint is Short. $MessagePrePrint is applied after each expression is wrapped
with HoldForm. See pages 480 and 706. See also: $PrePrint. New in Version 2.
$Messages
$Messages gives the list of files and pipes to which message output is sent.
Output from Message is always given on the $Messages channel.
New in Version 1.
$MinMachineNumber
$MinMachineNumber is the smallest positive machine-precision number that can be used on a
particular computer system.
Accuracy[0.] yields Log[10, $MinMachineNumber] . See notes for $MaxMachineNumber . See page 739.
also: $MinNumber. Related package: NumericalMath`ComputerArithmetic` . New in Version 2.
See
$MinNumber
$MinNumber gives the magnitude of the minimum positive arbitrary-precision number that can
be represented on a particular computer system.
A typical value for $MinNumber is around
.
$MinMachineNumber . New in Version 3.
-
$MinPrecision
$MinPrecision gives the minimum number of digits of precision to be allowed in
arbitrary-precision numbers.
The default value of $MinPrecision is -Infinity. Positive values of $MinPrecision make Mathematica pad
arbitrary-precision numbers with zero digits to achieve the specified nominal precision. The zero digits are taken to
be in base 2, and may not correspond to zeros in base 10. $MaxPrecision = $MinPrecision = n makes
Mathematica do fixed-precision arithmetic. $MinPrecision is measured in decimal digits, and need not be an
integer. See page 736. See also: SetPrecision, $MinNumber. New in Version 3; modified in Version 5.0.
$ModuleNumber
$ModuleNumber gives the current serial number to be used for local variables that are created.
$ModuleNumber is incremented every time Module or Unique is called. Every Mathematica session starts with
$ModuleNumber set to 1. You can reset $ModuleNumber to any positive integer, but if you do so, you run the risk
of creating naming conflicts. See page 381. See also: $SessionID, Temporary. New in Version 2.
$NewMessage $Output
1334
$NewMessage
$NewMessage is a global variable which, if set, is applied to the symbol name and tag of
messages that are requested but have not yet been defined.
$NewMessage is applied to the symbol name, tag and language of a message if an explicit language is specified.
Mathematica looks for the value of name::tag or name::tag::lang after $NewMessage has been applied. You can
set up $NewMessage to read the text of messages from files when they are first needed. A typical value for
$NewMessage might be Function[ToExpression[FindList[files, ToString[MessageName[#1, #2]]]]]. See
page 482. See also: $NewSymbol. New in Version 2.
$NewSymbol
$NewSymbol is a global variable which, if set, is applied to the name and context of each new
symbol that Mathematica creates.
The name and context of the symbol are given as strings. $NewSymbol is applied before the symbol is actually
created. If the action of $NewSymbol causes the symbol to be created, perhaps in a different context, then the
symbol as created will be the one used. $NewSymbol is applied even if a symbol has already been created with a
Stub attribute by DeclarePackage . $NewSymbol is not applied to symbols automatically created by scoping
constructs such as Module. See page 405. See also: DeclarePackage, $NewMessage. New in Version 2.
$Notebooks
$Notebooks is True if Mathematica is being used with a notebook-based front end.
$Notebooks is automatically set by the front end when it starts the Mathematica kernel.
$FrontEnd, $Linked, $BatchInput. New in Version 2.
See also:
$NumberMarks
$NumberMarks gives the default value for the option NumberMarks , which specifies whether `
marks should be included in the input form representations of approximate numbers.
The default setting for $NumberMarks is Automatic. $NumberMarks = True indicates that ` should by default be
used in all approximate numbers, both machine-precision and arbitrary-precision ones.
$NumberMarks = Automatic indicates that ` should by default be used in arbitrary-precision but not
machine-precision numbers. $NumberMarks = False indicates that ` should by default never be used in
outputting numbers. See page 730. See also: NumberForm, SetPrecision . New in Version 3.
$OperatingSystem
$OperatingSystem is a string giving the type of operating system under which Mathematica is
being run.
Typical values for $OperatingSystem are "Windows98", "MacOS" and "Unix". You can use $OperatingSystem to
get an idea of what external commands will be available from within Mathematica. $OperatingSystem typically
has the same value for different versions or variants of a particular operating system. See page 717. See also:
$MachineType, $System, $ProcessorType . New in Version 2.
$Output
$Output gives the list of files and pipes to which standard output from Mathematica is sent.
Output from Print is always given on the $Output channel.
Version 1.
New in
$Packages $Pre
1335
$Packages
$Packages gives a list of the contexts corresponding to all packages which have been loaded
in your current Mathematica session.
$Packages is updated when BeginPackage is executed. $Packages is used by Needs to determine whether a
particular package needs to be loaded explicitly. See page 397. See also: Contexts, $ContextPath,
DeclarePackage, $ExportFormats. New in Version 2.
$ParentLink
$ParentLink is the MathLink LinkObject currently used for input and output by the
Mathematica kernel in a particular session.
When the Mathematica kernel is started by a Mathematica front end, $ParentLink gives the MathLink connection
between the front end and the kernel. You can reset $ParentLink in the middle of a Mathematica session to
connect the kernel to a different front end. See page 686. See also: $CurrentLink, Links, $Input. New in
Version 3.
$ParentProcessID
$ParentProcessID gives the ID assigned to the process which invokes the Mathematica kernel
by the operating system under which it is run.
On operating systems where no process ID is assigned, $ParentProcessID is None. See page 716.
$ParentLink, $ProcessID, $CommandLine, $UserName, Environment. New in Version 3.
See also:
$Path
$Path gives the default list of directories to search in attempting to find an external file.
The structure of directory and file names may differ from one computer system to another. $Path is used both
for files in Get and for external programs in Install. The setting for $Path can be overridden in specific
functions using the Path option. The directory names are specified by strings. The full file names tested are of
the form ToFileName[directory,name] . On most computer systems, the following special characters can be used in
directory names:
.
..
M
$Post
$Post is a global variable whose value, if set, is applied to every output expression.
See page 703.
New in Version 1.
$Pre
$Pre is a global variable whose value, if set, is applied to every input expression.
Unless $Pre is assigned to be a function which holds its arguments unevaluated, input expressions will be
evaluated before $Pre is applied, so the effect of $Pre will be the same as $Post. $Pre is applied to expressions,
while $PreRead is applied to strings which have not yet been parsed into expressions. See page 703. See also:
$Post. New in Version 1.
$PrePrint $RandomState
1336
$PrePrint
$PrePrint is a global variable whose value, if set, is applied to every expression before it is
printed.
$PrePrint is applied after Out[n] is assigned, but before the output result is printed.
$Post, $MessagePrePrint . New in Version 1.
See also:
$PreRead
$PreRead is a global variable whose value, if set, is applied to the text or box form of every
input expression before it is fed to Mathematica.
$PreRead is always applied to each complete input string that will be fed to Mathematica. In multiline input with
a text-based interface, $PreRead is typically applied to the input so far whenever each line is terminated.
$PreRead is applied to all strings returned by a $SyntaxHandler function. $PreRead is applied before
InString[n] is assigned. See page 703. See also: $Pre, StringReplace, ToExpression. New in Version 2.
$ProcessID
$ProcessID gives the ID assigned to the Mathematica kernel process by the operating system
under which it is run.
On operating systems where no process ID is assigned, $ProcessID is None. See page 716.
$ParentProcessID , $UserName, Environment, $SessionID. New in Version 3.
See also:
$ProcessorType
$ProcessorType is a string giving the architecture of processor on which Mathematica is being
run.
Typical values are "x86", "PowerPC", "SPARC", "MIPS", "PA-RISC" and "AXP". $ProcessorType specifies the basic
instruction set used by the CPU of your computer. Computers with the same $ProcessorType may not be binary
compatible. See page 717. See also: $MachineType, $OperatingSystem , $System. New in Version 3.
,
$ProductInformation
$ProductInformation is a list of rules giving detailed information about the software product
to which the current kernel belongs.
Typical elements of $ProductInformation are "ProductIDName" -> "Mathematica" and
"ProductVersion" -> version. See page 717. See also: $Version, $VersionNumber , $OperatingSystem , $System.
New in Version 4.2.
$RandomState
$RandomState gives a representation of the internal state of the pseudorandom generator used
by Random.
The value of $RandomState changes every time Random is called. You can use s = $RandomState to explicitly save
the value of $RandomState, and $RandomState = s to restore. The value of $RandomState is always a long
integer chosen from a certain large set of possibilities. You can assign $RandomState only to values in this set.
You can use Block[{$RandomState}, expr] to localize the value of $RandomState during the evaluation of expr.
See page 747. See also: SeedRandom. New in Version 3.
$RecursionLimit $SyntaxHandler
1337
$RecursionLimit
$RecursionLimit gives the current limit on the number of levels of recursion that Mathematica
can use.
$RecursionLimit=n sets the limit on the number of recursion levels that Mathematica can use to be n.
$RecursionLimit=Infinity removes any limit on the number of recursion levels. $RecursionLimit gives the
maximum length of the stack returned by Stack[ ]. Each time the evaluation of a function requires the nested
evaluation of the same or another function, one recursion level is used up. On most computers, each level of
recursion uses a certain amount of stack space. $RecursionLimit allows you to control the amount of stack space
that Mathematica can use from within Mathematica. On some computer systems, your whole Mathematica session may
crash if you allow it to use more stack space than the computer system allows. MemoryInUse and related functions
do not count stack space. See page 369. See also: $IterationLimit , MemoryConstrained . New in Version 1.
$ReleaseNumber
$ReleaseNumber is an integer which gives the current Mathematica kernel release number, and
increases in successive releases.
Each released revision of the Mathematica kernel for any particular computer system is assigned a new release
number. The same source code may yield releases with different numbers on different computer systems. See
page 717. See also: $VersionNumber . New in Version 2.
$SessionID
$SessionID is a number set up to be unique to a particular Mathematica session.
$SessionID should be different for different Mathematica sessions run either on the same computer or on different
computers. The value of $SessionID is based on $MachineID, as well as AbsoluteTime[ ] and operating system
parameters such as the Mathematica process ID. See pages 384 and 716. See also: $ModuleNumber, $ProcessID.
New in Version 2.
$SoundDisplayFunction
$SoundDisplayFunction gives the default setting for the option DisplayFunction in sound
functions.
The initial setting of $SoundDisplayFunction is Display[$SoundDisplay, #]&.
ListPlay, Show, $DisplayFunction. New in Version 2.
$SyntaxHandler
$SyntaxHandler is a global variable which, if set, is applied to any input string that is found
to contain a syntax error.
The arguments given to $SyntaxHandler are the complete input string and an integer specifying the character
position at which the syntax error was detected. The first character in the string is taken to have position 1.
Any string returned by $SyntaxHandler is used as a new version of the input string, and is fed to Mathematica.
If the string does not end with a newline, Mathematica waits for input to complete the line. If $SyntaxHandler
returns $Failed, input to Mathematica is abandoned if possible. Input is not assigned to InString[n] until after
$SyntaxHandler is applied. $SyntaxHandler is not called for input from files obtained using Get. See
page 703. See also: SyntaxLength , SyntaxQ. New in Version 2.
$System $Urgent
1338
$System
$System is a string describing the type of computer system on which Mathematica is being run.
$System typically consists of words separated by spaces. Typical values are "Microsoft Windows",
"Power Macintosh", "Linux" and "Solaris". $SystemID provides a more succinct version of the same
information. See page 717. See also: $SystemID, $Version, $MachineType, $ProcessorType, $OperatingSystem .
New in Version 1.
$SystemCharacterEncoding
$SystemCharacterEncoding gives the default raw character encoding for the computer system
on which Mathematica is being run.
$SystemCharacterEncoding is used to determine the default value of $CharacterEncoding . The notebook front
end handles raw character encodings independent of the kernel. The possible settings for
$SystemCharacterEncoding are the same as for $CharacterEncoding . See page 420. See also:
CharacterEncoding . New in Version 3.
$SystemID
$SystemID is a short string that identifies the type of computer system on which Mathematica
is being run.
Computer systems with the same $SystemID should be binary compatible, so that the same external programs and
.mx files can be used. Sometimes binary compatibility may only be complete when the same version of the
operating system is used. $SystemID is used in naming directories generated by DumpSave and mcc. Values for
$SystemID contain only alphanumeric characters and dashes. Typical values are "Windows", "PowerMac", "Linux"
and "Solaris". See page 717. See also: $System, $Version, $MachineType , $OperatingSystem . New in
Version 3.
$TextStyle
$TextStyle gives the default style to use for text in graphics.
The following forms of settings can be used:
"style"
{opt ->val , . . . }
{"style", opt ->val , . . . }
The options that can be given are as in StyleForm. "style" settings can only be used when a notebook front
end is present. $TextStyle gives the default value for the TextStyle option in graphics. See page 556. See
also: $FormatType, TextStyle. New in Version 3.
$TimeUnit
$TimeUnit gives the minimum time interval in seconds recorded on your computer system.
Typical values for $TimeUnit are 1/100 and 1/1000. $TimeUnit determines the minimum granularity of
measurement in functions like Timing and Date. - In some functions the actual time granularity may be much
smaller than $TimeUnit. See page 710. New in Version 2.
$Urgent
$Urgent gives the list of files and pipes to which urgent output from Mathematica is sent.
Urgent output includes input prompts, and results from ?name information requests.
Version 1.
New in
$UserBaseDirectory $VersionNumber
1339
$UserBaseDirectory
$UserBaseDirectory gives the base directory in which user-specific files to be loaded by
Mathematica are conventionally placed.
$UserBaseDirectory returns the full name of the directory as a string.
Windows
Macintosh
Unix
The value of $UserBaseDirectory can be specified by setting the MATHEMATICA_USERBASE operating system
environment variable when the Mathematica kernel is launched. It cannot be reset from inside the kernel. Typical
subdirectories of $UserBaseDirectory are:
Applications
Autoload
FrontEnd
Kernel
Licensing
SystemFiles
These subdirectories are, if possible, created automatically the first time Mathematica is run by a given user.
Appropriate subdirectories are automatically included on $Path. The subdirectories of $UserBaseDirectory are
given in $Path before the corresponding ones of $BaseDirectory . See pages 637 and 1064. See also:
$BaseDirectory, $InitialDirectory , $HomeDirectory, $InstallationDirectory . New in Version 5.0.
$UserName
$UserName gives the login name of the user who invoked the Mathematica kernel, as recorded
by the operating system.
On Unix and similar operating systems, $UserName is derived from the UID associated with the Mathematica kernel
process. On operating systems where no login name can be found, $UserName is None. See page 716. See also:
$HomeDirectory, Environment, $UserBaseDirectory . New in Version 3.
$Version
$Version is a string that represents the version of Mathematica you are running.
See page 717.
New in Version 1.
$VersionNumber
$VersionNumber is a real number which gives the current Mathematica kernel version number,
and increases in successive versions.
To find out if you are running under Version 5 or above, you can use the test TrueQ[$VersionNumber >= 5.0].
A version with a particular number is typically derived from the same source code on all computer systems.
See page 717. See also: $ReleaseNumber. New in Version 2.
1340
MLINK stdlink : the standard link that connects a program built from MathLink templates to
Mathematica
MLENV stdenv : the standard MathLink environment in a program built from MathLink templates
All functions described here are C language functions. They can be called from other languages
with appropriate wrappers.
The functions have the following general features:
Those which return int yield a non-zero value if they succeed; otherwise they return 0 and have
no effect.
In a program set up using MathLink templates, the link to Mathematica is called stdlink .
Functions which put data to a link do not deallocate memory used to store the data.
Functions which get data from a link may allocate memory to store the data.
Functions which get data from a link will not return until the necessary data becomes available. A
yield function can be registered to be called during the wait.
MLAbort MLDeinitialize()
1341
MLAbort
int MLAbort is a global variable set when a program created using mcc or mprep has been sent
an abort interrupt.
LinkInterrupt[link] can be used to send an abort interrupt from Mathematica to a program connected to a
particular link. See page 697.
MLActivate()
int MLActivate(MLINK link) activates a MathLink connection, waiting for the program at the
other end to respond.
MLActivate() can be called only after MLOpenArgv() or MLOpenString() .
MLCheckFunction()
int MLCheckFunction(MLINK link, char *name, long *n) checks that a function whose head
is a symbol with the specified name is on link, and stores the number of the arguments of the
function in n.
MLCheckFunction() returns 0 if the current object on the link is not a function with a symbol as a head, or if the
name of the symbol does not match name. See page 672. See also: MLGetFunction .
MLClearError()
int MLClearError(MLINK link) if possible clears any error on link and reactivates the link.
MLClearError() returns 0 if it was unable to clear the error. This can happen if the error was for example the
result of a link no longer being open. See page 696.
MLClose()
void MLClose(MLINK link) closes a MathLink connection.
Calling MLClose() does not necessarily terminate a program at the other end of the link. Any data buffered in
the link is sent when MLClose() is called. Programs should close all links they have opened before terminating.
See pages 692 and 698. See also: MLDeinitialize.
MLCreateMark()
MLMARK MLCreateMark(MLINK link) creates a mark at the current position in a sequence of
expressions on a link.
Calling MLCreateMark() effectively starts recording all expressions received on the link.
MLLoopbackOpen.
See also:
MLDeinitialize()
void MLDeinitialize(MLENV env) deinitializes functions in the MathLink library.
An appropriate call to MLDeinitialize() is generated automatically when an external program is created from
MathLink templates. Any external program that uses the MathLink library must call MLDeinitialize() before
exiting. MLClose() must be called for all open links before calling MLDeinitialize() . See page 698.
MLDestroyMark() MLDisownSymbol()
1342
MLDestroyMark()
int MLDestroyMark(MLINK link, MLMARK mark) destroys the specified mark on a link.
Calling MLDestroyMark() disowns memory associated with the storage of expressions recorded after the mark.
See page 693.
MLDisownByteString()
void MLDisownByteString(MLINK link, unsigned char *s, long n) disowns memory
allocated by MLGetByteString() to store the array of character codes s.
See page 679.
MLDisownIntegerArray()
void MLDisownIntegerArray(MLINK link, int *a, long *dims, char **heads, long d)
disowns memory allocated by MLGetIntegerArray() to store the array a, its dimensions dims
and the heads heads.
See page 675.
MLDisownIntegerList()
void MLDisownIntegerList(MLINK link, int *a, long n) disowns memory allocated by
MLGetIntegerList() to store the array a of length n.
See page 674.
MLDisownRealArray()
void MLDisownRealArray(MLINK link, double *a, long *dims, char **heads, long d)
disowns memory allocated by MLGetRealArray() to store the array a, its dimensions dims and
the heads heads.
See page 675.
MLDisownRealList()
void MLDisownRealList(MLINK link, double *a, long n) disowns memory allocated by
MLGetRealList() to store the array a of length n.
See page 674.
MLDisownString()
void MLDisownString(MLINK link, char *s) disowns memory allocated by MLGetString() to
store the character string s.
See page 675.
MLDisownSymbol()
void MLDisownSymbol(MLINK link, char *s) disowns memory allocated by MLGetSymbol() or
MLGetFunction() to store the character string s corresponding to the name of a symbol.
See pages 675 and 676.
MLDisownUnicodeString() MLGetArgCount()
1343
MLDisownUnicodeString()
void MLDisownUnicodeString(MLINK link, unsigned short *s, long n) disowns memory
allocated by MLGetUnicodeString() to store the string s.
See page 679.
MLEndPacket()
int MLEndPacket(MLINK link) specifies that a packet expression is complete and is ready to be
sent on the specified link.
MLEndPacket() should be called to indicate the end of any top-level expression, regardless of whether its head is a
standard packet. See pages 689 and 699.
MLError()
long MLError(MLINK link) returns a constant identifying the last error to occur on link, or 0 if
none has occurred since the previous call to MLClearError() .
You can get a textual description of errors by calling MLErrorMessage() .
MathLink errors are defined in mathlink.h. See page 696.
MLErrorMessage()
char *MLErrorMessage(MLINK link) returns a character string describing the last error to occur
on link.
See page 696.
MLEvaluateString()
int MLEvaluateString(MLINK link, char *string) sends a string to Mathematica for evaluation,
and discards any packets sent in response.
The code for MLEvaluateString() is not included in the MathLink library, but is generated automatically by mcc or
mprep in processing MathLink template files. MLEvaluateString("Print[\"string\"]") will cause string to be
printed in a Mathematica session at the other end of the link. See pages 664 and 689.
MLFlush()
int MLFlush(MLINK link) flushes out any buffers containing data waiting to be sent on link.
If you call MLNextPacket() or any of the MLGet*() functions, then MLFlush() will be called automatically. If you
call MLReady(), then you need to call MLFlush() first in order to ensure that any necessary outgoing data has been
sent. See page 700. See also: MLReady.
MLGetArgCount()
int MLGetArgCount(MLINK link, long *n) finds the number of arguments to a function on link
and stores the result in n.
See page 694.
MLGetByteString() MLGetInteger()
1344
MLGetByteString()
int MLGetByteString(MLINK link, unsigned char **s, long *n, long spec) gets a string of
characters from the MathLink connection specified by link, storing the codes for the characters
in s and the number of characters in n. The code spec is used for any character whose
Mathematica character code is larger than 255.
MLGetByteString() allocates memory for the array of character codes. You must call MLDisownByteString() to
disown this memory. MLGetByteString() is convenient in situations where no special characters occur. The
character codes used by MLGetByteString() are exactly the ones returned by ToCharacterCode in Mathematica.
The array of character codes in MLGetByteString() is not terminated by a null character. Characters such as
newlines are specified by their raw character codes, not by ASCII forms such as \n. See page 679. See also:
MLGetString, MLGetUnicodeString .
MLGetDouble()
int MLGetDouble(MLINK link, double *x) gets a floating-point number from the MathLink
connection specified by link and stores it as C type double in x.
MLGetDouble() is normally equivalent to MLGetReal().
MLGetFloat.
See also:
MLGetFloat()
int MLGetFloat(MLINK link, float *x) gets a floating-point number from the MathLink
connection specified by link and stores it as C type float in x.
See notes for MLGetReal().
MLGetFunction()
int MLGetFunction(MLINK link, char **s, long *n) gets a function with a symbol as a head
from the MathLink connection specified by link, storing the name of the symbol in s and the
number of arguments of the function in n.
MLGetFunction() allocates memory for the character string corresponding to the name of the head of the function.
You must call MLDisownSymbol() to disown this memory. External programs should not modify the character
string s. MLGetFunction(link, &s, &n) has the same effect as MLGetNext(link); MLGetArgCount(link, &n);
MLGetSymbol(link, &s). See page 676. See also: MLGetNext.
MLGetInteger()
int MLGetInteger(MLINK link, int *i) gets an integer from the MathLink connection specified
by link and stores it in i.
If the data on the link corresponds to a real number, MLGetInteger() will round it to an integer. If the data on
the link corresponds to an integer too large to store in a C int on your computer system, then MLGetInteger()
will fail, and return 0. You can get arbitrary-precision integers by first using IntegerDigits to generate lists of
digits, then calling MLGetIntegerList() . See page 694. See also: MLGetShortInteger , MLGetLongInteger .
MLGetIntegerArray() MLGetReal()
1345
MLGetIntegerArray()
int MLGetIntegerArray(MLINK link, int **a, long **dims, char ***heads, long *d) gets an
array of integers from the MathLink connection specified by link, storing the array in a, its
dimensions in dims and its depth in d.
The array a is laid out in memory like a C array declared as int a[m][n]. . . . heads gives a list of character strings
corresponding to the names of symbols that appear as heads at each level in the array. MLGetIntegerArray()
allocates memory which must be disowned by calling MLDisownIntegerArray() . External programs should not
modify the arrays generated by MLGetIntegerArray() . See page 675. See also: MLGetIntegerList .
MLGetIntegerList()
int MLGetIntegerList(MLINK link, int **a, long *n) gets a list of integers from the
MathLink connection specified by link, storing the integers in the array a and the length of the
list in n.
MLGetIntegerList() allocates memory for the array of integers. You must call MLDisownIntegerList() to disown
this memory. External programs should not modify the array generated by MLGetIntegerList() . See notes for
MLGetInteger(). See page 674. See also: MLGetIntegerArray , MLGetByteString .
MLGetLongInteger()
int MLGetLongInteger(MLINK link, long *i) gets an integer from the MathLink connection
specified by link and stores it as a C long in i.
See notes for MLGetInteger().
MLGetNext()
int MLGetNext(MLINK link) goes to the next object on link and returns its type.
The following values can be returned:
MLTKERR
MLTKINT
MLTKFUNC
MLTKREAL
MLTKSTR
MLTKSYM
error
integer
composite function
approximate real number
character string
symbol
MLTKINT and MLTKREAL do not necessarily signify numbers that can be stored in C int and double variables.
See page 694. See also: MLGetArgCount.
MLGetReal()
int MLGetReal(MLINK link, double *x) gets a floating-point number from the MathLink
connection specified by link and stores it in x.
If the data on the link corresponds to an integer, MLGetReal() will coerce it to a double before storing it in x. If
the data on the link corresponds to a number outside the range that can be stored in a C double on your
computer system, then MLGetReal() will fail, and return 0. You can get arbitrary-precision real numbers by first
using RealDigits to generate lists of digits, then calling MLGetIntegerList() . MLGetReal() is normally
equivalent to MLGetDouble(). See page 694. See also: MLGetFloat, MLGetDouble, MLGetRealList.
1346
MLGetRealArray() MLGetUnicodeString()
MLGetRealArray()
int MLGetRealArray(MLINK link, double **a, long **dims, char ***heads, long *d) gets an
array of floating-point numbers from the MathLink connection specified by link, storing the
array in a, its dimensions in dims and its depth in d.
The array a is laid out in memory like a C array declared as double a[m][n]. . . . heads gives a list of character
strings corresponding to the names of symbols that appear as heads at each level in the array. MLGetRealArray()
allocates memory which must be disowned by calling MLDisownRealArray() . External programs should not
modify the arrays generated by MLGetRealArray() . See page 675.
MLGetRealList()
int MLGetRealList(MLINK link, double **a, long *n) gets a list of floating-point numbers
from the MathLink connection specified by link, storing the numbers in the array a and the
length of the list in n.
MLGetRealList() allocates memory for the array of numbers. You must call MLDisownRealList() to disown this
memory. External programs should not modify the array generated by MLGetRealList(). See notes for
MLGetReal(). See page 674.
MLGetShortInteger()
int MLGetShortInteger(MLINK link, short *i) gets an integer from the MathLink connection
specified by link and stores it as a C short in i.
See notes for MLGetInteger() .
MLGetString()
int MLGetString(MLINK link, char **s) gets a character string from the MathLink connection
specified by link, storing the string in s.
MLGetString() allocates memory for the character string. You must call MLDisownString() to disown this memory.
External programs should not modify strings generated by MLGetString() . MLGetString() creates a string that
is terminated by \0. MLGetString() stores single \ characters from Mathematica as pairs of characters \\.
MLGetString() stores special characters from Mathematica in a private format. See pages 675 and 694. See
also: MLGetByteString, MLGetUnicodeString .
MLGetSymbol()
int MLGetSymbol(MLINK link, char **s) gets a character string corresponding to the name of
a symbol from the MathLink connection specified by link, storing the resulting string in s.
MLGetSymbol() allocates memory for the character string. You must call MLDisownSymbol() to disown this memory.
MLGetSymbol() creates a string that is terminated by \0. See pages 675 and 694.
MLGetUnicodeString()
int MLGetUnicodeString(MLINK link, unsigned short **s, long *n) gets a character string
from the MathLink connection specified by link, storing the string in s as a sequence of 16-bit
Unicode characters.
MLGetUnicodeString() allocates memory for the character string. You must call MLDisownUnicodeString() to
disown this memory. External programs should not modify strings generated by MLGetUnicodeString() .
MLGetUnicodeString() stores all characters directly in 16-bit Unicode form. 8-bit ASCII characters are stored
with a null high-order byte. See page 679. See also: MLGetString, MLGetByteString .
MLInitialize() MLOpenArgv()
1347
MLInitialize()
MLENV MLInitialize(0) initializes functions in the MathLink library.
An appropriate call to MLInitialize() is generated automatically when an external program is created from
MathLink templates. Any external program that uses the MathLink library must call MLInitialize() before calling
any other MathLink library functions. See page 698.
MLLoopbackOpen()
MLINK MLLoopbackOpen(MLENV env, long *errno) opens a loopback MathLink connection.
In an external program set up with MathLink templates, the environment stdenv should be used. You can use
loopback links to effectively store Mathematica expressions in external programs. See page 692. See also:
MLCreateMark.
MLMain()
int MLMain(int argc, char **argv) sets up communication between an external program
started using Install and Mathematica.
The code for MLMain() is generated automatically by mprep or mcc. MLMain() opens a MathLink connection using
the parameters specified in argv, then goes into a loop waiting for CallPacket objects to arrive from Mathematica.
MLMain() internally calls MLOpenArgv() . See page 664.
MLNewPacket()
int MLNewPacket(MLINK link) skips to the end of the current packet on link.
MLNewPacket() works even if the head of the current top-level expression is not a standard packet type.
MLNewPacket() does nothing if you are already at the end of a packet. See pages 697 and 699. See also:
MLNextPacket.
MLNextPacket()
int MLNextPacket(MLINK link) goes to the next packet on link and returns a constant to
indicate its head.
See page 699.
MLOpenArgv()
MLINK MLOpenArgv(MLENV env, char **argv0, char **argv1, long *errno) opens a MathLink
connection taking parameters from an argv array.
MLInitialize() must be called before MLOpenArgv(). MLOpenArgv() scans for the following at successive
locations starting at argv0 and going up to just before argv1:
"-linkconnect"
"-linkcreate"
"-linklaunch"
"-linkname", "name"
"-linkprotocol", "protocol"
MLOpenArgv() is not sensitive to the case of argument names. MLOpenArgv() ignores argument names that it
does not recognize. MLOpenArgv() is called automatically by the MLMain() function created by mprep and mcc.
With a main program main(int argc, char *argv[]) typical usage is
MLOpenArgv(env, argv, argv+argc, errno). Avoiding an explicit argc argument allows MLOpenArgv() to work
independent of the size of an int. On some computer systems, giving 0 for argv0 and argv1 will cause arguments
to be requested interactively, typically through a dialog box. See page 698. See also: MLActivate, MLOpenString.
MLOpenString() MLPutInteger()
1348
MLOpenString()
MLINK MLOpenString(MLENV env, char *string, long *errno) opens a MathLink connection
taking parameters from a character string.
MLInitialize() must be called before MLOpenString(). MLOpenString() takes a single string instead of the argv
array used by MLOpenArgv(). Arguments in the string are separated by spaces. On some computer systems,
giving NULL in place of the string pointer will cause arguments to be requested interactively, typically through a
dialog box. See page 698. See also: MLActivate, MLOpenArgv.
MLPutArgCount()
int MLPutArgCount(MLINK link, long n) specifies the number of arguments of a composite
function to be put on link.
MLPutByteString()
int MLPutByteString(MLINK link, unsigned char *s, long n) puts a string of n characters
starting from location s to the MathLink connection specified by link.
All characters in the string must be specified using character codes as obtained from ToCharacterCode in
Mathematica. Newlines must thus be specified in terms of their raw character codes, rather than using \n.
MLPutByteString() handles only characters with codes less than 256. It can handle both ordinary ASCII as
well as ISO Latin-1 characters. See page 679. See also: MLPutString, MLPutIntegerList .
MLPutDouble()
int MLPutDouble(MLINK link, double x) puts the floating-point number x of C type double to
the MathLink connection specified by link.
See notes for MLPutReal().
MLPutFloat()
int MLPutFloat(MLINK link, double x) puts the floating-point number x to the MathLink
connection specified by link with a precision corresponding to the C type float.
The argument x is typically declared as float in external programs, but must be declared as double in
MLPutFloat() itself in order to work even in the absence of C prototypes. See notes for MLPutReal().
page 678.
See
MLPutFunction()
int MLPutFunction(MLINK link, char *s, long n) puts a function with head given by a
symbol with name s and with n arguments to the MathLink connection specified by link.
After the call to MLPutFunction() other MathLink functions must be called to send the arguments of the function.
See page 667. See also: MLPutString.
MLPutInteger()
int MLPutInteger(MLINK link, int i) puts the integer i to the MathLink connection specified
by link.
You can send arbitrary-precision integers to Mathematica by giving lists of digits, then converting them to numbers
using FromDigits. See pages 667 and 696. See also: MLGetInteger, MLPutShortInteger , MLPutLongInteger ,
MLPutIntegerList .
MLPutIntegerArray() MLPutRealList()
1349
MLPutIntegerArray()
int MLPutIntegerArray(MLINK link, int *a, long *dims, char **heads, long d) puts an
array of integers to the MathLink connection specified by link to form a depth d array with
dimensions dims.
The array a must be laid out in memory like a C array declared explicitly as int a[m][n]. . . . If heads is given as
NULL, the array will be assumed to have head List at every level. The length of the array at level i is taken to
be dims[i]. See page 667. See also: MLPutIntegerList .
MLPutIntegerList()
int MLPutIntegerList(MLINK link, int *a, long n) puts a list of n integers starting from
location a to the MathLink connection specified by link.
See page 667.
MLPutLongInteger()
int MLPutLongInteger(MLINK link, long i) puts the long integer i to the MathLink connection
specified by link.
See notes for MLPutInteger().
MLPutNext()
int MLPutNext(MLINK link, int type) prepares to put an object of the specified type on link.
The type specifications are as given in the notes for MLGetNext().
MLPutReal()
int MLPutReal(MLINK link, double x) puts the floating-point number x to the MathLink
connection specified by link.
You can send arbitrary-precision real numbers to Mathematica by giving lists of digits, then converting them to
numbers using FromDigits. MLPutReal() is normally equivalent to MLPutDouble(). See pages 667 and 696.
See also: MLPutRealList, MLPutFloat, MLPutDouble.
MLPutRealArray()
int MLPutRealArray(MLINK link, double *a, long *dims, char **heads, long d) puts an
array of floating-point numbers to the MathLink connection specified by link to form a depth d
array with dimensions dims.
The array a must be laid out in memory like a C array declared explicitly as double a[m][n]. . . . If heads is given
as NULL, the array will be assumed to have head List at every level. The length of the array at level i is taken
to be dims[i]. See page 667. See also: MLPutRealList.
MLPutRealList()
int MLPutRealList(MLINK link, double *a, long n) puts a list of n floating-point numbers
starting from location a to the MathLink connection specified by link.
See page 667.
MLPutShortInteger() MLTransferExpression()
1350
MLPutShortInteger()
int MLPutShortInteger(MLINK link, int i) puts the integer i to the MathLink connection
specified by link, assuming that i contains only the number of digits in the C type short.
The argument i is typically declared as short in external programs, but must be declared as int in
MLPutShortInteger() itself in order to work even in the absence of C prototypes. See notes for MLPutInteger() .
See page 678.
MLPutString()
int MLPutString(MLINK link, char *s) puts a character string to the MathLink connection
specified by link.
The character string must be terminated with a null byte, corresponding to \0 in C. A raw backslash in the
string must be sent as two characters \\. Special characters can be sent only using the private format returned by
MLGetString(). See pages 667 and 696. See also: MLPutByteString , MLPutUnicodeString , MLPutSymbol.
MLPutSymbol()
int MLPutSymbol(MLINK link, char *s) puts a symbol whose name is given by the character
string s to the MathLink connection specified by link.
The character string must be terminated with \0.
MLPutUnicodeString()
int MLPutUnicodeString(MLINK link, unsigned short *s, long n) puts a string of n 16-bit
Unicode characters to the MathLink connection specified by link.
All characters are assumed to be 16 bit. 8-bit characters can be sent by having the higher-order byte be null.
See page 679. See also: MLPutString, MLPutByteString.
MLReady()
int MLReady(MLINK link) tests whether there is data ready to be read from link.
Analogous to the Mathematica function LinkReadyQ. MLReady() is often called in a loop as a way of polling a
MathLink connection. MLReady() will always return immediately, and will not block. You need to call MLFlush()
before starting to call MLReady(). See page 700.
MLSeekMark()
MLMARK MLSeekMark(MLINK link, MLMARK mark, long n) goes back to a position n expressions
after the specified mark on a link.
See page 693.
MLTransferExpression()
int MLTransferExpression(MLINK dest, MLINK src) transfers an expression from one
MathLink connection to another.
src and dest need not be distinct.
1351
Prefix operators
e.g. x
Postfix operators
e.g. x!
Matchfix operators
Compound operators
Raw operators
Spacing characters
Structural elements
Uninterpretable elements
e.g. /x0
e.g. f 7 x
operator characters that can be typed on an ordinary
keyboard
interpreted in the same way as an ordinary space
characters used to specify structure; usually ignored in
interpretation
characters indicating missing information
Types of characters.
1352
Infix operators for which no grouping is specified in the listing are interpreted so that for example
x O y O z becomes CirclePlus[x, y, z].
Naming Conventions
Characters that correspond to built-in Mathematica functions typically have names corresponding to
those functions. Other characters typically have names that are as generic as possible.
Characters with different names almost always look at least slightly different.
\[Capital... ]
\[Left...] and \[Right...]
\[Raw...]
\[...Indicator]
style
variation
case
modifiers
direction
base
diacritical mark
Aliases
Mathematica supports both its own system of aliases, as well as aliases based on character names in TEX
and SGML or HTML. Except where they conflict, character names corresponding to plain TEX, LATEX
and AMSTEX are all supported. Note that TEX and SGML or HTML aliases are not given explicitly in
the list of characters below.
HxxxH
1353
H\xxxH
TEX alias
H&xxxH
Types of aliases.
Font Matching
The special fonts provided with Mathematica include all the characters given in this listing. Some of
these characters also appear in certain ordinary text fonts.
When rendering text in a particular font, the Mathematica notebook front end will use all the
characters available in that font. It will use the special Mathematica fonts only for other characters.
A choice is made between Times-like, Helvetica-like (sans serif) and Courier-like (monospaced)
variants to achieve the best matching with the ordinary text font in use.
AAcute Angle
1354
\[AAcute]
Alias: , a' ,.
Letter.
Letter.
Letter.
Letter.
\[AHat]
Alias: , a^ ,.
\[AGrave]
Alias: , a` ,.
See
\[AE]
Alias: , ae ,.
a`
\[ADoubleDot]
Alias: , a" ,. Letter.
\[EDoubleDot].
\[ACup]
Alias: , au ,. Letter. Included in ISO Latin-2.
See also: \[CapitalACup].
\[ABar]
Alias: , a- ,. Letter. Included in ISO Latin-4.
page 998. See also: \[CapitalABar].
\[Aleph]
Alias: , al ,. Hebrew letter. Sometimes called alef. Used in pure mathematics to denote transfinite cardinals.
See pages 192 and 993. See also: \[Bet], \[Gimel], \[Dalet].
\[AliasIndicator]
Alias: , esc ,. Letter-like form. Representation of the indicator for special character aliases in Mathematica.
\[AliasIndicator] is an inactive letter-like form, used in describing how to type aliases. An active character
of the same appearance is typically obtained by typing ESCAPE. See page 1009. See also: \[EscapeKey] ,
\[SpaceIndicator] , \[ReturnIndicator] .
\[AlignmentMarker]
Alias: , am ,. Letter-like form. Invisible by default on display. Used as a marker to indicate for example how
entries in a GridBox column should be lined up. See pages 451 and 1008. See also: \[InvisibleComma] ,
\[InvisibleSpace] , \[Null], \[NoBreak].
\[Alpha]
Aliases: , a ,, , alpha ,.
\[CapitalAlpha] .
Greek letter.
See also:
\[And]
Aliases: , && ,, , and ,. Infix operator with built-in evaluation rules. x y is by default interpreted as And[x, y],
equivalent to x && y. Not the same as \[Wedge]. Drawn slightly larger than \[Wedge]. See page 1001. See
also: \[Or], \[Nand], \[Not].
\[Angle]
Letter-like form. Used in geometry to indicate an angle, as in the symbol R ABC.
also: \[MeasuredAngle], \[SphericalAngle] , \[RightAngle] .
See
Angstrom CapitalAAcute
1355
\[Angstrom]
Alias: , Ang ,. Letter-like form. Unit corresponding to meters. Not the same as the letter
\[CapitalARing]. See pages 192 and 994. See also: \[ARing], \[Micro], \[EmptySmallCircle] , \[HBar].
\[ARing]
Alias: , ao ,. Letter. Included in ISO Latin-1.
\[EmptySmallCircle] .
\[AscendingEllipsis]
Letter-like form. Used to indicate omitted elements in a matrix.
\[DescendingEllipsis] , \[VerticalEllipsis] , \[Ellipsis].
See also:
\[ATilde]
Alias: , a~ ,.
Letter.
\[Backslash]
Alias: , \ ,. Infix operator. x - y is by default interpreted as Backslash[x, y]. Used in mathematics for set
difference. Also used to separate arguments of elliptic functions. Sometimes used to indicate x divides y. See
pages 191 and 1002. See also: \[RawBackslash], \[Colon], \[VerticalBar], \[Continuation].
\[Because]
Infix operator. x , y is by default interpreted as Because[x, y]. x , y , z groups as (x , y) , z.
page 1001. See also: \[Therefore], \[LeftTee], \[FilledRectangle] , \[Proportion].
"
\[Bet]
Alias: , be ,. Hebrew letter. Sometimes called beth.
cardinals. See page 993. See also: \[Aleph].
\[Beta]
Aliases: , b ,, , beta ,.
Greek letter.
\[Breve]
Alias: , bv ,. Letter-like form. Used in an overscript position as a diacritical mark.
\[DownBreve], \[Cup], \[RoundSpaceIndicator] , \[Hacek].
See also:
Letter-like form.
\[CAcute]
Alias: , c' ,.
\[Bullet]
Alias: , bu ,.
See
Letter.
\[Cap]
Infix operator. x % y is by default interpreted as Cap[x, y]. Used in pure mathematics to mean cap product.
Sometimes used as an overscript to indicate arc between. See page 1002. See also: \[Cup], \[Intersection],
\[CupCap], \[DownBreve].
\[CapitalAAcute]
Alias: , A' ,.
Letter.
CapitalABar CapitalDelta
1356
\[CapitalABar]
Alias: , A- ,.
Letter.
Letter.
Letter.
Letter.
Letter.
Letter.
Letter.
See
Letter.
Letter.
See
\[CapitalChi]
Aliases: , Ch ,, , Chi ,, , C ,.
\[CapitalXi].
\[CapitalCHacek]
Alias: , Cv ,.
\[CapitalCCedilla]
Alias: , C, ,.
\[CapitalCAcute]
Alias: , C' ,.
\[CapitalBeta]
Aliases: , B ,, , Beta ,. Greek letter.
page 990. See also: \[Beta].
\[CapitalATilde]
Alias: , A~ ,.
Greek letter.
\[CapitalARing]
Alias: , Ao ,. Letter.
also: \[ARing].
\[CapitalAlpha]
Aliases: , A ,, , Alpha ,.
\[CapitalAHat]
Alias: , A^ ,.
\[CapitalAGrave]
Alias: , A` ,.
\[CapitalAE]
Alias: , AE ,.
`
A
\[CapitalADoubleDot]
Alias: , A" ,.
\[CapitalACup]
Alias: , Au ,. Letter.
See also: \[ACup].
Greek letter.
\[CapitalDelta]
Aliases: , D ,, , Delta ,. Greek letter. Not the same as \[EmptyUpTriangle] .
denote Laplacian. See pages 175 and 990. See also: \[Delta], \[Del].
CapitalDifferentialD CapitalIGrave
1357
\[CapitalDifferentialD]
Alias: , DD ,. Compound operator. ) can only be interpreted by default when it appears with or other integral
operators. Used in mathematics to indicate a functional differential. See page 994. See also:
\[DifferentialD], \[DoubleStruckD] .
\[CapitalDigamma]
Aliases: , Di ,, , Digamma ,.
Letter.
Letter.
Letter.
Letter.
Letter.
\[CapitalEpsilon]
Greek letter.
Letter.
Letter.
\[CapitalICup]
Letter.
\[CapitalIDoubleDot]
Alias: , I" ,.
I`
\[CapitalIAcute]
Alias: , Iu ,.
\[CapitalGamma]
Alias: , I' ,.
\[CapitalEth]
Alias: , D- ,.
Greek letter.
\[CapitalEta]
Aliases: , Et ,, , Eta ,, , H ,.
Aliases: , E ,, , Epsilon ,.
\[CapitalEHat]
Alias: , E^ ,.
\[CapitalEGrave]
Alias: , E` ,.
Letter.
\[CapitalEDoubleDot]
Alias: , E" ,.
E`
\[CapitalECup]
Alias: , Eu ,.
\[CapitalEBar]
Alias: , E- ,.
Analogous to English W.
\[CapitalEAcute]
Alias: , E' ,.
Letter.
\[CapitalIGrave]
Alias: , I` ,.
Letter.
See also:
CapitalIHat CapitalOSlash
1358
\[CapitalIHat]
Alias: , I^ ,.
Letter.
Greek letter.
Letter.
Greek letter.
Letter.
Greek letter.
Letter.
Letter.
Letter.
Letter.
\[CapitalOHat]
Letter.
\[CapitalOmega]
Greek letter.
See also:
\[CapitalOmicron]
Aliases: , Om ,, , Omicron ,.
Aliases: , O ,, , Omega ,, , W ,.
\[Omega], \[Mho].
\[CapitalOGrave]
Alias: , O^ ,.
Greek letter.
\[CapitalODoubleDot]
Alias: , O` ,.
\[CapitalODoubleAcute]
Alias: , O" ,.
`
O
\[CapitalOAcute]
Alias: , O'' ,.
Analogous to English Q.
\[CapitalNu]
Alias: , O' ,.
\[CapitalNTilde]
Aliases: , N ,, , Nu ,.
\[CapitalMu]
Alias: , N~ ,.
\[CapitalLSlash]
Aliases: , M ,, , Mu ,.
\[CapitalLambda]
Alias: , L/ ,.
\[CapitalKoppa]
Aliases: , L ,, , Lambda ,.
Greek letter.
Aliases: , Ko ,, , Koppa ,.
\[CapitalKappa]
Aliases: , K ,, , Kappa ,.
\[CapitalIota]
Aliases: , I ,, , Iota ,.
Greek letter.
\[CapitalOSlash]
Alias: , O/ ,. Letter. Included in ISO Latin-1.
See also: \[OSlash].
Letter.
\[CapitalPhi]
Aliases: , Ph ,, , Phi ,, , F ,.
also: \[Phi].
Greek letter.
Greek letter.
Letter.
Greek letter.
Greek letter.
Greek letter.
Letter.
Letter.
\[CapitalUDoubleAcute]
Letter.
\[CapitalUDoubleDot]
Letter.
\[CapitalUGrave]
Alias: , U` ,.
\[CapitalUAcute]
Alias: , U" ,.
`
U
\[CapitalThorn]
Alias: , U'' ,.
\[CapitalTheta]
Alias: , U' ,.
\[CapitalTau]
Alias: , Thn ,.
\[CapitalStigma]
Aliases: , Th ,, , Theta ,, , Q ,.
\[CapitalSigma]
Aliases: , T ,, , Tau ,.
Aliases: , S ,, , Sigma ,.
\[CapitalSHacek]
Alias: , Sv ,.
\[CapitalSampi]
Aliases: , Sa ,, , Sampi ,.
Greek letter.
\[CapitalRho]
Aliases: , R ,, , Rho ,.
\[CapitalPsi]
Aliases: , Ps ,, , Psi ,, , Y ,.
\[CapitalPi]
Aliases: , P ,, , Pi ,. Greek letter. Used in TraditionalForm for EllipticPi.
See pages 175 and 990. See also: \[Pi].
1359
\[CapitalOTilde]
Alias: , O~ ,.
CapitalOTilde CapitalUHat
Letter.
\[CapitalUHat]
Alias: , U^ ,.
Letter.
See
CapitalUpsilon CircleMinus
1360
\[CapitalUpsilon]
Aliases: , U ,, , Upsilon ,. Greek letter. Not commonly used. Used in physics for bb particles, and in the
quantum theory of measurement. See pages 175 and 990. See also: \[CurlyCapitalUpsilon] , \[Upsilon].
\[CapitalXi]
Aliases: , X ,, , Xi ,. Greek letter. Not commonly used. Used for grand canonical partition function, cascade
hyperon and regular language complexity. See page 990. See also: \[Xi].
\[CapitalYAcute]
Alias: , Y' ,.
Letter.
\[CapitalZeta]
Aliases: , Z ,, , Zeta ,. Greek letter. Used in TraditionalForm for JacobiZeta.
See page 990. See also: \[Zeta].
\[CCedilla]
Alias: , c, ,.
Letter.
See also:
\[Cent]
Alias: , cent ,.
&
\[Cedilla]
Alias: , cd ,. Letter-like form.
\[Hacek], \[Breve].
Letter-like form.
\[CenterDot]
Alias: , . ,. Infix operator. x o y is by default interpreted as CenterDot[x, y]. Used to indicate various forms
of multiplication, particularly dot products of vectors. Sometimes used to indicate concatenation or composition.
Used in the British mathematical tradition as a decimal point. See page 1002. See also: \[CenterEllipsis] ,
\[RawDot], \[CircleDot].
\[CenterEllipsis]
Letter-like form. Used to indicate omitted elements in a row of a matrix.
\[VerticalEllipsis] , \[CenterDot].
Letter.
\[Chi]
Aliases: , ch ,, , chi ,, , c ,.
\[CHacek]
Alias: , cv ,.
Greek letter.
\[CircleDot]
Alias: , c. ,. Infix operator. x y is by default interpreted as CircleDot[x, y]. Used in mathematics for
various operations related to multiplication, such as direct or tensor products. Also sometimes used to indicate a
vector pointing out of the page. See page 1002. See also: \[CircleTimes], \[CenterDot].
\[CircleMinus]
Alias: , c- ,. Infix operator.
\[CirclePlus].
See also:
CirclePlus ControlKey
1361
\[CirclePlus]
Alias: , c+ ,. Infix operator. x O y is by default interpreted as CirclePlus[x, y]. Used in mathematics for
various operations related to addition, such as direct sum and addition modulo two. Also sometimes used to
indicate a vector pointing into the page. See pages 191 and 1002. See also: \[CircleTimes], \[CircleMinus],
\[Xor].
\[CircleTimes]
Alias: , c* ,. Infix and prefix operator. x g y is by default interpreted as CircleTimes[x, y]. Used in
mathematics for various operations related to multiplication, such as direct or tensor products. Also sometimes
used to indicate a vector pointing into the page. See pages 191 and 1002. See also: \[CircleDot], \[Times],
\[Cross], \[Wedge], \[CirclePlus] .
\[ClockwiseContourIntegral]
Alias: , ccint ,. Compound operator (see page 1031). J f 7x is by default interpreted as
ClockwiseContourIntegral[f, x]. See page 1000. See also: \[CounterClockwiseContourIntegral] ,
\[ContourIntegral] .
\[CloverLeaf]
Alias: , cl ,. Letter-like form. Used on Macintosh and other computers to indicate command keys.
page 1009. See also: \[CommandKey].
\[ClubSuit]
Letter-like form.
See
\[Colon]
Alias: , : ,. Infix operator. x : y is by default interpreted as Colon[x, y]. Used in mathematics to mean such
that. Occasionally used to indicate proportion. Used to separate hours and minutes in times. See page 1001.
See also: \[SuchThat], \[VerticalSeparator] , \[Exists], \[ForAll], \[RawColon], \[Proportion],
\[Therefore].
\[CommandKey]
Alias: , cmd ,. Letter-like form. Representation of the COMMAND or ALT key on a keyboard.
also: \[CloverLeaf], \[LeftModified], \[ControlKey], \[EscapeKey].
See
\[Congruent]
Alias: , === ,. Infix similarity operator. x k y is by default interpreted as Congruent[x, y]. Used in
mathematics for many notions of equivalence and equality. See pages 191 and 1003. See also: \[NotCongruent],
\[Equal], \[TildeFullEqual] , \[CupCap], \[LeftRightArrow] .
\[Continuation]
Alias: , cont ,. Structural element. Used at the end of a line of input to indicate that the expression on that line
continues onto the next line. Equivalent in meaning to \ at the end of a line. Not the same as
\[DescendingEllipsis] . See page 1009. See also: \[RawBackslash] , \[Backslash] , \[ReturnIndicator] .
)
Q
\[ContourIntegral]
Alias: , cint ,. Compound operator (see page 1031). 5 f 7x is by default interpreted as ContourIntegral[f, x].
See page 1000. See also: \[ClockwiseContourIntegral] , \[DoubleContourIntegral] .
\[ControlKey]
Alias: , ctrl ,. Letter-like form. Representation of the CONTROL key on a keyboard.
\[LeftModified], \[CommandKey], \[EscapeKey] , \[ReturnKey].
See also:
Coproduct CurlyTheta
1362
\[Coproduct]
Alias: , coprod ,. Infix operator. x 1 y is by default interpreted as Coproduct[x, y]. 1 x is by default
interpreted as Coproduct[x]. Coproduct is used as an abstract dual to the operation of multiplication, most often
in infix form. See page 1002. See also: \[Product], \[Wedge], \[Vee], \[CircleTimes] , \[SquareUnion] .
\[Copyright]
Letter-like form.
\[CounterClockwiseContourIntegral]
Alias: , cccint ,. Compound operator (see page 1031). K f 7x is by default interpreted as
CounterClockwiseContourIntegral[f, x]. See page 1000. See also: \[ClockwiseContourIntegral] ,
\[ContourIntegral] .
\[Cross]
Alias: , cross ,. Infix operator with built-in evaluation rules. x y is by default interpreted as Cross[x, y].
Not the same as \[Times]. \[Cross] represents vector cross product, while \[Times] represents ordinary
multiplication. \[Cross] is drawn smaller than \[Times]. See page 1000. See also: \[CircleTimes].
\[Cup]
Infix operator. x & y is by default interpreted as Cup[x, y]. Used in pure mathematics to mean cup product.
See page 1002. See also: \[Cap], \[Union], \[CupCap], \[RoundSpaceIndicator] , \[Breve].
\[CupCap]
Infix similarity operator. x . y is by default interpreted as CupCap[x, y]. Used in mathematics for various
notions of equivalence, usually fairly weak. f . g is often specifically used to indicate that f/g has bounded
variation. See page 1003. See also: \[NotCupCap] , \[Cap], \[Cup].
\[CurlyCapitalUpsilon]
Aliases: , cU ,, , cUpsilon ,. Greek letter. Not commonly used.
page 990. See also: \[CapitalUpsilon] .
See
\[CurlyEpsilon]
Aliases: , ce ,, , cepsilon ,. Greek letter. Not the same as \[Element]. Used in physics for Fermi energy and
dielectric constant. See page 990. See also: \[Epsilon], \[ScriptCapitalE] .
\[CurlyKappa]
Aliases: , ck ,, , ckappa ,.
Greek letter.
Greek letter.
\[CurlyRho]
Aliases: , cr ,, , crho ,.
Greek letter.
See also:
\[CurlyPi]
Aliases: , cp ,, , cpi ,.
\[Omega].
\[CurlyPhi]
Aliases: , j ,, , cph ,, , cphi ,.
\[Phi].
Greek letter.
\[CurlyTheta]
Aliases: , cq ,, , cth ,, , ctheta ,. Greek letter. Used in TraditionalForm for EllipticTheta and
RiemannSiegelTheta . See page 990. See also: \[CapitalTheta] , \[Theta].
Dagger Divide
\[Dagger]
Alias: , dg ,. Letter-like form and overfix operator.
pages 192 and 996. See also: \[DoubleDagger] .
1363
See
\[Dalet]
Alias: , da ,. Hebrew letter. Sometimes called daleth. Used occasionally in pure mathematics in the theory of
transfinite cardinals. See page 993. See also: \[Aleph].
\[Dash]
Alias: , - ,.
Letter-like form.
\[Degree]
Alias: , deg ,. Letter-like form with built-in value. Interpreted by default as the symbol Degree. 30 is
interpreted as 30 Degree. The symbol is sometimes used in mathematics to indicate the interior of a set. Not
the same as \[SmallCircle] or \[EmptySmallCircle] . See page 994. See also: \[Prime], \[DoublePrime] .
\[Del]
Alias: , del ,. Prefix operator. Yf is by default interpreted as Del[f]. Used in vector analysis to denote gradient
operator and its generalizations. Used in numerical analysis to denote backward difference operator. Also called
nabla. Not the same as \[EmptyDownTriangle] . See pages 994 and 1000. See also: \[CapitalDelta] ,
\[PartialD], \[Square].
\[Delta]
Aliases: , d ,, , delta ,.
Greek letter.
\[DescendingEllipsis]
Letter-like form. Used to indicate omitted elements in a matrix. Not the same as \[Continuation].
page 997. See also: \[AscendingEllipsis] , \[VerticalEllipsis] , \[Ellipsis].
>
\[Diameter]
Letter-like form.
Used in geometry.
See also:
\[DiamondSuit]
Letter-like form. Sometimes used to indicate the end of a proof.
\[EmptyDiamond]. See page 996. See also: \[ClubSuit].
\[Diamond]
Alias: , dia ,. Infix operator. x n y is by default interpreted as Diamond[x, y].
\[EmptyDiamond], \[FilledDiamond] , \[DiamondSuit].
See
\[DifferentialD]
Alias: , dd ,. Compound operator with built-in evaluation rules. ( can only be interpreted by default when it
appears with or other integral operators. f 7x is by default interpreted as Integrate[f, x].
\[DifferentialD] is also used in TraditionalForm to indicate total derivatives. See pages 185, 994 and 1000.
See also: \[PartialD], \[CapitalDifferentialD] , \[Delta].
\[Digamma]
Aliases: , di ,, , digamma ,. Special Greek letter. Analogous to English w. Sometimes used to denote
PolyGamma[x]. See page 990. See also: \[CapitalDigamma] , \[Koppa], \[Stigma], \[Sampi].
\[Divide]
Alias: , div ,. Infix operator with built-in evaluation rules.
x / y. x
y
z groups as (x
y)
z. See page 1000.
x
y is by default interpreted as Divide[x, y] or
See also: \[Times], \[Proportion], \[Backslash].
DotEqual DoubleLeftTee
1364
\[DotEqual]
Alias: , .= ,. Infix similarity operator. x / y is by default interpreted as DotEqual[x, y]. Used to mean
approximately equal, or in some cases, image of, or equal by definition. See page 1003. See also:
\[TildeEqual], \[RightArrow].
\[DotlessI]
Letter. Used when an i will have an overscript on top.
font. See page 992. See also: \[DotlessJ], \[Iota].
\[DotlessJ]
Letter. Used when a j will have an overscript on top.
See page 992. See also: \[DotlessI].
\[DoubleContourIntegral]
Compound operator (see page 1031). L f 7s is by default interpreted as ContourIntegral[f, s]. Used to
indicate integrals over closed surfaces. See page 1000. See also: \[ContourIntegral] , \[Integral].
\[DoubleDagger]
Alias: , ddg ,.
May or may not match the ordinary j from the text font.
\[DottedSquare]
Letter-like form.
Letter-like form.
\[DoubledGamma]
Alias: , gg ,. Letter-like form. Not by default assigned any interpretation in StandardForm . Interpreted as
EulerGamma in TraditionalForm. Not the same as \[Gamma]. See page 994. See also: \[DoubledPi],
\[ExponentialE] , \[DoubleStruckA] .
'
\[DoubleDownArrow]
Infix arrow operator. x s y is by default interpreted as DoubleDownArrow[x, y].
page 1006. See also: \[DownArrow], \[DoubleUpArrow] .
Extensible character.
\[DoubledPi]
Alias: , pp ,. Letter-like form. Not by default assigned any interpretation. Not the same as \[Pi].
page 994. See also: \[DoubledGamma] , \[ExponentialE] , \[DoubleStruckA] .
See
See
\[DoubleLeftArrow]
Alias: , <= ,. Infix arrow operator. x t y is by default interpreted as DoubleLeftArrow[x, y]. Extensible
character. , <= , is the alias for \[LessEqual]. The alias for \[DoubleLeftArrow] has a space at the beginning.
See page 1006. See also: \[DoubleLongLeftArrow] , \[LeftArrow], \[DoubleRightArrow] .
\[DoubleLeftRightArrow]
Alias: , <=> ,. Infix arrow operator. x u y is by default interpreted as DoubleLeftRightArrow[x, y]. Used in
mathematics to indicate logical equivalence. Extensible character. See page 1006. See also:
\[DoubleLongLeftRightArrow] , \[LeftRightArrow] , \[RightArrowLeftArrow] , \[LeftArrowRightArrow] ,
\[Congruent], \[Implies].
\[DoubleLeftTee]
Infix operator. x + y is by default interpreted as DoubleLeftTee[x, y]. x + y + z groups as (x + y) + z.
Used in mathematics to indicate various strong forms of logical implication of x from yoften tautological
implication. See pages 1001 and 1007. See also: \[LeftTee], \[DoubleRightTee] .
DoubleLongLeftArrow DoubleUpDownArrow
\[DoubleLongLeftArrow]
Alias: , <== ,. Infix arrow operator. x v y is by default interpreted as DoubleLongLeftArrow[x, y].
page 1006. See also: \[DoubleLeftArrow] , \[LongLeftArrow] , \[DoubleLongRightArrow] .
1365
See
\[DoubleLongLeftRightArrow]
Alias: , <==> ,. Infix arrow operator. x w y is by default interpreted as DoubleLongLeftRightArrow[x, y].
page 1006. See also: \[DoubleLeftRightArrow] , \[LongLeftRightArrow] , \[RightArrowLeftArrow] ,
\[LeftArrowRightArrow] .
\[DoubleLongRightArrow]
Alias: , ==> ,. Infix arrow operator. x x y is by default interpreted as DoubleLongRightArrow[x, y].
page 1006. See also: \[DoubleRightArrow] , \[LongRightArrow] , \[DoubleLongLeftArrow] .
See
\[DoublePrime]
Alias: , '' ,. Letter-like form. Used to indicate angles in seconds or distances in inches.
See also: \[Prime], \[ReverseDoublePrime] .
See
\[DoubleRightArrow]
Alias: , => ,. Infix arrow operator. x y is by default interpreted as DoubleRightArrow[x, y]. Used in
mathematics to indicate various strong forms of convergence. Also used to indicate algebraic field extensions.
Not the same as \[Implies]. Extensible character. See page 1006. See also: \[DoubleLongRightArrow] ,
\[RightArrow], \[DoubleLeftArrow] .
\[DoubleRightTee]
Infix operator. x ) y is by default interpreted as DoubleRightTee[x, y]. x ) y ) z groups as x ) (y ) z).
Used in mathematics to indicate various strong forms of logical implicationoften tautological implication. In
prefix form, used to indicate a tautology. See pages 1001 and 1007. See also: \[RightTee], \[DoubleLeftTee] .
\[DoubleStruckA] \[DoubleStruckZ]
Aliases: , dsa , through , dsz ,. Letters. Treated as distinct characters rather than style modifications of ordinary
letters. Contiguous character codes from the private Unicode character range are used, even though a few
double-struck characters are included in ordinary Unicode. See page 993. See also: \[DoubleStruckCapitalA] ,
\[GothicA], \[ScriptA], etc.
\[DoubleStruckCapitalA] \[DoubleStruckCapitalZ]
Aliases: , dsA , through , dsZ ,. Letters. Treated as distinct characters rather than style modifications of ordinary
letters. , , , , , are used respectively to denote the sets of natural numbers, integers, rationals, reals,
complex numbers and quaternions. Contiguous character codes from the private Unicode character range are
used, even though a few capital double-struck characters are included in ordinary Unicode. See page 993. See
also: \[GothicCapitalA] , \[ScriptCapitalA] , etc.
\[DoubleUpArrow]
Infix arrow operator. x y y is by default interpreted as DoubleUpArrow[x, y].
page 1006. See also: \[UpArrow], \[DoubleDownArrow] .
Extensible character.
See
\[DoubleUpDownArrow]
Infix arrow operator. x z y is by default interpreted as DoubleUpDownArrow[x, y]. Extensible character.
page 1006. See also: \[UpDownArrow], \[UpArrowDownArrow] , \[DownArrowUpArrow] .
See
1366
DoubleVerticalBar DownRightTeeVector
\[DoubleVerticalBar]
Alias: , || ,. Infix operator. x 4 y is by default interpreted as DoubleVerticalBar[x, y]. Used in
mathematics to indicate that x exactly divides y. Used in geometry to mean parallel to. Not the same as
\[LeftDoubleBracketingBar] , \[RightDoubleBracketingBar] . , || , is the alias for \[Or]. The alias for
\[DoubleVerticalBar] has a space at the beginning. See page 1005. See also: \[VerticalBar],
\[VerticalSeparator] , \[NotDoubleVerticalBar] .
\[DownArrow]
Infix arrow operator. x c y is by default interpreted as DownArrow[x, y]. Used to indicate monotonic decrease
to a limit. Sometimes used for logical nor. Sometimes used in prefix form to indicate the closure of a set.
Extensible character. See page 1006. See also: \[DownTeeArrow], \[DownArrowBar], \[DoubleDownArrow] ,
\[LeftDownVector] , \[UpArrow].
'
\[DownArrowBar]
Infix arrow operator. x y is by default interpreted as DownArrowBar[x, y]. Sometimes used as an indicator of
depth. Extensible character. See page 1006. See also: \[DownTeeArrow], \[DownArrow],
\[LeftDownVectorBar] , \[UpArrowBar].
\[DownArrowUpArrow]
Infix arrow operator. x y is by default interpreted as DownArrowUpArrow[x, y]. Extensible character. See
page 1006. See also: \[UpDownArrow] , \[DoubleUpDownArrow] , \[UpArrowDownArrow] , \[UpEquilibrium] .
\[DownBreve]
Alias: , dbv ,. Letter-like form.
\[Breve], \[Cap].
See also:
\[DownExclamation]
Alias: , d! ,. Letter-like form.
\[DownQuestion] .
Used in Spanish.
\[DownLeftRightVector]
Infix arrow-like operator. x y is by default interpreted as DownLeftRightVector[x, y]. Extensible character.
See page 1007. See also: \[LeftRightVector] , \[Equilibrium] , \[RightUpDownVector] .
\[DownLeftTeeVector]
Infix arrow-like operator. x y is by default interpreted as DownLeftTeeVector[x, y].
See page 1007. See also: \[LeftTeeVector], \[LeftVectorBar] .
Extensible character.
\[DownLeftVector]
Infix arrow-like operator. x y is by default interpreted as DownLeftVector[x, y]. Extensible character.
page 1007. See also: \[LeftVector], \[LeftTeeVector] , \[LeftArrow], \[LeftUpVector].
\[DownLeftVectorBar]
Infix arrow-like operator. x
y is by default interpreted as DownLeftVectorBar[x, y].
See page 1007. See also: \[LeftVectorBar], \[LeftTeeVector] .
Extensible character.
\[DownQuestion]
Alias: , d? ,. Letter-like form.
\[DownExclamation] .
See
Used in Spanish.
\[DownRightTeeVector]
Infix arrow-like operator. x ! y is by default interpreted as DownRightTeeVector[x, y].
See page 1007. See also: \[RightTeeVector] , \[RightVectorBar] .
Extensible character.
DownRightVector EmptyCircle
1367
\[DownRightVector]
Infix arrow-like operator. x " y is by default interpreted as DownRightVector[x, y]. Extensible character.
page 1007. See also: \[RightVector], \[RightTeeVector] , \[RightArrow], \[RightUpVector] .
<
\[DownRightVectorBar]
Infix arrow-like operator. x # y is by default interpreted as DownRightVectorBar[x, y].
See page 1007. See also: \[RightVectorBar] , \[RightTeeVector] .
Letter.
See
\[EDoubleDot]
Included in ISO Latin-1.
Letter.
Letter.
\[EGrave]
See also: \[CapitalEGrave].
\[EHat]
Alias: , e^ ,.
\[ECup]
Alias: , e` ,.
\[EBar]
e`
See
\[EAcute]
See also:
\[DownTeeArrow]
Alias: , e' ,.
Extensible character.
\[DownTee]
Alias: , dT ,. Infix operator. x 0 y is by default interpreted as DownTee[x, y].
\[UpTee], \[RightTee], \[DownTeeArrow] .
See
\[Element]
Alias: , el ,. Infix operator with built-in evaluation rules. x y is by default interpreted as Element[x, y].
Not the same as \[Epsilon]. See pages 191, 1001 and 1004. See also: \[NotElement], \[ReverseElement] ,
\[Euro].
\[Ellipsis]
Alias: , ... ,. Letter-like form. Used to indicate omitted elements in a row of a matrix. \[Ellipsis] on its
own will act as a symbol. See pages 996 and 997. See also: \[CenterEllipsis] , \[VerticalEllipsis] ,
\[AscendingEllipsis] , \[HorizontalLine] , \[LeftSkeleton] , \[RawDot].
\[EmptyCircle]
Alias: , eci ,. Letter-like form. Not the same as the infix operator \[SmallCircle] .
\[EmptySmallCircle] , \[FilledCircle] , \[Degree].
See also:
EmptyDiamond Equilibrium
1368
\[EmptyDiamond]
Letter-like form.
\[EmptyDownTriangle]
Letter-like form. Not the same as \[Del]. See page 995. See also: \[EmptyUpTriangle] ,
\[FilledDownTriangle] , \[FilledUpTriangle] , \[LeftTriangle] , \[NotLeftTriangle] , \[NotRightTriangle] ,
\[RightTriangle] .
\[EmptyRectangle]
Letter-like form.
\[EmptySet]
Alias: , es ,.
Letter-like form.
\[EmptySmallCircle]
Alias: , esci ,. Letter-like form. Not the same as the infix operator \[SmallCircle] . Used as an overscript to
add ring diacritical marks. See page 995. See also: \[FilledSmallCircle] , \[Degree], \[ARing], \[Angstrom].
\[EmptySmallSquare]
Alias: , essq ,. Letter-like form. Not the same as the operator \[Square].
See page 995. See also: \[EmptySquare] , \[FilledSmallSquare] .
\[EmptySquare]
Alias: , esq ,. Letter-like form. Not the same as the operator \[Square]. Not the same as \[Placeholder].
See page 995. See also: \[FilledSquare] , \[GraySquare], \[DottedSquare] , \[EmptyRectangle] .
\[EmptyUpTriangle]
Letter-like form. Used in geometry to indicate a triangle, as in the symbol 1ABC. Not the same as
\[CapitalDelta] . See pages 995 and 996. See also: \[FilledUpTriangle] , \[EmptyDownTriangle] ,
\[RightTriangle] , \[Angle].
\[EnterKey]
Alias: , ent ,. Letter-like form.
textual input. See page 1009.
\[Epsilon]
Aliases: , e ,, , epsilon ,. Greek letter. Not the same as \[Element].
\[CurlyEpsilon] , \[CapitalEpsilon] , \[Eta], \[Euro].
See also:
\[Equal]
Alias: , == ,. Infix operator with built-in evaluation rules. x y is by default interpreted as Equal[x, y] or
x == y. \[Equal] is drawn longer than \[RawEqual]. See page 1003. See also: \[LongEqual], \[NotEqual],
\[Congruent], \[Rule].
\[EqualTilde]
Alias: , =~ ,. Infix similarity operator.
See also: \[NotEqualTilde] .
\[Equilibrium]
Alias: , equi ,. Infix arrow-like operator. x
y is by default interpreted as Equilibrium[x, y]. Used in
chemistry to represent a reversible reaction. Extensible character. See pages 191 and 1007. See also:
\[ReverseEquilibrium] , \[RightArrowLeftArrow] , \[LeftRightArrow] , \[LeftRightVector] , \[UpEquilibrium] .
ErrorIndicator FilledSmallCircle
1369
\[ErrorIndicator]
Uninterpretable element. Generated to indicate the position of a syntax error in messages produced by functions
like Get and ToExpression. Shown as ^^^ in OutputForm. \[ErrorIndicator] indicates the presence of a
syntax error, and so by default generates an error if you try to interpret it. See also: \[LeftSkeleton] .
\[EscapeKey]
Alias: , esc ,. Letter-like form. Representation of the escape key on a keyboard. Used in describing how to
type aliases for special characters in Mathematica. , esc , is the alias for \[AliasIndicator] . The alias for
\[EscapeKey] has a space at the beginning. See page 1009. See also: \[AliasIndicator] , \[RawEscape],
\[ReturnKey], \[ControlKey], \[CommandKey].
\[Eta]
Aliases: , et ,, , eta ,, , h ,. Greek letter.
See also: \[CapitalEta], \[Epsilon].
\[Eth]
Alias: , d- ,. Letter. Included in ISO Latin-1.
\[CapitalEth], \[Thorn], \[PartialD].
See also:
\[Exists]
Alias: , ex ,. Compound operator.
\[NotExists].
\[Euro]
Letter-like form.
\[Sterling].
See also:
\[ExponentialE]
Alias: , ee ,. Letter-like form with built-in value. is interpreted by default as the symbol E, representing the
exponential constant. See pages 988 and 994. See also: \[DifferentialD] , \[ImaginaryI] .
\[FilledCircle]
Alias: , fci ,. Letter-like form. Used as a dingbat. See page 995.
\[FilledSmallCircle] , \[SmallCircle], \[EmptyCircle].
\[FilledDiamond]
Letter-like form.
\[FilledDownTriangle]
Letter-like form. See page 995. See also: \[EmptyDownTriangle] , \[EmptyUpTriangle] , \[FilledUpTriangle] ,
\[LeftTriangle], \[NotLeftTriangle] , \[NotRightTriangle] , \[RightTriangle] .
\[FilledRectangle]
Letter-like form. Used in mathematics to indicate the end of a proof.
\[EmptyRectangle] .
See also:
\[FilledSmallCircle]
Alias: , fsci ,. Letter-like form.
\[EmptySmallCircle] .
Used as a dingbat.
1370
\[FilledSmallSquare]
Alias: , fssq ,. Letter-like form. Used as a dingbat. Not the same as \[SelectionPlaceholder] .
page 995. See also: \[FilledSquare] , \[EmptySmallSquare] , \[Square].
See
\[FilledSquare]
Alias: , fsq ,. Letter-like form. Used as a dingbat. Not the same as \[SelectionPlaceholder] . See page 995.
See also: \[FilledSmallSquare] , \[EmptySquare] , \[Square], \[GraySquare], \[FilledRectangle] .
\[FilledUpTriangle]
Letter-like form. See page 995. See also: \[EmptyDownTriangle] , \[EmptyUpTriangle] ,
\[FilledDownTriangle] , \[LeftTriangle] , \[NotLeftTriangle] , \[NotRightTriangle] , \[RightTriangle] .
\[FilledVerySmallSquare]
Alias: , fvssq ,.
\[Square].
Letter-like form.
Used as a dingbat.
\[FinalSigma]
Alias: , fs ,. Greek letter. Used in written Greek when occurs at the end of a word.
technical notation. Not the same as \[Stigma]. See page 990. See also: \[Sigma].
\[FivePointedStar]
Alias: , *5 ,. Letter-like form. Not the same as the operator \[Star].
\[SixPointedStar] , \[Star], \[RawStar].
See also:
\[Gamma]
Aliases: , g ,, , gamma ,. Greek letter. Used in TraditionalForm for EulerGamma and StieltjesGamma.
pages 175 and 990. See also: \[DoubledGamma] , \[CapitalGamma] , \[Digamma].
See
\[Gimel]
Alias: , gi ,. Hebrew letter. Used occasionally in pure mathematics in the theory of transfinite cardinals.
page 993. See also: \[Aleph].
See
\[FreakedSmiley]
Alias: , :-@ ,. Letter-like form.
\[WarningSign] .
See also:
\[ForAll]
Alias: , fa ,. Compound operator.
\[Exists], \[Not].
\[Flat]
Letter-like form. Used to denote musical notes.
also: \[Sharp], \[Natural].
See
\[GothicA] \[GothicZ]
Aliases: , goa , through , goz ,. Letters. Treated as distinct characters rather than style modifications of ordinary
letters. Used in pure mathematics. Contiguous character codes from the private Unicode character range are
used, even though a few gothic characters are included in ordinary Unicode. See page 993. See also:
\[GothicCapitalA] , \[ScriptA], \[DoubleStruckA] , etc.
1371
\[GothicCapitalA] \[GothicCapitalZ]
Aliases: , goA , through , goZ ,. Letters. Treated as distinct characters rather than style modifications of ordinary
letters. is used to denote imaginary part; X is used to denote real part. Used in pure mathematics and theory
of computation. Contiguous character codes from the private Unicode character range are used, even though a
few capital gothic characters are included in ordinary Unicode. See page 993. See also: \[GothicA],
\[ScriptCapitalA] , \[DoubleStruckCapitalA] , etc.
\[GrayCircle]
Alias: , gci ,. Letter-like form. Used as a dingbat. Generated internally by Mathematica, rather than being an
explicit font character. See page 995. See also: \[FilledCircle] , \[GraySquare].
\[GraySquare]
Alias: , gsq ,. Letter-like form. Used as a dingbat. Generated internally by Mathematica, rather than being an
explicit font character. See page 995. See also: \[FilledSquare] , \[EmptySquare] .
\[GreaterEqual]
Alias: , >= ,. Infix operator with built-in evaluation rules. x y is by default interpreted as GreaterEqual[x, y].
See page 1004. See also: \[GreaterSlantEqual] , \[GreaterFullEqual] , \[NotGreaterEqual] .
\[GreaterEqualLess]
Infix ordering operator.
\[LessEqualGreater] .
See also:
See also:
\[GreaterFullEqual]
Infix ordering operator. x 4 y is by default interpreted as GreaterFullEqual[x, y].
\[GreaterEqual], \[GreaterSlantEqual] , \[NotGreaterFullEqual] .
\[GreaterGreater]
Infix ordering operator. x y is by default interpreted as GreaterGreater[x, y]. Not the same as
\[RightGuillemet] . See pages 191 and 1004. See also: \[NestedGreaterGreater] , \[NotGreaterGreater] ,
\[NotNestedGreaterGreater] .
\[GreaterLess]
Infix ordering operator. x 5 y is by default interpreted as GreaterLess[x, y].
\[GreaterEqualLess] , \[NotGreaterLess] .
See also:
\[GreaterSlantEqual]
Alias: , >/ ,. Infix operator with built-in evaluation rules. x y is by default interpreted as GreaterEqual[x, y].
See page 1004. See also: \[GreaterEqual] , \[GreaterFullEqual] , \[NotGreaterSlantEqual] .
\[GreaterTilde]
Alias: , >~ ,. Infix ordering operator. x y is by default interpreted as GreaterTilde[x, y].
and 1004. See also: \[NotGreaterTilde] .
\[Hacek]
Alias: , hc ,. Letter-like form. Used primarily in an overscript position. Used as a diacritical mark in Eastern
HappySmiley ImaginaryJ
1372
\[HappySmiley]
Aliases: , :) ,, , :-) ,. Letter-like form.
\[FreakedSmiley] , \[Wolf].
\[HBar]
Alias: , hb ,. Letter-like form. Used in physics to denote Plancks constant divided by ; sometimes called
Diracs constant. See pages 192 and 994. See also: \[Angstrom].
\[HeartSuit]
Letter-like form.
\[HorizontalLine]
Alias: , hline ,. Letter-like form. Extensible character. Thickness can be adjusted using the SpanThickness
option in StyleBox. See page 997. See also: \[Dash], \[LongDash], \[VerticalSeparator] .
\[HumpDownHump]
Infix similarity operator. x 6 y is by default interpreted as HumpDownHump[x, y].
equivalence. See page 1003. See also: \[HumpEqual], \[NotHumpDownHump] .
\[HumpEqual]
Alias: , h= ,. Infix similarity operator. x 7 y is by default interpreted as HumpEqual[x, y]. Sometimes used to
mean approximately equal and sometimes difference between. See page 1003. See also: \[HumpDownHump] ,
\[TildeEqual], \[NotHumpEqual] .
\[IAcute]
Alias: , i' ,.
Letter.
Letter.
Letter.
\[IHat]
Alias: , i^ ,.
\[IGrave]
Alias: , i` ,.
\[IDoubleDot]
Alias: , i" ,. Letter.
\[ADoubleDot].
\[ICup]
Alias: , iu ,. Letter. Included in ISO Latin-2.
See also: \[CapitalICup].
\[ImaginaryI]
Alias: , ii ,. Letter-like form with built-in value. is interpreted by default as the symbol I, representing
See pages 988 and 994. See also: \[ImaginaryJ] , \[ExponentialE] .
.
\[ImaginaryJ]
Alias: , jj ,. Letter-like form with built-in value. " is interpreted by default as the symbol I, representing
Used in electrical engineering. See pages 988 and 994. See also: \[ImaginaryI], \[ExponentialE].
.
Implies Kappa
1373
\[Implies]
Alias: , => ,. Infix operator with built-in evaluation rules. x y is by default interpreted as Implies[x, y].
x y z groups as x (y z). Not the same as \[DoubleRightArrow] . \[DoubleRightArrow] is
extensible; \[Implies] is not. See pages 1001 and 1006. See also: \[RoundImplies] , \[SuchThat],
\[RightArrow], \[Rule].
\[IndentingNewLine]
Alias: , nl ,. Raw operator. Forces a line break in an expression, maintaining the correct indenting level based on
the environment of the line break. See pages 460 and 1008. See also: \[NewLine], \[NoBreak].
\[Infinity]
Alias: , inf ,.
page 994.
See
\[Integral]
Alias: , int ,.
f 7 x is by default interpreted as
Integrate[f, x]. a f 7 x is by default interpreted as Integral[f, {x, a, b}]. a and b must appear as a
subscript and superscript, respectively. a b 7 x is by default output as (a b) 7 x whenever is an
operator with a precedence lower than [. Note the use of 7, entered as , dd , or \[DifferentialD] , rather than
ordinary d. See page 1000. See also: \[ContourIntegral] .
\[Intersection]
Alias: , inter ,. Infix operator with built-in evaluation rules. x y is by default interpreted as
Intersection[x, y]. The character V is sometimes called cap; but see also \[Cap]. , int , gives \[Integral]
not \[Intersection] . See page 1002. See also: \[Union], \[SquareIntersection] , \[Cap], \[Wedge].
\[InvisibleApplication]
Alias: , @ ,. Structural element with built-in meaning. \[InvisibleApplication] is by default not visible on
display, but is interpreted as function application. f H @ H x is interpreted as f @ x or f[x].
\[InvisibleApplication] can be used as an invisible separator between functions or between functions and
their arguments. See page 1008. See also: \[InvisibleSpace] , \[InvisibleComma] , \[RawAt].
\[InvisibleComma]
Alias: , , ,. Structural element with built-in meaning. \[InvisibleComma] is by default not visible on display, but
is interpreted on input as an ordinary comma. \[InvisibleComma] can be used as an invisible separator between
indices, as in Mij . See page 1008. See also: \[AlignmentMarker] , \[Null], \[InvisibleSpace] , \[RawComma].
\[InvisibleSpace]
Alias: , is ,. Spacing character. \[InvisibleSpace] is by default not visible on display, but is interpreted on
input as an ordinary space. \[InvisibleSpace] can be used as an invisible separator between variables that are
being multiplied together, as in xy. See pages 454 and 1008. See also: \[AlignmentMarker] , \[Null],
\[VeryThinSpace], \[RawSpace].
\[Iota]
Aliases: , i ,, , iota ,. Greek letter. Not commonly used. Used in set theory to indicate an explicitly
constructible set. See page 990. See also: \[CapitalIota] , \[DotlessI].
\[Kappa]
Aliases: , k ,, , kappa ,.
Greek letter.
KernelIcon LeftDoubleBracket
1374
\[KernelIcon]
Letter-like form.
See page 995.
\[Koppa]
Aliases: , ko ,, , koppa ,. Special Greek letter. Analogous to English q. Appeared between and in early
Greek alphabet; used for Greek numeral 90. See page 990. See also: \[CapitalKoppa] , \[Digamma], \[Stigma],
\[Sampi].
\[Lambda]
Aliases: , l ,, , lambda ,. Greek letter.
See also: \[CapitalLambda] .
\[LeftAngleBracket]
Alias: , < ,. Matchfix operator. / x 0 is by default interpreted as AngleBracket[x] . Used in the form /x0 to
indicate expected or average value. Called bra in quantum mechanics. Used in the form /x, y0 to indicate
various forms of inner product. Used in the form /x, y, . . . 0 to denote an ordered set of objects. Not the same
as \[RawLess]. Extensible character; grows by default to limited size. See pages 191 and 1002. See also:
\[RightAngleBracket] , \[LeftFloor], \[LeftCeiling].
\[LeftArrow]
Alias: , <- ,. Infix arrow operator. x a y is by default interpreted as LeftArrow[x, y]. Sometimes used in
computer science to indicate assignment: x gets value y. Extensible character. See page 1006. See also:
\[LongLeftArrow] , \[ShortLeftArrow] , \[DoubleLeftArrow] , \[LeftTeeArrow], \[LeftArrowBar],
\[LowerLeftArrow] , \[LeftVector], \[LeftTriangle] , \[RightArrow] .
\[LeftArrowBar]
Infix arrow operator. x % y is by default interpreted as LeftArrowBar[x, y]. Sometimes used to indicate a
backtab. Extensible character. See page 1006. See also: \[LeftTeeArrow] , \[LeftVectorBar] ,
\[DownArrowBar] , \[RightArrowBar] .
\[LeftArrowRightArrow]
Infix arrow operator. x & y is by default interpreted as LeftArrowRightArrow[x, y]. Used in mathematics to
indicate logical equivalence. Sometimes used to indicate chemical equilibrium. Extensible character. See
page 1006. See also: \[RightArrowLeftArrow] , \[LeftRightArrow] , \[DoubleLeftRightArrow] , \[Equilibrium] ,
\[UpArrowDownArrow] .
\[LeftBracketingBar]
Alias: , l| ,. Matchfix operator. @ x A is by default interpreted as BracketingBar[x] . Used in mathematics to
indicate absolute value (Abs), determinant (Det), and other notions of evaluating size or magnitude. Not the same
as \[VerticalBar] . Drawn in monospaced fonts with a small left-pointing tee to indicate direction. Extensible
character. See page 1002. See also: \[LeftDoubleBracketingBar] , \[LeftTee].
&
\[LeftCeiling]
Alias: , lc ,. Matchfix operator with built-in evaluation rules. F x G is by default interpreted as Ceiling[x].
Extensible character. See page 1002. See also: \[RightCeiling], \[LeftFloor], \[LeftAngleBracket] .
\[LeftDoubleBracket]
Alias: , [[ ,. Compound operator with built-in evaluation rules. m+i,j, . . . , is by default interpreted as
Part[m, i, j, . . . ]. Sometimes used in mathematics to indicate a class of algebraic objects with certain variables
or extensions. Extensible character; grows by default to limited size. See page 1002. See also:
\[RawLeftBracket] , \[LeftDoubleBracketingBar] .
LeftDoubleBracketingBar LeftSkeleton
1375
\[LeftDoubleBracketingBar]
Alias: , l|| ,. Matchfix operator. B x C is by default interpreted as DoubleBracketingBar[x] . Used in
mathematics to indicate taking a norm. Sometimes used for determinant. Sometimes used to indicate a matrix.
Not the same as \[DoubleVerticalBar] . Drawn in monospaced fonts with a small left-pointing tee to indicate
direction. Extensible character. See page 1002. See also: \[LeftBracketingBar] .
\[LeftDownTeeVector]
Infix arrow-like operator. x ' y is by default interpreted as LeftDownTeeVector[x, y]. Extensible character.
See page 1007. See also: \[RightDownTeeVector] , \[LeftDownVectorBar] , \[DownTeeArrow] ,
\[LeftUpTeeVector] .
\[LeftDownVector]
Infix arrow-like operator. x ( y is by default interpreted as LeftDownVector[x, y]. Extensible character.
page 1007. See also: \[RightDownVector] , \[LeftDownTeeVector] , \[DownArrow], \[UpEquilibrium] ,
\[LeftUpVector].
See
\[LeftDownVectorBar]
Infix arrow-like operator. x ) y is by default interpreted as LeftDownVectorBar[x, y]. Extensible character.
See page 1007. See also: \[RightDownVectorBar] , \[LeftDownTeeVector] , \[DownArrowBar] ,
\[LeftUpVectorBar] .
\[LeftFloor]
Alias: , lf ,. Matchfix operator with built-in evaluation rules. D x E is by default interpreted as Floor[x].
Extensible character. See page 1002. See also: \[RightFloor], \[LeftCeiling], \[LeftAngleBracket] .
\[LeftGuillemet]
Alias: , g<< ,. Letter-like form. Used as opening quotation marks in languages such as Spanish. Not the same
as \[LessLess]. Not the same as \[LeftSkeleton] . Guillemet is sometimes misspelled as guillemot. See
page 996. See also: \[RightGuillemet] .
\[LeftModified]
Alias: , [ ,. Letter-like form. Used in documenting control and command characters.
key\[LeftModified]char\[RightModified] is used to indicate that char should be typed while key is being
pressed. Not the same as \[RawLeftBracket] . See page 1009. See also: \[ControlKey], \[CommandKey] ,
\[RightModified].
\[LeftRightArrow]
Alias: , <-> ,. Infix arrow operator. x j y is by default interpreted as LeftRightArrow[x, y]. Used in
mathematics for various notions of equivalence and equality. Extensible character. See pages 191 and 1006.
also: \[LongLeftRightArrow] , \[DoubleLeftRightArrow] , \[LeftArrowRightArrow] , \[LeftRightVector] ,
\[Equilibrium], \[UpDownArrow].
See
\[LeftRightVector]
Infix arrow-like operator. x * y is by default interpreted as LeftRightVector[x, y]. Extensible character. See
page 1007. See also: \[DownLeftRightVector] , \[Equilibrium], \[ReverseEquilibrium] , \[LeftRightArrow] ,
\[RightArrowLeftArrow] , \[RightUpDownVector] .
\[LeftSkeleton]
Uninterpretable element. : n ; is used on output to indicate n omitted pieces in an expression obtained from
Short or Shallow. \[LeftSkeleton] indicates the presence of missing information, and so by default generates
an error if you try to interpret it. Not the same as \[LeftGuillemet] . See page 1009. See also:
\[RightSkeleton], \[SkeletonIndicator] , \[Ellipsis], \[ErrorIndicator] .
LeftTee LeftVectorBar
1376
\[LeftTee]
Alias: , lT ,. Infix operator. x * y is by default interpreted as LeftTee[x, y]. x * y * z groups as (x * y) * z.
Used in mathematics to indicate the lack of logical implication or proof. See pages 1001 and 1007. See also:
\[DoubleLeftTee] , \[LeftTeeArrow] , \[LeftTeeVector], \[RightTee], \[DownTee], \[LeftBracketingBar] .
\[LeftTeeArrow]
Infix arrow operator. x + y is by default interpreted as LeftTeeArrow[x, y]. Extensible character.
page 1006. See also: \[LeftTeeVector] , \[LeftTee], \[RightTeeArrow] , \[DownTeeArrow] .
See
\[LeftTeeVector]
Infix arrow-like operator. x , y is by default interpreted as LeftTeeVector[x, y]. Extensible character.
page 1007. See also: \[DownLeftTeeVector] , \[LeftVectorBar] , \[LeftVector] , \[LeftTeeArrow] .
See
\[LeftTriangle]
Infix ordering operator. x 8 y is by default interpreted as LeftTriangle[x, y]. Used in pure mathematics to
mean normal subgroup of. See page 1005. See also: \[LeftTriangleEqual] , \[LeftTriangleBar] ,
\[LeftArrow], \[NotLeftTriangle] , \[RightTriangle] , \[EmptyUpTriangle] , \[FilledUpTriangle] .
\[LeftTriangleBar]
Infix ordering operator. x y is by default interpreted as LeftTriangleBar[x, y]. See page 1005.
\[LeftTriangle] , \[LeftTriangleEqual] , \[LeftArrowBar] , \[NotLeftTriangleBar] .
See also:
\[LeftTriangleEqual]
Infix ordering operator. x 9 y is by default interpreted as LeftTriangleEqual[x, y]. See page 1005. See also:
\[LeftTriangle] , \[LeftTriangleBar] , \[PrecedesEqual] , \[NotLeftTriangleEqual] , \[RightTriangleEqual] .
A
E
?
I
1
\[LeftUpDownVector]
Infix arrow-like operator. x - y is by default interpreted as LeftUpDownVector[x, y]. Extensible character. See
page 1007. See also: \[RightUpDownVector] , \[UpEquilibrium] , \[UpArrowDownArrow] , \[LeftRightVector] .
\[LeftUpTeeVector]
Infix arrow-like operator. x . y is by default interpreted as LeftUpTeeVector[x, y]. Extensible character.
page 1007. See also: \[RightUpTeeVector] , \[LeftUpVectorBar] , \[UpTeeArrow], \[LeftDownTeeVector] .
\[LeftUpVector]
Infix arrow-like operator. x / y is by default interpreted as LeftUpVector[x, y]. Extensible character.
page 1007. See also: \[RightUpVector] , \[LeftUpTeeVector] , \[UpArrow], \[UpEquilibrium] ,
\[LeftDownVector] .
See
\[LeftUpVectorBar]
Infix arrow-like operator. x 0 y is by default interpreted as LeftUpVectorBar[x, y]. Extensible character.
page 1007. See also: \[RightUpVectorBar] , \[LeftUpTeeVector] , \[UpArrowBar], \[LeftDownVectorBar] .
See
\[LeftVector]
Infix arrow-like operator. x 1 y is by default interpreted as LeftVector[x, y]. Extensible character.
page 1007. See also: \[DownLeftVector] , \[LeftTeeVector], \[LeftVectorBar] , \[LeftArrow],
\[RightVector] , \[LeftUpVector] .
See
See
\[LeftVectorBar]
Infix arrow-like operator. x 2 y is by default interpreted as LeftVectorBar[x, y]. Extensible character.
page 1007. See also: \[DownLeftVectorBar] , \[LeftTeeVector] , \[LeftArrowBar] .
See
LessEqual LongRightArrow
1377
\[LessEqual]
Alias: , <= ,. Infix operator with built-in evaluation rules. x y is by default interpreted as LessEqual[x, y].
See page 1004. See also: \[LessSlantEqual] , \[LessFullEqual], \[NotLessEqual] .
\[LessEqualGreater]
Infix ordering operator.
\[GreaterEqualLess] .
See also:
\[LessGreater]
Infix ordering operator. x < y is by default interpreted as LessGreater[x, y].
\[LessEqualGreater] , \[NotLessGreater] .
See also:
\[LessFullEqual]
Infix ordering operator. x ; y is by default interpreted as LessFullEqual[x, y].
\[LessEqual], \[LessSlantEqual] , \[NotLessFullEqual] .
See also:
\[LessLess]
Infix ordering operator. x = y is by default interpreted as LessLess[x, y]. Not the same as \[LeftGuillemet].
See page 1004. See also: \[NestedLessLess] , \[NotLessLess], \[NotNestedLessLess] .
\[LessSlantEqual]
Alias: , </ ,. Infix operator with built-in evaluation rules. x ( y is by default interpreted as LessEqual[x, y].
See page 1004. See also: \[LessEqual], \[LessFullEqual] , \[NotLessSlantEqual] .
\[LessTilde]
Alias: , <~ ,. Infix ordering operator.
also: \[NotLessTilde] .
Letter-like form.
\[LongEqual]
Infix operator with built-in evaluation rules. x y is by default interpreted as Equal[x, y] or x == y.
\[LongEqual] is drawn longer than \[RawEqual]. Used as an alternative to \[Equal]. See page 1003.
also: \[Equal], \[NotEqual], \[Congruent].
See
\[LongDash]
Alias: , -- ,.
\[LightBulb]
Letter-like form.
See
\[LongLeftArrow]
Alias: , <-- ,. Infix arrow operator. x { y is by default interpreted as LongLeftArrow[x, y]. See page 1006.
See also: \[LeftArrow], \[DoubleLongLeftArrow] , \[LongRightArrow] , \[LongLeftRightArrow] .
\[LongLeftRightArrow]
Alias: , <--> ,. Infix arrow operator. x | y is by default interpreted as LongLeftRightArrow[x, y].
page 1006. See also: \[LeftRightArrow] , \[DoubleLongLeftRightArrow] , \[LeftArrowRightArrow] ,
\[Equilibrium].
See
\[LongRightArrow]
Alias: , --> ,. Infix arrow operator.
\[Rule]. See pages 191 and 1006.
\[LongLeftRightArrow] .
LowerLeftArrow Natural
1378
\[LowerLeftArrow]
Infix arrow operator. x 3 y is by default interpreted as LowerLeftArrow[x, y]. Extensible character; grows by
default to limited size. See page 1006. See also: \[LeftArrow], \[UpperRightArrow] .
\[LowerRightArrow]
Infix arrow operator. x 4 y is by default interpreted as LowerRightArrow[x, y]. Extensible character; grows by
default to limited size. See page 1006. See also: \[RightArrow], \[UpperLeftArrow] .
\[LSlash]
Alias: , l/ ,.
Letter.
\[MathematicaIcon]
Alias: , math ,. Letter-like form. Icon typically used for Mathematica. Based on a stellated icosahedron.
icon is a trademark of Wolfram Research. See page 995. See also: \[KernelIcon].
<
This
\[MeasuredAngle]
Letter-like form. Used in geometry to indicate an angle, as in the symbol ABC.
\[Angle], \[SphericalAngle] , \[RightAngle] .
See also:
\[MediumSpace]
Alias: , ,. Spacing character. Width: 4/18 em. Interpreted by default just like an ordinary \[RawSpace].
Sometimes used in output as a separator between digits in numbers. See page 1008. See also: \[ThinSpace],
\[ThickSpace], \[NegativeMediumSpace] , \[NonBreakingSpace] , \[SpaceIndicator] .
\[Mho]
Alias: , mho ,. Letter-like form. Used to denote the inverse ohm unit of conductance. "Mho" is "ohm" spelled
backwards. Occasionally called agemo in pure mathematics. Used to denote characteristic subgroups, and in
set theory to denote functions of sets with special properties. See page 994. See also: \[CapitalOmega].
\[Micro]
Alias: , mi ,. Letter-like form. Used as a prefix in units to denote .
pages 192 and 994. See also: \[Angstrom].
\[MinusPlus]
Alias: , -+ ,. Prefix or infix operator. x is by default interpreted as MinusPlus[x].
interpreted as MinusPlus[x, y]. See page 1000. See also: \[PlusMinus].
x y is by default
\[Mu]
Aliases: , m ,, , mu ,. Greek letter. Used in TraditionalForm for MoebiusMu.
pages 175 and 990. See also: \[CapitalMu].
See
\[Nand]
Alias: , nand ,. Infix operator with built-in evaluation rules. x y is by default interpreted as Nand[x, y].
page 1001. See also: \[And], \[Not], \[Nor], \[VerticalBar].
See
See
\[Natural]
Letter-like form. Used to denote musical notes. Sometimes used in mathematical notation, often as an inverse of
numbering operations represented by \[Sharp]. See pages 192 and 996. See also: \[Flat], \[Sharp].
NegativeMediumSpace Nor
1379
\[NegativeMediumSpace]
Alias: , - ,. Negative spacing character. Used to bring characters on either side closer together.
em. Interpreted by default just like an ordinary \[RawSpace]. See page 1008. See also:
\[NegativeThinSpace] , \[NegativeThickSpace] , \[MediumSpace].
Width:
\[NegativeThickSpace]
Alias: , - ,. Negative spacing character. Used to bring characters on either side closer together.
em. Interpreted by default just like an ordinary \[RawSpace]. See page 1008. See also:
\[NegativeMediumSpace] , \[ThickSpace].
Width:
\[NegativeThinSpace]
Alias: , - ,. Negative spacing character. Used to bring characters on either side closer together.
em. Interpreted by default just like an ordinary \[RawSpace]. See page 1008. See also:
\[NegativeVeryThinSpace] , \[NegativeMediumSpace] , \[ThinSpace].
Width:
\[NegativeVeryThinSpace]
Alias: , - ,. Negative spacing character. Used to bring characters on either side closer together.
em. Interpreted by default just like an ordinary \[RawSpace]. See page 1008. See also:
\[NegativeThinSpace] , \[VeryThinSpace].
\[NestedGreaterGreater]
Infix ordering operator. x ? y is by default interpreted as NestedGreaterGreater[x, y].
also: \[GreaterGreater] , \[NotGreaterGreater] , \[NotNestedGreaterGreater] .
Width:
See
\[NestedLessLess]
Infix ordering operator. x y is by default interpreted as NestedLessLess[x, y]. Used to denote much less
than. Occasionally used in measure theory to denote absolutely continuous with respect to. See page 1004.
See also: \[LessLess], \[NotLessLess], \[NotNestedLessLess] .
\[NeutralSmiley]
Alias: , :-| ,.
Letter-like form.
\[NewLine]
Raw operator. Inserted whenever a raw newline is entered on the keyboard. Forces a line break in an
expression, fixing the indenting level at the time when the line break is inserted. \[NewLine] represents a
newline on any computer system, independent of the underlying character code used on that computer system.
See pages 460, 1008 and 1010. See also: \[IndentingNewLine] , \[RawReturn].
\[NoBreak]
Alias: , nb ,. Letter-like form. Used to indicate that no line break can occur at this position in an expression.
See pages 459, 460 and 1008. See also: \[NonBreakingSpace] , \[NewLine], \[Continuation] ,
\[AlignmentMarker] , \[Null], \[InvisibleSpace] .
\[NonBreakingSpace]
Alias: , nbs ,. Spacing character. Generates a space with the same width as \[RawSpace], but with no line break
allowed to occur on either side of it. See pages 459 and 1008. See also: \[NoBreak], \[InvisibleSpace] ,
\[NewLine].
\[Nor]
Alias: , nor ,. Infix operator with built-in evaluation rules.
page 1001. See also: \[Xor], \[Or], \[Not].
See
Not NotGreaterLess
1380
\[Not]
Aliases: , ! ,, , not ,. Prefix operator with built-in evaluation rules. x is by default interpreted as Not[x],
equivalent to !x. See page 1001. See also: \[RightTee], \[And], \[Or].
\[NotCongruent]
Alias: , !=== ,. Infix similarity operator.
See also: \[NotEqual], \[Congruent] .
\[NotCupCap]
x A y is by default interpreted as NotCupCap[x, y].
See also:
\[NotDoubleVerticalBar]
Alias: , !|| ,. Infix operator. x y is by default interpreted as NotDoubleVerticalBar[x, y]. Used in geometry
to mean not parallel to. See page 1005. See also: \[DoubleVerticalBar] , \[NotVerticalBar] , \[UpTee].
\[NotElement]
Alias: , !el ,. Infix set relation operator with built-in evaluation rules. x ^ y is by default interpreted as
NotElement[x, y]. See pages 191 and 1004. See also: \[Element], \[NotReverseElement] .
\[NotEqual]
Alias: , != ,. Infix operator with built-in evaluation rules. x y is by default interpreted as Unequal[x, y].
page 1003. See also: \[Equal], \[NotCongruent] , \[GreaterLess] .
\[NotEqualTilde]
Alias: , !=~ ,. Infix similarity operator.
See also: \[EqualTilde].
See
\[NotGreater]
Alias: , !> ,. Infix ordering operator. x C y is by default interpreted as NotGreater[x, y].
only for a totally ordered set. See page 1004. See also: \[RawGreater].
\[NotExists]
Alias: , !ex ,. Compound operator.
also: \[Exists], \[ForAll].
See
is equivalent to *
\[NotGreaterEqual]
Alias: , !>= ,. Infix ordering operator. x D y is by default interpreted as NotGreaterEqual[x, y]. See
page 1004. See also: \[GreaterEqual] , \[GreaterFullEqual] , \[GreaterSlantEqual] , \[NotGreaterFullEqual] ,
\[NotGreaterSlantEqual] .
\[NotGreaterFullEqual]
Infix ordering operator. x E y is by default interpreted as NotGreaterFullEqual[x, y]. See page 1004.
also: \[GreaterEqual], \[GreaterFullEqual] , \[GreaterSlantEqual] , \[NotGreaterEqual] ,
\[NotGreaterSlantEqual] .
\[NotGreaterGreater]
Infix ordering operator. x F y is by default interpreted as NotGreaterGreater[x, y].
\[GreaterGreater] , \[NestedGreaterGreater] , \[NotNestedGreaterGreater] .
See
See also:
\[NotGreaterLess]
Infix ordering operator.
\[GreaterLess] .
See also:
NotGreaterSlantEqual NotLessSlantEqual
1381
\[NotGreaterSlantEqual]
Alias: , !>/ ,. Infix ordering operator. x H y is by default interpreted as NotGreaterSlantEqual[x, y]. See
page 1004. See also: \[GreaterEqual], \[GreaterFullEqual] , \[GreaterSlantEqual] , \[NotGreaterEqual] ,
\[NotGreaterFullEqual] .
\[NotGreaterTilde]
Alias: , !>~ ,. Infix ordering operator. x I y is by default interpreted as NotGreaterTilde[x, y].
page 1004. See also: \[GreaterTilde].
\[NotHumpDownHump]
x J y is by default interpreted as NotHumpDownHump[x, y].
\[NotLeftTriangle]
Infix ordering operator. x L y is by default interpreted as NotLeftTriangle[x, y]. See page 1005.
\[NotLeftTriangleBar] , \[NotLeftTriangleEqual] , \[NotRightTriangle] , \[LeftTriangle] .
See also:
\[NotHumpEqual]
Alias: , !h= ,. Infix similarity operator.
See also: \[HumpEqual].
See
See also:
\[NotLeftTriangleBar]
Infix ordering operator. x M y is by default interpreted as NotLeftTriangleBar[x, y]. See page 1005.
also: \[NotLeftTriangle] , \[NotLeftTriangleEqual] , \[NotRightTriangleBar] , \[LeftTriangleBar] .
See
\[NotLeftTriangleEqual]
Infix ordering operator. x N y is by default interpreted as NotLeftTriangleEqual[x, y]. See page 1005.
also: \[NotLeftTriangle] , \[NotLeftTriangleBar] , \[NotRightTriangleEqual] , \[LeftTriangleEqual] .
\[NotLess]
Alias: , !< ,. Infix ordering operator. x O y is by default interpreted as NotLess[x, y].
only for a totally ordered set. See page 1004. See also: \[RawLess].
See
is equivalent to !
\[NotLessEqual]
Alias: , !<= ,. Infix ordering operator. x P y is by default interpreted as NotLessEqual[x, y]. See page 1004.
See also: \[LessEqual], \[LessFullEqual] , \[LessSlantEqual] , \[NotLessFullEqual] , \[NotLessSlantEqual] .
\[NotLessFullEqual]
Infix ordering operator. x Q y is by default interpreted as NotLessFullEqual[x, y]. See page 1004.
\[LessEqual], \[LessFullEqual] , \[LessSlantEqual] , \[NotLessEqual] , \[NotLessSlantEqual] .
\[NotLessGreater]
Infix ordering operator.
\[LessGreater].
See also:
\[NotLessLess]
Infix ordering operator. x S y is by default interpreted as NotLessLess[x, y].
\[LessLess], \[NestedLessLess] , \[NotNestedLessLess] .
See also:
See also:
\[NotLessSlantEqual]
Alias: , !</ ,. Infix ordering operator. x T y is by default interpreted as NotLessSlantEqual[x, y].
page 1004. See also: \[LessEqual], \[LessFullEqual] , \[LessSlantEqual] , \[NotLessEqual] ,
\[NotLessFullEqual] .
See
1382
NotLessTilde NotSquareSubsetEqual
\[NotLessTilde]
Alias: , !<~ ,. Infix ordering operator.
See also: \[LessTilde].
\[NotNestedGreaterGreater]
Infix ordering operator. x V y is by default interpreted as NotNestedGreaterGreater[x, y].
See also: \[GreaterGreater] , \[NestedGreaterGreater] , \[NotGreaterGreater] .
See also:
\[NotPrecedesSlantEqual]
See page 1005.
See also:
\[NotReverseElement]
Alias: , !mem ,. Infix set relation operator. x y is by default interpreted as NotReverseElement[x, y].
page 1004. See also: \[ReverseElement] , \[NotElement].
See
\[NotRightTriangle]
Infix ordering operator. x \ y is by default interpreted as NotRightTriangle[x, y]. See page 1005.
\[NotRightTriangleBar] , \[NotRightTriangleEqual] , \[NotLeftTriangle] , \[RightTriangle] .
See
\[NotPrecedesTilde]
Infix ordering operator. x [ y is by default interpreted as NotPrecedesTilde[x, y].
\[NotPrecedesEqual] , \[PrecedesTilde] .
See also:
See also:
\[NotPrecedesEqual]
Infix ordering operator. x Y y is by default interpreted as NotPrecedesEqual[x, y].
\[NotPrecedesSlantEqual] , \[NotPrecedesTilde] , \[PrecedesEqual].
\[NotPrecedes]
Infix ordering operator.
\[Precedes].
\[NotNestedLessLess]
Infix ordering operator. x W y is by default interpreted as NotNestedLessLess[x, y].
\[LessLess], \[NestedLessLess] , \[NotLessLess].
See also:
\[NotRightTriangleBar]
Infix ordering operator. x y is by default interpreted as NotRightTriangleBar[x, y]. See page 1005.
also: \[NotRightTriangle] , \[NotRightTriangleEqual] , \[NotLeftTriangleBar] , \[RightTriangleBar] .
See
\[NotRightTriangleEqual]
Infix ordering operator. x ] y is by default interpreted as NotRightTriangleEqual[x, y]. See page 1005.
also: \[NotRightTriangle] , \[NotRightTriangleBar] , \[NotLeftTriangleEqual] , \[RightTriangleEqual] .
\[NotSquareSubset]
Infix set relation operator. x ^ y is by default interpreted as NotSquareSubset[x, y].
\[NotSquareSubsetEqual] , \[SquareSubset].
See
See also:
\[NotSquareSubsetEqual]
Infix set relation operator. x _ y is by default interpreted as NotSquareSubsetEqual[x, y].
also: \[NotSquareSubset] , \[SquareSubsetEqual] .
See
NotSquareSuperset NotTildeFullEqual
\[NotSquareSuperset]
Infix set relation operator. x ` y is by default interpreted as NotSquareSuperset[x, y].
also: \[NotSquareSupersetEqual] , \[SquareSuperset] .
\[NotSubset]
Alias: , !sub ,. Infix set relation operator. x } y is by default interpreted as NotSubset[x, y].
See also: \[NotSubsetEqual] , \[Subset].
\[NotSubsetEqual]
Alias: , !sub= ,. Infix set relation operator. x b y is by default interpreted as NotSubsetEqual[x, y].
page 1004. See also: \[NotSubset], \[SubsetEqual] .
See also:
\[NotSuperset]
Alias: , !sup ,. Infix set relation operator. x g y is by default interpreted as NotSuperset[x, y].
See also: \[NotSupersetEqual] , \[Superset].
\[NotSupersetEqual]
Alias: , !sup= ,. Infix set relation operator. x h y is by default interpreted as NotSupersetEqual[x, y].
page 1004. See also: \[NotSuperset], \[SupersetEqual].
See
\[NotTildeEqual]
Alias: , !~= ,. Infix similarity operator. x j y is by default interpreted as NotTildeEqual[x, y].
See also: \[NotTildeFullEqual] , \[TildeEqual], \[TildeFullEqual] .
See
\[NotTilde]
Alias: , !~ ,. Infix similarity operator.
also: \[Tilde].
See
\[NotSucceedsTilde]
Infix ordering operator. x f y is by default interpreted as NotSucceedsTilde[x, y].
\[NotSucceedsEqual] , \[SucceedsTilde] .
See also:
\[NotSucceedsSlantEqual]
Infix ordering operator. x e y is by default interpreted as NotSucceedsSlantEqual[x, y].
also: \[NotSucceedsEqual] , \[SucceedsSlantEqual] .
See also:
\[NotSucceedsEqual]
Infix ordering operator. x d y is by default interpreted as NotSucceedsEqual[x, y].
\[NotSucceedsSlantEqual] , \[NotSucceedsTilde] , \[SucceedsSlantEqual] .
See
\[NotSucceeds]
Infix ordering operator. x c y is by default interpreted as NotSucceeds[x, y].
\[NotSucceedsEqual] , \[Succeeds].
See
\[NotSquareSupersetEqual]
Infix set relation operator. x a y is by default interpreted as NotSquareSupersetEqual[x, y].
See also: \[NotSquareSuperset] , \[SquareSupersetEqual] .
1383
\[NotTildeFullEqual]
Alias: , !~== ,. Infix similarity operator. x k y is by default interpreted as NotTildeFullEqual[x, y].
page 1003. See also: \[NotTildeEqual], \[NotCongruent] , \[TildeFullEqual] .
See
NotTildeTilde OSlash
1384
\[NotTildeTilde]
Alias: , !~~ ,. Infix similarity operator.
page 1003. See also: \[TildeTilde].
See
\[NotVerticalBar]
Alias: , !| ,. Infix operator. x y is by default interpreted as NotVerticalBar[x, y]. Used in mathematics to
mean x does not divide y. See page 1005. See also: \[VerticalBar], \[NotDoubleVerticalBar] .
\[NTilde]
Alias: , n~ ,.
Letter.
\[Nu]
Aliases: , n ,, , nu ,.
Greek letter.
\[Null]
Alias: , null ,. Letter-like form. Can be used to place subscripts and superscripts without having a visible base.
See page 1008. See also: \[InvisibleComma] , \[InvisibleSpace] , \[AlignmentMarker] .
\[OAcute]
Alias: , o' ,.
Letter.
\[ODoubleAcute]
Alias: , o'' ,. Letter. Included in ISO Latin-2. Used in Hungarian, for example in the name Erdos.
page 998. See also: \[CapitalODoubleAcute] , \[UDoubleAcute] .
\[ODoubleDot]
Alias: , o" ,. Letter. Included in ISO Latin-1.
\[CapitalODoubleDot] .
o`
Letter.
\[Omega]
Greek letter.
\[Omicron]
Aliases: , om ,, , omicron ,. Greek letter.
\[CapitalOmicron] , \[Omega].
Letter.
Aliases: , o ,, , omega ,, , w ,.
\[Omicron].
\[OHat]
Alias: , o^ ,.
\[OGrave]
Alias: , o` ,.
See
See also:
\[Or]
Aliases: , || ,, , or ,. Infix operator with built-in evaluation rules. x y is by default interpreted as Or[x, y],
equivalent to x || y. Not the same as \[Vee]. Drawn slightly larger than \[Vee]. See page 1001. See also:
\[And], \[Xor], \[Nor], \[Not].
\[OSlash]
Alias: , o/ ,. Letter. Included in ISO Latin-1.
also: \[CapitalOSlash].
See
Letter.
\[OverBrace]
Alias: , o{ ,. Letter-like form. Extensible character.
\[OverParenthesis] , \[UnderBrace] .
Extensible character.
\[Paragraph]
Letter-like form.
"
\[OverParenthesis]
Alias: , o( ,. Letter-like form.
\[UnderParenthesis] .
\[OverBracket]
Alias: , o[ ,. Letter-like form. Extensible character. See page 997.
\[OverBrace], \[UnderBracket] , \[HorizontalLine] .
1385
\[OTilde]
Alias: , o~ ,.
OTilde PrecedesEqual
\[PartialD]
Alias: , pd ,. Prefix operator with built-in evaluation rules.
8x y is by default interpreted as D[y, x]. " is used
in mathematics to indicate boundary. , d , gives \[Delta], not \[PartialD]. You can use \[InvisibleComma] in
the subscript to 8 to give several variables without having them separated by visible commas. See pages 185, 994
and 1000. See also: \[Delta], \[Del], \[DifferentialD], \[Eth].
\[Phi]
Aliases: , ph ,, , phi ,, , f ,. Greek letter. Used in TraditionalForm for EulerPhi and GoldenRatio.
pages 175 and 990. See also: \[CurlyPhi], \[CapitalPhi].
\[Pi]
Aliases: , p ,, , pi ,. Greek letter with built-in value. Interpreted by default as the symbol Pi.
and 990. See also: \[DoubledPi], \[CapitalPi], \[CurlyPi].
See
\[Placeholder]
Alias: , pl ,. Letter-like form. Used to indicate where expressions can be inserted in a form obtained by pasting
the contents of a button. Not the same as \[EmptySquare]. See pages 199, 587 and 1008. See also:
\[SelectionPlaceholder] , \[RawNumberSign] .
\[PlusMinus]
Alias: , +- ,. Prefix or infix operator. m x is by default interpreted as PlusMinus[x].
interpreted as PlusMinus[x, y]. See pages 191 and 1000. See also: \[MinusPlus].
x m y is by default
\[Precedes]
Infix ordering operator. x y is by default interpreted as Precedes[x, y]. Used in mathematics to indicate
various notions of partial ordering. Often applied to functions and read x is dominated by y. See page 1005.
See also: \[PrecedesEqual], \[Succeeds], \[NotPrecedes] .
\[PrecedesEqual]
Infix ordering operator. x m y is by default interpreted as PrecedesEqual[x, y]. See page 1005.
\[PrecedesSlantEqual] , \[PrecedesTilde] , \[SucceedsEqual] , \[NotPrecedesEqual] .
See also:
PrecedesSlantEqual RawColon
1386
\[PrecedesSlantEqual]
Infix ordering operator. x n y is by default interpreted as PrecedesSlantEqual[x, y].
also: \[PrecedesEqual], \[SucceedsSlantEqual] , \[NotPrecedesSlantEqual] .
See
\[PrecedesTilde]
Infix ordering operator. x o y is by default interpreted as PrecedesTilde[x, y].
\[PrecedesEqual] , \[SucceedsTilde] , \[NotPrecedesTilde] .
See also:
\[Prime]
Alias: , ' ,. Letter-like form. Used to indicate angles in minutes or distances in feet. Used in an overscript
position as an acute accent. See page 996. See also: \[DoublePrime], \[ReversePrime], \[RawQuote].
\[Product]
Alias: , prod ,.
imax
f is by default interpreted as
i
imax
i=imin
\[Proportion]
Infix relational operator. x p y is by default interpreted as Proportion[x, y]. Used historically to indicate
equality; now used to indicate proportion. See page 1003. See also: \[Divide], \[Proportional] , \[Colon],
\[Therefore].
\[Proportional]
Alias: , prop ,. Infix relational operator.
as \[Alpha]. See pages 191 and 1003.
See
Raw operator. Equivalent to the ordinary ASCII character with code 64.
\[RawAmpersand] , \[SmallCircle] .
See also:
\[RawAt]
\[RawBackquote]
Equivalent to the ordinary ASCII character with code 96.
\[RawBackslash]
Raw operator. Equivalent to the ordinary ASCII character with code 92.
page 1010. See also: \[Backslash].
Raw operator.
\[Prime].
Greek letter.
\[RawAmpersand]
Raw operator.
\[Psi]
Aliases: , ps ,, , psi ,, , y ,.
also: \[CapitalPsi].
&
See
\[RawColon]
Raw operator.
RawComma RawLess
\[RawComma]
Raw operator. Equivalent to the ordinary ASCII character with code 44.
\[InvisibleComma] .
1387
See also:
\[RawDash]
Raw operator. Equivalent to the ordinary ASCII character with code 45. As an overscript, used to indicate
conjugation or negation. Also used to indicate an average value or an upper value. In geometry, used to denote
a line segment. As an underscript, used to indicate a lower value.
x is interpreted as SuperMinus[x]. x is
interpreted as SubMinus[x]. Not the same as the letter-like form \[Dash]. See page 1010. See also:
\[RawPlus], \[HorizontalLine] .
\[RawDollar]
Letter-like form.
\[RawDot]
Raw operator. Equivalent to the ordinary ASCII character with code 46. As an overscript, used to indicate time
derivative.
xL is interpreted as OverDot[x]. See page 1010. See also: \[CenterDot], \[Ellipsis].
"
\[RawDoubleQuote]
Raw operator. Equivalent to the ordinary ASCII character with code 34.
page 1010. See also: \[RawQuote], \[Prime].
See
\[RawEqual]
Raw operator.
\[NotEqual].
\[RawEscape]
Raw element. Equivalent to the non-printable ASCII character with code 27.
characters in Mathematica. See also: \[AliasIndicator] , \[EscapeKey].
\[RawExclamation]
Raw operator. Equivalent to the ordinary ASCII character with code 33.
\[DownExclamation] .
>
See also:
\[RawLeftBrace]
Raw operator. Equivalent to the ordinary ASCII character with code 123.
See also: \[RawRightBrace].
\[RawGreater]
Raw operator. Equivalent to the ordinary ASCII character with code 62.
\[RightAngleBracket] . See page 1010. See also: \[NotGreater].
Extensible character.
\[RawLeftBracket]
Raw operator. Equivalent to the ordinary ASCII character with code 91. Extensible character.
See also: \[LeftDoubleBracket] , \[RawRightBracket] , \[RightDoubleBracket] .
\[RawLeftParenthesis]
Raw operator. Equivalent to the ordinary ASCII character with code 40.
See also: \[RawRightParenthesis] .
<
Extensible character.
\[RawLess]
Raw operator. Equivalent to the ordinary ASCII character with code 60.
\[RightAngleBracket] . See page 1010. See also: \[NotLess].
RawNumberSign RawStar
1388
\[RawNumberSign]
Raw operator. Equivalent to the ordinary ASCII character with code 35.
page 1010. See also: \[Placeholder] .
See also:
\[RawQuestion]
Raw operator. Equivalent to the ordinary ASCII character with code 63.
\[DownQuestion] .
See
\[RawPlus]
Raw operator.
\[RawPercent]
Raw operator.
\[RawQuote]
Raw operator. Equivalent to the ordinary ASCII character with code 39.
\[RawDoubleQuote] .
\[RawReturn]
Spacing character. Equivalent to the ordinary ASCII character with code 13.
the same as \[NewLine]. See page 1010. See also: \[ReturnIndicator] .
Extensible character.
Extensible character.
\[RawSemicolon]
Raw operator.
\[RawRightParenthesis]
Raw operator. Equivalent to the ordinary ASCII character with code 41.
See also: \[RawLeftParenthesis] .
\[RawRightBracket]
Raw operator. Equivalent to the ordinary ASCII character with code 93. Extensible character.
\[RightModified] . See page 1010. See also: \[LeftDoubleBracket] , \[RawLeftBracket] ,
\[RightDoubleBracket] .
Not always
\[RawRightBrace]
Raw operator. Equivalent to the ordinary ASCII character with code 125.
See also: \[RawLeftBrace] .
\[RawSlash]
Raw operator. Equivalent to the ordinary ASCII character with code 47.
to limited size. See page 1010. See also: \[Divide].
\[RawSpace]
Spacing character. Equivalent to the ordinary ASCII character with code 32. See page 1010.
\[NonBreakingSpace] , \[MediumSpace], \[SpaceIndicator] , \[InvisibleSpace] .
See also:
\[RawStar]
Raw operator. Equivalent to the ordinary ASCII character with code 42. In addition to one-dimensional uses,
x[ is by default interpreted as SuperStar[x]. x[ is often used in mathematics to indicate a conjugate, dual, or
completion of x. See page 1010. See also: \[Star], \[Times], \[SixPointedStar] .
RawTab ReversePrime
1389
\[RawTab]
Spacing character. Equivalent to the ordinary ASCII character with code 9.
See page 1010. See also: \[RightArrowBar] .
\[RawTilde]
Raw operator. Equivalent to the ordinary ASCII character with code 126. In addition to one-dimensional uses,
K
x is by default interpreted as OverTilde[x]. See page 1010. See also: \[Tilde], \[NotTilde].
\[RawUnderscore]
Raw operator. Equivalent to the ordinary ASCII character with code 95.
interpreted as UnderBar[x]. See page 1010. See also: \[Dash].
x is
N
\[RawVerticalBar]
Raw operator. Equivalent to the ordinary ASCII character with code 124.
See also: \[VerticalBar], \[LeftBracketingBar] .
N
x is interpreted as OverBar[x].
Extensible character.
\[RawWedge]
Raw operator. Equivalent to the ordinary ASCII character with code 94. In addition to one-dimensional uses, x
f
is by default interpreted as OverHat[x].
x is used for many purposes in mathematics, from indicating an
operator form of x to indicating that x is an angle. See page 1010. See also: \[Wedge].
\[RegisteredTrademark]
Letter-like form. Used as a superscript to indicate a registered trademark such as Mathematica. Typically used
only on the first occurrence of a trademark in a document. See page 996. See also: \[Trademark] ,
\[Copyright].
\[ReturnIndicator]
Alias: , ret ,. Letter-like form. Representation of the return or newline character on a keyboard. Used in
showing how textual input is typed. See page 1009. See also: \[ReturnKey], \[EnterKey], \[Continuation],
\[ControlKey], \[CommandKey] , \[SpaceIndicator] , \[NonBreakingSpace] .
\[ReturnKey]
Alias: , ret ,. Letter-like form. Representation of the RETURN key on a keyboard. Used in describing how to
type textual input. , ret , is the alias for \[ReturnIndicator] . The alias for \[ReturnKey] has a space at the
beginning. See page 1009. See also: \[EnterKey], \[ReturnIndicator] , \[ControlKey], \[CommandKey].
\[ReverseDoublePrime]
Alias: , `` ,.
Letter-like form.
\[ReverseElement]
Alias: , mem ,. Infix set relation operator. x y is by default interpreted as ReverseElement[x, y].
same as \[SuchThat]. See page 1004. See also: \[Element], \[NotReverseElement] .
>
Not the
\[ReverseEquilibrium]
Infix arrow-like operator. x 5 y is by default interpreted as ReverseEquilibrium[x, y]. Extensible character.
See page 1007. See also: \[Equilibrium] , \[ReverseUpEquilibrium] , \[LeftArrowRightArrow] ,
\[LeftRightArrow] .
\[ReversePrime]
Alias: , ` ,. Letter-like form. Used in an overscript position as a grave accent.
\[DoublePrime], \[Prime], \[ReverseDoublePrime] , \[RawBackquote].
See also:
ReverseUpEquilibrium RightDoubleBracket
1390
\[ReverseUpEquilibrium]
Infix arrow-like operator. x 6 y is by default interpreted as ReverseUpEquilibrium[x, y]. Extensible character.
See page 1007. See also: \[UpEquilibrium], \[DownArrowUpArrow] , \[RightUpDownVector] , \[Equilibrium].
\[Rho]
Aliases: , r ,, , rho ,.
Greek letter.
\[RightAngle]
Letter-like form. Used in geometry to indicate a right angle, as in the symbol ABC.
\[Angle], \[MeasuredAngle] , \[UpTee].
See also:
\[RightAngleBracket]
Alias: , > ,. Matchfix operator. / x 0 is by default interpreted as AngleBracket[x] . Used in the form /x0 to
indicate expected or average value. Called ket in quantum mechanics. Used in the form /x, y0 to indicate
various forms of inner product. Used in the form /x, y, . . . 0 to denote an ordered set of objects. Not the same
as \[RawGreater] . Extensible character; grows by default to limited size. See page 1002. See also:
\[LeftAngleBracket] .
\[RightArrow]
Alias: , -> ,. Infix arrow operator. Used for many purposes in mathematics to indicate transformation, tending
to a limit or implication. Used as an overscript to indicate a directed object. Not the same as \[Rule]. , -> , is
the alias for \[Rule]. The alias for \[RightArrow] has a space at the beginning. Extensible character. See
page 1006. See also: \[LongRightArrow] , \[ShortRightArrow] , \[DoubleRightArrow] , \[RightTeeArrow] ,
\[RightArrowBar] , \[UpperRightArrow] , \[RightVector] , \[RightTriangle] , \[LeftArrow],
\[HorizontalLine] , \[Implies].
"
\[RightArrowBar]
Infix arrow operator. x 7 y is by default interpreted as RightArrowBar[x, y]. Used in mathematics to indicate
an epimorphism. Sometimes used to indicate a tab. Extensible character. See page 1006. See also:
\[RightTeeArrow] , \[RightVectorBar] , \[UpArrowBar], \[LeftArrowBar], \[RawTab].
\[RightArrowLeftArrow]
Infix arrow operator. x 8 y is by default interpreted as RightArrowLeftArrow[x, y]. Extensible character. See
page 1006. See also: \[LeftArrowRightArrow] , \[LeftRightArrow] , \[DoubleLeftRightArrow] , \[Equilibrium] ,
\[UpArrowDownArrow] .
\[RightBracketingBar]
Alias: , r| ,. Matchfix operator. @ x A is by default interpreted as BracketingBar[x] . Used in mathematics to
indicate absolute value (Abs), determinant (Det), and other notions of evaluating size or magnitude. Not the same
as \[VerticalBar] . Drawn in monospaced fonts with a small right-pointing tee to indicate direction. Extensible
character. See page 1002. See also: \[RightDoubleBracketingBar] , \[RightTee].
'
\[RightCeiling]
Alias: , rc ,. Matchfix operator with built-in evaluation rules. F x G is by default interpreted as Ceiling[x].
Extensible character. See page 1002. See also: \[LeftCeiling], \[RightFloor] .
\[RightDoubleBracket]
Alias: , ]] ,. m+i,j, . . . , is by default interpreted as Part[m, i, j, . . . ]. Extensible character; grows by default
to limited size. See page 1002. See also: \[RawRightBracket] , \[RightDoubleBracketingBar] .
RightDoubleBracketingBar RightTeeArrow
1391
\[RightDoubleBracketingBar]
Alias: , r|| ,. Matchfix operator. B x C is by default interpreted as DoubleBracketingBar[x] . Used in
mathematics to indicate taking a norm. Sometimes used for determinant. Sometimes used to indicate a matrix.
Not the same as \[DoubleVerticalBar] . Drawn in monospaced fonts with a small right-pointing tee to
indicate direction. Extensible character. See page 1002. See also: \[RightBracketingBar] .
\[RightDownTeeVector]
Infix arrow-like operator. x 9 y is by default interpreted as RightDownTeeVector[x, y]. Extensible character.
See page 1007. See also: \[LeftDownTeeVector] , \[RightDownVectorBar] , \[DownTeeArrow] ,
\[RightUpTeeVector] .
\[RightDownVector]
Infix arrow-like operator. x : y is by default interpreted as RightDownVector[x, y]. Extensible character.
page 1007. See also: \[LeftDownVector] , \[RightDownTeeVector] , \[DownArrow], \[UpEquilibrium] ,
\[RightUpVector].
See
\[RightDownVectorBar]
Infix arrow-like operator. x ; y is by default interpreted as RightDownVectorBar[x, y]. Extensible character.
See page 1007. See also: \[LeftDownVectorBar] , \[RightDownTeeVector] , \[DownArrowBar] ,
\[RightUpVectorBar] .
\[RightFloor]
Alias: , rf ,. Matchfix operator with built-in evaluation rules. D x E is by default interpreted as Floor[x].
Extensible character. See page 1002. See also: \[LeftFloor], \[RightCeiling].
\[RightGuillemet]
Alias: , g>> ,. Letter-like form. Used as closing quotation marks in languages such as Spanish. Not the same as
\[GreaterGreater] . Not the same as RightSkeleton. Guillemet is sometimes misspelled as guillemot. See
page 996. See also: \[LeftGuillemet] .
\[RightModified]
Alias: , ] ,. Letter-like form. Used in documenting control and command characters.
key\[LeftModified]char\[RightModified] is used to indicate that char should be typed while key is being
pressed. Not the same as \[RawRightBracket] . See page 1009. See also: \[ControlKey], \[CommandKey],
\[LeftModified].
\[RightSkeleton]
Uninterpretable element. : n ; is used on output to indicate n omitted pieces in an expression obtained from
Short or Shallow. \[RightSkeleton] indicates the presence of missing information, and so by default generates
an error if you try to interpret it. Not the same as \[RightGuillemet] . See page 1009. See also:
\[LeftSkeleton], \[SkeletonIndicator] , \[Ellipsis].
\[RightTee]
Alias: , rT ,. Infix operator. x y is by default interpreted as RightTee[x, y]. x y z groups as x (y z).
Used in mathematics to indicate logical implication or proof. See pages 191, 1001 and 1007. See also:
\[DoubleRightTee] , \[RightTeeArrow] , \[RightTeeVector] , \[LeftTee], \[DownTee], \[RightBracketingBar] .
\[RightTeeArrow]
Infix arrow operator. x < y is by default interpreted as RightTeeArrow[x, y]. Used in mathematics to indicate
a transformation, often the action of a mapping on a specific element in a space. Also used in logic to indicate
deducibility. Extensible character. See page 1006. See also: \[RightTeeVector] , \[RightTee],
\[LeftTeeArrow], \[UpTeeArrow].
1392
RightTeeVector RoundImplies
\[RightTeeVector]
Infix arrow-like operator. x = y is by default interpreted as RightTeeVector[x, y]. Extensible character.
page 1007. See also: \[DownRightTeeVector] , \[RightVectorBar] , \[RightVector], \[RightTeeArrow] .
See
\[RightTriangle]
Infix ordering operator. x q y is by default interpreted as RightTriangle[x, y]. Used in pure mathematics to
mean contains as a normal subgroup. See pages 191 and 1005. See also: \[RightTriangleEqual] ,
\[RightTriangleBar] , \[RightArrow], \[NotRightTriangle] , \[LeftTriangle], \[EmptyUpTriangle] ,
\[FilledUpTriangle] , \[RightAngle].
\[RightTriangleBar]
Infix ordering operator. x r y is by default interpreted as RightTriangleBar[x, y]. See page 1005.
\[RightTriangle] , \[RightTriangleEqual] , \[RightArrowBar], \[NotRightTriangleBar] .
See also:
\[RightTriangleEqual]
Infix ordering operator. x s y is by default interpreted as RightTriangleEqual[x, y]. See page 1005.
also: \[RightTriangle], \[RightTriangleBar] , \[SucceedsEqual] , \[NotRightTriangleEqual] ,
\[LeftTriangleEqual] .
G
B
K
0
See
\[RightUpDownVector]
Infix arrow-like operator. x > y is by default interpreted as RightUpDownVector[x, y]. Extensible character.
See page 1007. See also: \[LeftUpDownVector] , \[UpEquilibrium] , \[UpArrowDownArrow] ,
\[LeftRightVector] .
\[RightUpTeeVector]
Infix arrow-like operator. x ? y is by default interpreted as RightUpTeeVector[x, y]. Extensible character.
page 1007. See also: \[LeftUpTeeVector] , \[RightUpVectorBar] , \[UpTeeArrow], \[RightDownTeeVector] .
See
\[RightUpVector]
Infix arrow-like operator. x @ y is by default interpreted as RightUpVector[x, y]. Used in pure mathematics to
indicate the restriction of x to y. Extensible character. See page 1007. See also: \[LeftUpVector],
\[RightUpTeeVector] , \[UpArrow], \[UpEquilibrium] , \[RightDownVector] .
\[RightUpVectorBar]
Infix arrow-like operator. x A y is by default interpreted as RightUpVectorBar[x, y]. Extensible character.
page 1007. See also: \[LeftUpVectorBar] , \[RightUpTeeVector] , \[UpArrowBar], \[RightDownVectorBar] .
See
\[RightVector]
Alias: , vec ,. Infix and overfix arrow-like operator. x y is by default interpreted as RightVector[x, y].
=
Used in mathematics to indicate weak convergence.
x is by default interpreted as OverVector[x]. Used in
mathematics to indicate a vector quantity. Sometimes used in prefix form as a typographical symbol to stand for
see also. Extensible character. See page 1007. See also: \[DownRightVector] , \[RightTeeVector] ,
\[RightVectorBar] , \[RightArrow], \[LeftVector] , \[RightUpVector] .
\[RightVectorBar]
Infix arrow-like operator. x y is by default interpreted as RightVectorBar[x, y]. Extensible character.
page 1007. See also: \[DownRightVectorBar] , \[RightTeeVector] , \[RightArrowBar] .
See
\[RoundImplies]
Infix operator with built-in evaluation rules. x ! y is by default interpreted as Implies[x, y]. x ! y ! z groups
as x ! (y ! z). Not the same as \[Superset]. See pages 1001 and 1006. See also: \[Implies], \[SuchThat],
\[RightArrow], \[Rule].
RoundSpaceIndicator Sharp
\[RoundSpaceIndicator]
Spacing character. Interpreted by default as equivalent to \[RawSpace].
\[SpaceIndicator] , \[Cup], \[Breve].
1393
See also:
\[Rule]
Alias: , -> ,. Infix operator with built-in evaluation rules. x y is by default interpreted as x -> y or
Rule[x, y]. x y z groups as x (y z). \[Rule] is not the same as \[RightArrow]. See page 1006.
See also: \[RuleDelayed].
\[RuleDelayed]
Alias: , :> ,. Infix operator with built-in evaluation rules.
RuleDelayed[x, y]. x
y
z groups as x
(y
z).
\[RightArrow].
\[SadSmiley]
Alias: , :-( ,. Letter-like form.
\[FreakedSmiley].
\[Sampi]
Aliases: , sa ,, , sampi ,. Special Greek letter. Appeared after in early Greek alphabet; used for Greek numeral
900. See page 990. See also: \[CapitalSampi] , \[Digamma], \[Stigma], \[Koppa].
\[ScriptA] \[ScriptZ]
Aliases: , sca , through , scz ,. Letters. Treated as distinct characters rather than style modifications of ordinary
letters. \[ScriptL] is a commonly used form. Contiguous character codes from the private Unicode character
range are used, even though a few script characters are included in ordinary Unicode. See page 993. See also:
\[ScriptCapitalA] , \[GothicA], \[DoubleStruckA] , etc.
\[ScriptCapitalA] \[ScriptCapitalZ]
Aliases: , scA , through , scZ ,. Letters. Treated as distinct characters rather than style modifications of ordinary
letters. is sometimes called Eulers E. \[ScriptCapitalE] is not the same as \[CurlyEpsilon] . is
sometimes used to denote Fourier transform. is sometimes used to denote Laplace transform. and are
used in physics to denote Hamiltonian and Lagrangian density. \[ScriptCapitalP] is not the same as
\[WeierstrassP]. Contiguous character codes from the private Unicode character range are used, even though a
few capital script characters are included in ordinary Unicode. See page 993. See also: \[GothicCapitalA] ,
\[DoubleStruckCapitalA] , etc.
\[Section]
Letter-like form.
\[SelectionPlaceholder]
Alias: , spl ,. Letter-like form. Used to indicate where the current selection should be inserted when the contents
of a button are pasted by NotebookApply. Not the same as \[FilledSquare] . See pages 199, 587 and 1008.
See also: \[Placeholder].
\[SHacek]
Alias: , sv ,.
Letter.
\[Sharp]
Letter-like form. Used to denote musical notes. Sometimes used in mathematical notation, typically to indicate
some form of numbering or indexing. Not the same as \[RawNumberSign] . See page 996. See also: \[Flat],
\[Natural].
ShortLeftArrow SquareIntersection
1394
\[ShortLeftArrow]
Infix arrow operator.
Extensible character.
\[ShortRightArrow]
Infix arrow operator. Not the same as \[Rule].
\[RightArrow], \[LongRightArrow] .
Extensible character.
See also:
\[Sigma]
Aliases: , s ,, , sigma ,. Greek letter. Used in TraditionalForm for DivisorSigma and WeierstrassSigma .
pages 175 and 990. See also: \[CapitalSigma] , \[FinalSigma].
\[SixPointedStar]
Alias: , *6 ,. Letter-like form. Not the same as the operator \[Star].
\[FivePointedStar] , \[Star], \[RawStar].
See
See also:
\[SkeletonIndicator]
Uninterpretable element. A name A is used on output to indicate an expression that has head name, but whose
arguments will not explicitly be given. \[SkeletonIndicator] indicates the presence of missing information, and
so by default generates an error if you try to interpret it. See page 1009. See also: \[LeftSkeleton] ,
\[Ellipsis].
\[SmallCircle]
Alias: , sc ,. Infix operator. x y is by default interpreted as SmallCircle[x, y]. Used to indicate function
composition. Not the same as the letter-like form \[EmptyCircle] . Not the same as \[Degree]. See pages 191
and 1002. See also: \[FilledCircle], \[CircleDot], \[CircleTimes] .
\[SpaceIndicator]
Alias: , space ,. Spacing character. Interpreted by default as equivalent to \[RawSpace].
also: \[RoundSpaceIndicator] , \[ThinSpace], \[ReturnIndicator] .
See
\[SpadeSuit]
Letter-like form.
\[SphericalAngle]
Letter-like form. Used in geometry to indicate a spherical angle, as in the symbol ABC.
also: \[Angle], \[MeasuredAngle] .
See
\[Sqrt]
Alias: , sqrt ,. Prefix operator with built-in evaluation rules. 2 x is by default interpreted as Sqrt[x]. @ ,
2 or \@ yields a complete SqrtBox object. \[Sqrt] is equivalent when evaluated, but will not draw a line
on top of the quantity whose square root is being taken. See page 1000.
\[Square]
Alias: , sq ,. Prefix operator. x is by default interpreted as Square[x]. Used in mathematical physics to
denote the dAlembertian operator. Sometimes used in number theory to indicate a quadratic residue. Not the
same as \[EmptySquare] . See page 1002. See also: \[Del].
\[SquareIntersection]
Infix operator. x M y is by default interpreted as SquareIntersection[x, y].
also: \[SquareUnion], \[Intersection] , \[Wedge].
See
SquareSubset Succeeds
1395
\[SquareSubset]
Infix set relation operator. x t y is by default interpreted as SquareSubset[x, y]. Used in computer science to
indicate that x is a substring occurring at the beginning of y. See page 1005. See also: \[NotSquareSubset] ,
\[SquareSuperset] .
\[SquareSubsetEqual]
Infix set relation operator. x u y is by default interpreted as SquareSubsetEqual[x, y].
also: \[NotSquareSubsetEqual] .
See
\[SquareSuperset]
Infix set relation operator. x v y is by default interpreted as SquareSuperset[x, y].
Used in computer science
to indicate that x is a substring occurring at the end of y. See page 1005. See also: \[NotSquareSuperset] ,
\[SquareSubset].
\[SquareSupersetEqual]
Infix set relation operator. x w y is by default interpreted as SquareSupersetEqual[x, y].
also: \[NotSquareSupersetEqual] .
See
\[SquareUnion]
Infix operator. x ? y is by default interpreted as SquareUnion[x, y]. Used in mathematics to denote various
forms of generalized union, typically of disjoint subspaces. See page 1002. See also: \[SquareIntersection] ,
\[Union], \[UnionPlus] , \[Vee], \[Coproduct].
\[Star]
Alias: , star ,. Infix operator. x [ y is by default interpreted as Star[x, y]. Used to denote convolution and
generalized forms of multiplication. Sometimes used in prefix form to indicate dual. Not the same as
\[SixPointedStar] or \[RawStar]. \[RawStar] is the character entered for superscripts. See page 1002. See
also: \[Times], \[Cross].
\[Sterling]
Letter-like form. Currency symbol for British pound sterling, as in x 5. Used in mathematics to denote Lie
derivative. See pages 192 and 994. See also: \[RawNumberSign] , \[Euro].
\[Stigma]
Aliases: , sti ,, , stigma ,. Special Greek letter. Appeared between and in early Greek alphabet; used for
Greek numeral 6. Not the same as \[FinalSigma] . See page 990. See also: \[CapitalStigma] , \[Digamma],
\[Koppa], \[Sampi].
\[Subset]
Alias: , sub ,. Infix set relation operator. x p y is by default interpreted as Subset[x, y]. Usually used in
mathematics to indicate subset; sometimes proper subset. See page 1004. See also: \[SubsetEqual],
\[SquareSubset], \[Element], \[Precedes], \[LeftTriangle] , \[NotSubset].
\[SubsetEqual]
Alias: , sub= ,. Infix set relation operator.
See also: \[NotSubsetEqual] .
\[Succeeds]
Infix ordering operator. x y is by default interpreted as Succeeds[x, y]. Used in mathematics to indicate
various notions of partial ordering. Often applied to functions and read x dominates y. See pages 191
and 1005. See also: \[SucceedsEqual] , \[Precedes], \[NotSucceeds].
SucceedsEqual Theta
1396
\[SucceedsEqual]
Infix ordering operator. x y y is by default interpreted as SucceedsEqual[x, y]. See page 1005.
\[SucceedsSlantEqual] , \[SucceedsTilde] , \[PrecedesEqual], \[NotSucceedsEqual] .
\[SucceedsSlantEqual]
Infix ordering operator. x z y is by default interpreted as SucceedsSlantEqual[x, y].
also: \[SucceedsEqual], \[PrecedesSlantEqual] , \[NotSucceedsSlantEqual] .
See
\[SucceedsTilde]
Infix ordering operator. x { y is by default interpreted as SucceedsTilde[x, y].
\[SucceedsEqual] , \[PrecedesTilde] , \[NotSucceedsTilde] .
See also:
See also:
\[SuchThat]
Alias: , st ,. Infix operator. x _ y is by default interpreted as SuchThat[x, y]. x _ y _ z groups as
x _ (y _ z). Not the same as \[ReverseElement] . See page 1001. See also: \[Exists], \[ForAll], \[Colon],
\[VerticalBar] .
\[Sum]
Alias: , sum ,.
imax
f is by default interpreted as
i
imax
i=imin
\[CapitalSigma] .
\[Superset]
Alias: , sup ,. Infix set relation operator. x q y is by default interpreted as Superset[x, y]. Usually used in
mathematics to indicate superset; sometimes proper superset. Not the same as \[RoundImplies] . See pages 191
and 1004. See also: \[SupersetEqual] , \[SquareSuperset] , \[ReverseElement] , \[Succeeds],
\[RightTriangle] , \[NotSuperset] .
\[SupersetEqual]
Alias: , sup= ,. Infix set relation operator. x y is by default interpreted as SupersetEqual[x, y].
page 1004. See also: \[NotSupersetEqual] .
See
\[SZ]
Aliases: , sz ,, , ss ,. Letter. Used in German. Sometimes called s sharp, ess-zed or ess-zet. Usually
transliterated in English as ss. Upper-case form is SS. Included in ISO Latin-1. See pages 190 and 998.
also: \[Beta].
\[Tau]
Aliases: , t ,, , tau ,.
See
Greek letter.
\[Therefore]
Alias: , tf ,. Infix operator. x i y is by default interpreted as Therefore[x, y]. x i y i z groups as
x i (y i z). See pages 191 and 1001. See also: \[Because], \[Implies], \[RightTee], \[FilledRectangle] ,
\[Proportion].
\[Theta]
Aliases: , th ,, , theta ,, , q ,.
\[Tau].
Greek letter.
ThickSpace UDoubleAcute
1397
\[ThickSpace]
Alias: , ,. Spacing character. Width: 5/18 em. Interpreted by default just like an ordinary \[RawSpace].
See page 1008. See also: \[MediumSpace] , \[NegativeThickSpace] , SpaceIndicator .
\[ThinSpace]
Alias: , ,. Spacing character. Width: 3/18 em. Interpreted by default just like an ordinary \[RawSpace].
See page 1008. See also: \[VeryThinSpace] , \[MediumSpace] , \[NegativeThinSpace] , \[SpaceIndicator] .
\[Thorn]
Alias: , thn ,. Letter. Included in ISO Latin-1.
\[CapitalThorn], \[Eth].
See also:
\[Tilde]
Alias: , M ,. Infix similarity operator. x M y is by default interpreted as Tilde[x, y]. Used in mathematics for
many notions of similarity or equivalence. Used in physical science to indicate approximate equality.
Occasionally used in mathematics for notions of difference. Occasionally used in prefix form to indicate
complement or negation. Not the same as \[RawTilde]. See pages 191 and 1003. See also: \[NotTilde],
\[VerticalTilde], \[Not].
\[TildeEqual]
Alias: , ~= ,. Infix similarity operator. x | y is by default interpreted as TildeEqual[x, y]. Used to mean
approximately or asymptotically equal. Also used in mathematics to indicate homotopy. See pages 191 and 1003.
See also: \[TildeTilde], \[TildeFullEqual] , \[NotTildeEqual] .
\[TildeFullEqual]
Alias: , ~== ,. Infix similarity operator. x y is by default interpreted as TildeFullEqual[x, y]. Used in
mathematics to indicate isomorphism, congruence and homotopic equivalence. See page 1003. See also:
\[TildeEqual], \[Congruent], \[NotTildeFullEqual] .
\[TildeTilde]
Alias: , ~~ ,. Infix similarity operator. x h y is by default interpreted as TildeTilde[x, y]. Used for various
notions of approximate or asymptotic equality. Used in pure mathematics to indicate homeomorphism. See
pages 191 and 1003. See also: \[TildeEqual], \[NotTildeTilde] .
\[Times]
Alias: , * ,. Infix operator with built-in evaluation rules. x y is by default interpreted as Times[x, y], which is
equivalent to x y or x * y. Not the same as \[Cross]. \[Times] represents ordinary multiplication, while
\[Cross] represents vector cross product. \[Times] is drawn larger than \[Cross]. See page 1000. See also:
\[Star], \[CircleTimes] , \[Divide], \[Wedge].
\[Trademark]
Letter-like form. Used to indicate a trademark that may not be registered. Typically used only on the first
occurrence of a trademark in a document. See page 996. See also: \[RegisteredTrademark] , \[Copyright].
\[UAcute]
Alias: , u' ,.
Letter.
\[UDoubleAcute]
Alias: , u'' ,. Letter. Included in ISO Latin-2.
\[CapitalUDoubleAcute] .
Used in Hungarian.
See also:
UDoubleDot UpEquilibrium
1398
\[UDoubleDot]
Alias: , u" ,. Letter. Included in ISO Latin-1.
\[CapitalUDoubleDot] .
u`
Letter.
Letter.
\[UHat]
Alias: , u^ ,.
\[UGrave]
Alias: , u` ,.
\[UnderBrace]
Alias: , u{ ,. Letter-like form. Extensible character.
\[UnderParenthesis] , \[OverBrace].
\[UnderBracket]
Alias: , u[ ,. Letter-like form. Extensible character. See page 997.
\[UnderBrace], \[OverBracket], \[HorizontalLine] .
\[UnderParenthesis]
Alias: , u( ,. Letter-like form.
\[OverParenthesis] .
Extensible character.
\[Union]
Alias: , un ,. Infix operator with built-in evaluation rules. x y is by default interpreted as Union[x, y].
character is sometimes called cup; but see also \[Cup]. See page 1002. See also: \[Intersection],
\[SquareUnion] , \[UnionPlus], \[Cup], \[Vee].
The
\[UnionPlus]
Infix operator. x } y is by default interpreted as UnionPlus[x, y]. Used to denote union of multisets, in which
multiplicities of elements are added. See page 1002. See also: \[Union], \[CirclePlus].
\[UpArrow]
Infix arrow operator. x b y is by default interpreted as UpArrow[x, y]. Sometimes used in mathematics to
denote generalization of powers. Used to indicate monotonic increase to a limit. Sometimes used in prefix form
to indicate the closure of a set. Extensible character. See pages 191 and 1006. See also: \[UpTeeArrow],
\[UpArrowBar], \[DoubleUpArrow] , \[LeftUpVector] , \[DownArrow], \[Wedge], \[RawWedge].
&
*
\[UpArrowBar]
Infix arrow operator. x B y is by default interpreted as UpArrowBar[x, y].
See also: \[UpTeeArrow], \[LeftUpVectorBar] .
Extensible character.
\[UpArrowDownArrow]
Infix arrow operator. x C y is by default interpreted as UpArrowDownArrow[x, y]. Extensible character. See
page 1006. See also: \[DownArrowUpArrow] , \[UpDownArrow], \[DoubleUpDownArrow] , \[UpEquilibrium] .
\[UpDownArrow]
Infix arrow operator. x y is by default interpreted as UpDownArrow[x, y]. Extensible character. See
page 1006. See also: \[UpArrowDownArrow] , \[DoubleUpDownArrow] , \[LeftUpDownVector] , \[UpEquilibrium] .
\[UpEquilibrium]
Infix arrow-like operator. x D y is by default interpreted as UpEquilibrium[x, y]. Extensible character. See
page 1007. See also: \[ReverseUpEquilibrium] , \[UpArrowDownArrow] , \[LeftUpDownVector] , \[Equilibrium].
UpperLeftArrow VerticalLine
1399
\[UpperLeftArrow]
Infix arrow operator. x E y is by default interpreted as UpperLeftArrow[x, y]. Extensible character; grows by
default to limited size. See page 1006. See also: \[UpperRightArrow] , \[LeftArrow].
\[UpperRightArrow]
Infix arrow operator. x y is by default interpreted as UpperRightArrow[x, y]. Extensible character; grows by
default to limited size. See page 1006. See also: \[UpperLeftArrow] , \[RightArrow].
\[Upsilon]
Aliases: , u ,, , upsilon ,.
Greek letter.
\[UpTee]
Alias: , uT ,. Infix relational operator. x ~ y is by default interpreted as UpTee[x, y]. Used in geometry to
indicate perpendicular. Used in number theory to indicate relative primality. See page 1007. See also:
\[RightAngle], \[NotDoubleVerticalBar] , \[DownTee].
\[UpTeeArrow]
Infix arrow operator. x F y is by default interpreted as UpTeeArrow[x, y]. Extensible character.
See also: \[UpArrowBar], \[LeftUpTeeVector] , \[UpTee], \[DownTeeArrow] .
\[Vee]
Alias: , v ,. Infix operator. x # y is by default interpreted as Vee[x, y]. Used to indicate various notions of
joining, and as a dual of \[Wedge]. Not the same as \[Or]. Drawn slightly smaller than \[Or]. Sometimes
used in prefix form to indicate the total variation of a function. See pages 191 and 1002. See also: \[Wedge],
\[Union], \[SquareUnion] , \[Nu], \[Hacek].
\[VerticalBar]
Alias: , | ,. Infix operator. x 3 y is by default interpreted as VerticalBar[x, y]. Used in mathematics to
indicate that x divides y. Also sometimes called Sheffer stroke, and used to indicate logical NAND. Not the
same as \[VerticalSeparator] , which is drawn longer. Not the same as \[LeftBracketingBar] and
\[RightBracketingBar] , which are drawn with a small tee to indicate their direction. , | , is the alias for
\[VerticalSeparator] . The alias for \[VerticalBar] has a space at the beginning. See pages 191 and 1005.
See also: \[RawVerticalBar] , \[Nand], \[NotVerticalBar] , \[DoubleVerticalBar] , \[Backslash],
\[HorizontalLine] .
\[VerticalEllipsis]
Letter-like form. Used to indicate omitted elements in columns of a matrix.
\[Ellipsis], \[AscendingEllipsis] , \[VerticalBar].
See also:
\[VerticalLine]
Alias: , vline ,. Letter-like form. Extensible character. Not the same as \[VerticalSeparator] or
\[VerticalBar], which are infix operators. Not the same as \[LeftBracketingBar] and
\[RightBracketingBar] , which are matchfix operators, drawn with a small tee to indicate their direction.
page 997. See also: \[RawVerticalBar] , \[HorizontalLine] , \[VerticalEllipsis] , \[UpArrow].
See
VerticalSeparator Xor
1400
\[VerticalSeparator]
Alias: , | ,. Infix operator. x y is by default interpreted as VerticalSeparator[x, y]. Used in mathematics
for many purposes, including indicating restriction and standing for such that. Also used to separate arguments
of various mathematical functions. Extensible character; grows by default to limited size. Not the same as
\[VerticalBar] , which is drawn shorter. Not the same as \[LeftBracketingBar] and \[RightBracketingBar] ,
which are drawn with a small tee to indicate their direction. Not the same as \[VerticalLine] , which is a
letter-like form, and is indefinitely extensible. See pages 191 and 1001. See also: \[RawVerticalBar] ,
\[NotVerticalBar] , \[DoubleVerticalBar] , \[Colon], \[SuchThat], \[HorizontalLine] .
\[VerticalTilde]
Infix operator. x $ y is by default interpreted as VerticalTilde[x, y].
product. See page 1002. See also: \[Tilde].
\[VeryThinSpace]
Alias: , ,. Spacing character. Width: 1/18 em. Interpreted by default just like an ordinary \[RawSpace].
page 1008. See also: \[ThinSpace], \[NegativeVeryThinSpace] , \[AlignmentMarker] , \[Null],
\[InvisibleComma] .
\[WarningSign]
Letter-like form.
\[WatchIcon]
Letter-like form. Used to indicate a calculation that may take a long time.
\[WarningSign] .
See
See also:
\[Wedge]
Alias: , ^ ,. Infix operator. x y is by default interpreted as Wedge[x, y]. Used to mean wedge or exterior
product and other generalized antisymmetric products. Occasionally used for generalized notions of intersection.
Not the same as \[And], \[CapitalLambda] or \[RawWedge]. See pages 191 and 1002. See also: \[Vee],
\[UpArrow], \[Intersection] , \[SquareIntersection] , \[CircleTimes].
\[WeierstrassP]
Alias: , wp ,.
page 992.
Letter.
Letter-like form.
\[Xi]
Aliases: , x ,, , xi ,.
See
\[Wolf]
Aliases: , wf ,, , wolf ,.
Greek letter.
\[Xor]
Alias: , xor ,. Infix operator with built-in evaluation rules.
page 1001. See also: \[Nor], \[Or], \[CirclePlus].
See
Letter.
\[Yen]
Letter-like form.
1401
\[YAcute]
Alias: , y' ,.
&
YAcute Zeta
5000.
\[Zeta]
Aliases: , z ,, , zeta ,. Greek letter. Used in TraditionalForm for Zeta and WeierstrassZeta.
and 990. See also: \[CapitalZeta], \[Xi].
1402
N[expr, n] now always tries to give n digits of precision if possible, rather than simply starting with n digits of precision.
1403
All expressions containing only numeric functions and numerical constants are now converted to approximate numerical
form whenever they contain any approximate numbers.
Many expressions involving exact numbers that used to remain unevaluated are now evaluated. Example:
Floor[(7/3)^20].
Plus and Times now apply built-in rules before user-defined ones, so it is no longer possible to make definitions such as
2+2=5.
The operator precedence for . and ** has been changed so as to be below ^. This has the consequence that expressions
previously written in InputForm as a . b ^ n must now be written as (a . b)^n. V2Get[file] will read a file using old
operator precedences.
\^ is now an operator used to generate a superscript. Raw octal codes must be used instead of \^A for inputting
control characters.
In Mathematica notebooks, several built-in Mathematica functions are now output by default using special characters.
Example: x->y is output as xy in StandardForm.
More sophisticated definite integrals now yield explicit If constructs unless the option setting
GenerateConditions->False is used.
1404
xy
The symbols I and E are now output in StandardForm as (\[ImaginaryI]) and (\[ExponentialE]) respectively.
A new second argument has been added to CompiledFunction to allow easier manipulation and composition of
compiled functions.
Precision and Accuracy now return exact measures of uncertainty in numbers, not just estimates of integer numbers of
digits.
Precision now returns the symbol MachinePrecision for machine numbers, rather than the numerical value
$MachinePrecision .
N[expr, MachinePrecision] is now used for numerical evaluation with machine numbers; N[expr, $MachinePrecision]
generates arbitrary-precision numbers.
ConstrainedMin and ConstrainedMax have been superseded by Minimize, Maximize, NMinimize and NMaximize.
SingularValues has been superseded by SingularValueList and SingularValueDecomposition .
SingularValueDecomposition uses a different and more complete definition.
FindRoot[f, {x, {x , x }}] is now used to specify a starting vector value for x, rather than a pair of values. The same
is true for FindMinimum.
DSolveConstants has been superseded by the more general option GeneratedParameters .
TensorRank has been replaced by ArrayDepth.
$TopDirectory has been superseded by $InstallationDirectory and $BaseDirectory.
The default setting for the MathLink LinkProtocol option when connecting different computer systems is now "TCPIP"
rather than "TCP".
Index
This index includes not only specific words and phrases from the
text but also concepts and topics related to them. This means that
a particular term in the index may not appear in its literal form on
any of the pages specified. Note that the terms are sorted in standard dictionary order, with most non-alphabetic characters ignored.
See the Standard Add-on Packages book for information on capabilities included in additional packages bundled with most versions
of Mathematica.
You can also use the online Help Browser in the Mathematica
notebook front end to search for topics that appear anywhere in
documentation for Mathematica and for packages that you have
installed.
Index
Index
1407
1408
cells, 54
element, ButtonBox, 448, 595, 1092
elements in notebooks, 54
links, Links, 662, 1198
text, in notebooks, 56
\[ACup] ( a ), 998, 1354
Adamchik techniques, Sum, 1071, 1296
Adams methods, NDSolve, 979, 1068, 1216
Adaptive integration procedure, 953
Adaptive procedure, in NDSolve, 966, 1216
Adaptive sampling, in plots, 137
Add, without carry, BitXor, 756, 1090
Add-in programs, 657
Add-ons, location of files for, 1063
Addition, of elements to lists, Append, 125,
288, 1080
patterns involving, 270
Plus (+), 29, 1244
Additive cellular automata,
CellularAutomaton, 946, 1101
AddTo (+=), 305, 1029, 1077
Adjoint, Conjugate, 746, 1111
AdjustmentBox, 455, 1078
Adjustments, to formatting, 449
Adobe character encoding, 421
\[ADoubleDot] ( a ), 190, 998, 1354
Advanced topic sections, xv
\[AE] ( ), 998, 1354
\ae (TEX), \[AE] ( ), 998
\AE (TEX), \[CapitalAE] ( ), 998
Agemo, \[Mho] ( ), 994
Aggregating brace, \[OverBrace] ( ), 997
\[AGrave] ( a` ), 190, 998, 1354
\[AHat] ( a ), 998, 1354
AIFF format, exporting, Export, 569, 1141
importing, Import, 570, 1176
Airy functions, AiryAi, 776, 1078
derivatives of, AiryAiPrime, 776, 1078
Airys differential equation, DSolve, 872,
1129
AiryAi, 775, 776, 1078
AiryAiPrime, 775, 776, 1078
AiryBi, 775, 776, 1078
AiryBiPrime, 775, 1078
Alarm, Pause, 710, 1241
Albedo, 547
\[Aleph] ( ), 192, 993, 1354
Algebraic algorithms, GroebnerBasis, 805,
1168
Algebraic computation, 63
Algebraic curves, 822
Algebraic equations, 88
Solve, 820, 1285
Algebraic expressions, internal
representation of, 234, 279
parts in, 234
patterns for, 261, 279
pieces of, 73
Algebraic extensions, 751
Algebraic geometry, 845
Algebraic numbers, 809, 826
Index
Index
AppellF1 Assignments
1409
1410
Index
Back-tracking, 48
Background, 444, 452, 504, 574, 604, 612,
619, 1087
Background color, for text, Background,
444, 612, 1087
Background lighting, AmbientLight, 545,
1079
\backprime (TEX), \[RawBackquote] ( ),
1010
Backquote, 1015
Backs of polygons, 529
Backslash, at end of line, 1038
different forms of, 191
inside strings, 415
\[Backslash] ( ), 191, 985, 1002, 1355
\backslash (TEX), \[Backslash] ( ), 1002
Backslash notations, 462
Backslash sequences, activating, 177
Backtab indicator, \[LeftArrowBar] ( ),
1006
Bags, saving expressions in, Sow, 355, 1286
Band structure calculations, MathieuS, 789,
1207
Band-diagonal matrices, SparseArray, 297,
1287
Banded matrices, ListConvolve, 937, 1200
Bang, Factorial (!), 31, 757, 1143
Not (!), 87, 1221
Bar, as diacritical mark, 998
input of, 188
vertical, \[VerticalBar] ( ), 1005
vertical (|), Alternatives, 269, 1079
vertical (||), Or, 87, 1233
\bar (TEX), OverBar, 472, 989
Barbed arrow, \[RightVector] ( ), 1007
BarChart, 168
Barnes extended hypergeometric function,
HypergeometricPFQ, 781, 1172
Barred characters, AdjustmentBox, 455,
1078
Base directories, 1063
setting, 1055
BASE environment variables, 1055
$BaseDirectory, 637, 1064, 1325
BaseForm, 438, 725, 1088
Baseline, of expressions, 451
of GridBox, GridBaseline, 449, 1166
of inline cells, CellBaseline, 605, 1097
Baseline, 451
\baselineskip (TEX), LineSpacing, 611,
1196
Bases, for numbers, 725
for printing of numbers, 438
numbers in various, 1021
numbers in various, IntegerDigits, 725,
1181
numbers in various, RealDigits, 725,
1258
Basic Input palette, 14
Basis, Grobner,
Index
1411
BLAS, 1069
Blob, Disk, 496, 1125
during input, ShowCursorTracker, 613,
1072, 1281
Blobs, in buttons, 55
Blochs Theorem, 789
Block, 389, 391, 1091
Block matrices, Take, 898, 1301
Blocking, in MathLink, 701
Blocking lists, Partition, 128, 292, 1240
Blocks, compared with modules, 391
in arrays, Partition, 130, 1240
Blocks (procedures), 111
Module, 378, 1213
Blue, 500
BMP, exporting, Export, 568, 1141
importing, Import, 570, 1176
Bocharov techniques, DSolve, 1071, 1129
Boilerplate, for MathLink programs, 659
Bold fonts, 444, 558, 612
Boldface, FontWeight, 444, 612, 1152
\boldmath (TEX), FontWeight, 444, 612,
1152
Book style definitions, 602
Books, of integrals, 864
Boolean expressions, 86, 87
evaluation in, 347, 1046
expansion of, LogicalExpand, 87, 1203
input of, 1033
Boolean satisfiability, FindInstance, 845,
1147
Boolean tests, Equal (==), 84, 1135
Booleans, 817, 1091
Boot time, network licenses and, 1058
Borders of polygons in three dimensions,
EdgeForm, 528, 1130
\bot (TEX), \[UpTee] ( ), 1007
Bottom, 451
Bottom of an expression, 451
Bottom of fraction, Denominator, 74, 1120
Bottom parenthesis, \[UnderParenthesis]
( ), 997
Bound variables, in pure functions, 249
scoping of, 385
Boundary conditions, for NDSolve, 962
in differential equations, 871
in rules, 310
Bounding box, in three-dimensional
graphics, 530, 531
in two-dimensional graphics, 507
Bounding sphere, 536
Box, around expression, FrameBox, 446,
1156
\[Square] ( ), 1002
Box coordinate system, 535
Box options, setting globally, 615
BoxAutoDelete, 448
BoxBaselineShift, 455
BoxData, 600
Boxed, 151, 549, 1091
Boxel, Cuboid, 524, 1116
1412
Boxes, 444
around cells, CellFrame, 604, 1098
around two-dimensional plots, Frame,
134, 511, 514, 1155
converting to, ToBoxes, 428, 464, 1307
displaying, DisplayForm, 445, 1126
entering raw, 463
for representing textual forms, 427
in book style, 602
in strings, 461, 1020
input forms for, 462
pasting of, 461
raw, 461
representation by strings, 460
sequence of, RowBox, 445, 1267
BoxMargins, 455
BoxRatios, 531, 1091
for SurfaceGraphics, 531
BoxStyle, 503, 550, 1091
Bra, \[LeftAngleBracket] ( ), 1002
Brace, horizontal, \[UnderBrace] ( ), 997
\brace (TEX), GridBox, 445, 1167
Braces, 42, 1022
colored, ShowAutoStyles, 613, 1280
\brack (TEX), GridBox, 445, 1167
Bracket, horizontal, \[UnderBracket] ( ),
997
Bracketed objects, 1021
Brackets, 42, 1021
advantages of square, 35
cell, 49
cell, ShowCellBracket, 604, 1280
colored, ShowAutoStyles, 613, 1280
double, 42, 1023
flashing of, DelimiterFlashTime, 613,
1120
reading data containing,
RecordSeparators, 648, 1259
square, 31, 1023
types of, 42, 1021
Branch, If, 345, 1173
in programs, 1046
Branch cuts, 762
Branches, in expression trees, 237
Break, 353, 1092
\break (TEX), \[NewLine], 460
Break (interrupt), 62
Break loops, dialogs, 707
Breaking, of output lines, PageWidth, 635,
1237
of pages in output, 609
Breaking of words, Hyphenation, 609, 1173
Breakpoints, in MathLink programs, 691
Breaks, in strings, 415
inhibiting line, \[NoBreak], 459
Brent-McMillan algorithm, EulerGamma,
1067, 1136
Brents method, FindRoot, 1068, 1149
\[Breve] ( ), 999, 1355
Breve mark, 998
Brightness, GrayLevel, 499, 1165
Bromwich integral,
Index
Index
1413
CD players, 172
CDF, inverse, Quantile, 925, 1253
CDF, 794, 795
\cdot (TEX), \[CenterDot] ( # ), 1002
\cdots (TEX), \[CenterEllipsis] ( ),
997
cdr, Rest, 123, 1264
\[Cedilla] ( ), 999, 1360
Ceiling, 745, 1096
implementation of, 1067
Cell, 572, 599, 1097
Cell array, Raster, 492, 497, 1255
Cell brackets, 49
ShowCellBracket, 604, 1280
CellArray (Version 1 function), see
Raster, 1402
CellAutoOverwrite, 608, 1097
CellBaseline, 605, 1097
CellContents, 582
CellDingbat, 604, 1098
CellEditDuplicate, 607, 1098
CellElementSpacings, 605
CellEvaluationDuplicate, 608, 1098
CellFrame, 574, 604, 1098
CellFrameMargins, 605, 1098
CellGroup, 582
CellGroupData, 600, 1098
CellGrouping, 577, 618, 1099
CellLabel, 584, 607, 1099
CellLabelAutoDelete, 607, 1099
CellMargins, 605, 1099
CellOpen, 604, 1099
CellPrint, 575, 1100
Cells, active, 54
adding new, CellPrint, 575, 1100
as Mathematica expressions, 572
entering raw form of, 572
groups of, 51
in notebooks, 49
in solution sets, 846
initialization, 205
labels for, 50
options for, 574
styles of, 52
CellStyle, 584
CellTags, 574, 584, 607, 1100
Cellular automata, vii
programs for, 18
Random, 1067, 1254
CellularAutomaton, 942, 944, 945, 946,
949, 1101
implementation of, 1069
\[Cent] ( ), 994, 1360
Center, 442, 450
\[CenterDot] ( # ), 985, 1002, 1360
\centerdot (TEX), \[CenterDot] ( # ),
1002
\[CenterEllipsis] ( ), 997, 1360
Centering, in tables, TableForm, 442, 1299
of text, TextJustification, 610, 1303
of three-dimensional image, ViewCenter,
534, 1318
1359
` ), 998, 1359
\[CapitalUGrave] ( U
), 998, 1359
\[CapitalUHat] ( U
\[CapitalUpsilon] ( ), 175, 990, 1360
\[CapitalXi] ( ! ), 175, 990, 1360
\[CapitalYAcute] ( ), 998, 1360
\[CapitalZeta] ( " ), 990, 1360
Captions, in tables, TableHeadings, 443,
1300
Capturing images, Import, 570, 1176
Cardanos formula, 820
Cards, suits of, 996
Caret, double, 725
Power (^), 29, 1248
\[Wedge] ( ), 1002
CarmichaelLambda, 752, 1096
Carry, add without, BitXor, 756, 1090
Cartesian coordinates, 97
Cartesian form, 813
Cartesian products, Outer, 902, 1234
CAs, CellularAutomaton, 942, 1101
Cascade, FoldList, 243, 1151
Cascade hyperons, 991
Case independence, in string operations,
410
Case sensitivity, 31, 40, 1014
in string matching, 412
Cases, Switch, 345, 1298
Cases, 261, 284, 1096
level specification in, 262, 1041
\cases (TEX), GridBox, 445, 1167
Cat, example of image processing, 9
cat Unix command, 630
Catalan, 765, 1096
implementation of, 1067
Catalan beta function, LerchPhi, 773, 1193
Catalan constant, Catalan, 765, 1096
Catalan numbers, 757
Catalog, Names, 403, 1215
Catastrophe theory, GroebnerBasis, 805,
1168
Catch, 350, 1096
Catching, of aborts, CheckAbort, 371, 1103
\catcode (TEX), ToCharacterCode, 417,
1307
Catenating lists, Join, 126, 1190
Catenating strings, StringJoin (<>), 407,
1291
Cauchy principal value, PrincipalValue,
866, 1251
Cauchys Theorem, 955
residues for, 895
Causal signals, UnitStep, 879, 1316
\[CCedilla] ( c ), 190, 998, 1360
cd, SetDirectory, 206, 636, 1278
1414
of three-dimensional object,
SphericalRegion, 536, 1287
of three-dimensional object, ViewCenter,
534, 1318
Central Limit Theorem, 794
Central moments,
CharacteristicFunction, 795
Central value, Median, 109, 924, 1209
CForm, 213, 425, 1101
\[CHacek] ( c ), 190, 998, 1360
Chain rule, 80, 855
Chains of assignments, 313
Change directory, SetDirectory, 206, 636,
1278
Changes, since earlier editions, 1402
Changing parts, of lists, 285
of lists, ReplacePart, 125, 288, 1263
Channels, for output, 633, 705
Chaos theory, 979
Chaotic attractor, solving equations for, 968
Chapters, in notebooks, 51
\char (TEX), FromCharacterCode, 417,
1157
char * C type, 679
Character, end-of-file, 706
Character, 582, 646, 1101
Character codes, 417
in MathLink, 679
Character encoding, in MathLink, 679
Character names, conventions for, 985, 1352
Character sets, $CharacterEncoding, 420,
1327
Character strings, 406, 1017
CharacterEncoding, 421, 422, 634, 1102
$CharacterEncoding, 420, 421, 422, 1327
Characteristic function, UnitStep, 879, 1316
CharacteristicFunction, 794, 795
CharacteristicPolynomial, 905, 910,
1102
CharacterRange, 413, 417, 418, 1102
Characters, extensible, 456
minimum size of, ScriptMinSize, 457,
1272
number in output lines, PageWidth, 634,
1237
on keyboard, xv
reading from files, 646
replacement of, StringReplace, 410,
1292
searching for, StringPosition, 409, 1292
sizes of in graphics, 558
special, 414
tests on, 413
Characters, 412, 1102
Chasing method, NDSolve, 1068, 1216
Chebyshev functions, ChebyshevT, 778,
1102
ChebyshevT, 766, 768, 778, 1102
ChebyshevU, 766, 1102
Check, \[Hacek] ( ), 999
Check, 481, 482, 742, 1102
CheckAbort, 371, 1103
Centering \[Colon]
Index
Index
1415
1416
Index
DOSTextFormat,
1054
Index
Conversions \[Dalet]
\[CounterClockwiseContourIntegral]
(
), 1000, 1362
Coupled map lattices, CellularAutomaton,
946, 1101
Courier fonts, 444, 558, 612
FontFamily, 612, 1151
Covariant indices, 915
Covering, multiple of surfaces, 167
CPU ID, $MachineID, 718, 1331
CPU time, TimeUsed, 710, 1306
CPU type, $ProcessorType, 717, 1336
Cramers rule, 907
Crashing, due to out of memory, 75, 713
Create Automatic Numbering Object menu item,
202
Create Button menu item, 595
Create link, LinkCreate, 680, 1197
Create notebook, NotebookCreate, 591,
1222
CreateDirectory, 641, 1116
Creation of symbols, 404
context for, 395
$CreationDate, 717, 1328
Criteria, finding elements based on, Cases,
261, 1096
for applicability of patterns, Condition
(/;), 265, 1111
on parameters, Assumptions, 867, 1084
selection based on, Select, 251, 1273
Critical line for zeta function, 772
Critical section, AbortProtect, 371, 1075
crontab file, 1058
Cross, 119, 1116
\[Cross] ( / ), 183, 985, 1000, 1362
Cross-platform MathLink programs, 676
Csc, 761, 1116
Csch, 761, 1116
CSV format, exporting, Export, 208, 642,
1141
importing, Import, 208, 642, 1176
Cube, Cuboid, 524, 1116
Cubic equations, 820
Cuboid, 520, 524, 1116
Cumulative distribution function, CDF, 795
Cumulative sums, FoldList, 243, 1151
Cunningham functions,
Hypergeometric1F1, 779, 1171
\[Cup] ( ), 1002, 1362
\cup (TEX), \[Union] ( ), 1002, 1315
Cup accent, 998
Cup product, \[Cup] ( ), 1002
Cup symbol, \[Union] ( ), 1002, 1315
\[CupCap] ( ), 1003, 1362
Curl, 97
Curly braces, 42, 1022
\[CurlyCapitalUpsilon] ( 0 ), 990, 1362
1417
1418
Index
self-referential, 370
taking from packages, Remove, 59, 1261
use of in evaluation, 325, 332
Degree, of polynomial, Exponent, 73, 1138
Degree, 32, 761, 765, 1119
\[Degree] ( 5 ), 182, 994, 1363
Del, Grad, 97
\[Del] ( 6 ), 994, 1000, 1363
del DOS command, DeleteFile, 641, 1120
Delayed definitions, SetDelayed (:=), 311,
1278
Delayed rules, RuleDelayed (:>), 314, 1269
Deletable, 448, 607, 619, 1119
Delete, 125, 288, 1119
Delete old output, CellAutoOverwrite,
608, 1097
DeleteCases, 262, 1120
DeleteContents, 641
DeleteDirectory, 641, 1120
DeleteFile, 206, 641, 1120
Deleting, in notebooks, NotebookDelete,
585, 1222
in strings, StringDrop, 407, 1291
Deleting elements, from lists, Delete, 125,
288, 1119
from lists, Drop, 123, 287, 1128
from lists, Select, 251, 1273
Deleting functions, Clear, 110, 1103
Deleting objects, 1052
Deleting symbols, Clear, 304, 1103
Deleting values, Unset (=.), 39, 1316
DeletionWarning, 448
Delimiter characters, 1002
DelimiterFlashTime, 613, 1120
Delimiters, in Mathematica syntax, 470
RecordSeparators, 647, 1259
types of, 42
WordSeparators, 646, 1323
Delta, discrete, DiscreteDelta, 882, 1125
Kronecker, KroneckerDelta, 749, 882,
1190
\[Delta] ( ), 175, 990, 1363
Delta function, DiracDelta, 879, 1124
Equal (==), 84, 1135
Demon, Mathematica, 1058
Denominator, 74, 1120
Denominators, collecting over common,
Together, 69, 70, 802, 1308
expansion of, ExpandAll, 69, 1138
expansion of, ExpandDenominator, 801,
1138
Density, of gray, GrayLevel, 499, 1165
Density map, Raster, 492, 497, 1255
Density of lines, ImageResolution, 569,
1174
Density plots, 517
color in, 517
converting, 157
from lists, ListDensityPlot, 159, 1201
DensityGraphics, 487, 517, 1121
DensityPlot, 146, 487, 517, 1121
Dependence, on computer systems, 46
Index
Dependencies Directory
Diagrams, 486
examples of, 11
\diagup (TEX), \[RawSlash] ( / ), 1010
Dialog, 707, 1122
Dialog boxes, 478
buttons in, 452
creating, 598
windows for, 621
Dialog settings, for front end, 622
DialogIndent, 708
DialogProlog, 708, 1123
Dialogs, 26, 367, 707
contexts in, 401
in tracing, 366
local variables in, 382
nested, 708
DialogSymbols, 708, 1123
\[Diameter] ( ' ), 996, 1363
\[Diamond] ( 8 ), 1002, 1363
\[DiamondSuit] ( 9 ), 996, 1363
DICOM, exporting, Export, 568, 1141
importing, Import, 568, 570, 1176
Dictionaries, spelling, 1072
Dictionary, analysis of words in, 9
Diereses, 998
Difference equations, RSolve, 96, 891, 1269
Difference-algebraic equations, RSolve, 891,
1071, 1269
Differences, as inverse of sums, 890
Differentation, of InterpolatingFunction
objects, 932
Differential, Dt, 80, 854, 1129
total, Dt, 855, 1129
Differential equations, Bessel, BesselJ, 776,
1088
numerical solution of, NDSolve, 105, 961,
1216
partial, DSolve, 874, 1129
partial, NDSolve, 970, 1216
plotting solutions to, 105, 133
representation of, 93
symbolic solution of, DSolve, 93, 869,
1129
undetermined coefficients in, C, 93, 871,
1095
Differential-algebraic equations, DSolve,
873, 1071, 1129
NDSolve, 969, 1216
\[DifferentialD] ( 4 ), 184, 185, 984, 994,
1000, 1363
Differentiation, 79, 80, 853
as a functional operation, 856
constant functions in, 855
constants in, Constant, 854, 1111
implicit dependencies in, NonConstants,
853, 1220
numerical, 791
of integrals, 869
of power series, 886
partial, D, 853, 1117
total, 854
variables in, 853
1419
1420
DirectoryName \[DownBreve]
Index
Index
Downvalues, 316
in evaluation, 334
DownValues, 322, 1052, 1128
Downward motion, in input, 177
Drafting lines, GridLines, 515, 1167
DragAndDrop, 615, 1128
Draw programs, input for, Import, 570,
1176
output for, Export, 568, 1141
Drawing format, exporting, Export, 569,
1141
importing, Import, 570, 1176
Drop, 123, 287, 1128
Dropping parts of expressions in printing,
Shallow, 432, 1279
DSolve, 93, 869, 871, 872, 873, 874, 875,
951, 1071, 1129
implementation of, 1071
Dt, 80, 854, 855, 1129
Duffing equation, 981
Dull surfaces, 547
Dummy variables, 110, 259, 387
in differential equations, 870
in differentiation, 856
Dump files, 1053
DumpSave, 627, 1129
Duplicate, expression in MathLink,
MLCreateMark(), 693, 1341
Duplicates, removal of in lists, Union, 127,
1315
Duplicating files, CopyFile, 641, 1114
Duplication-on-edit, CellEditDuplicate,
607, 1098
Dwights tables, Integrate, 864, 1182
DXF format, exporting, Export, 569, 1141
importing, Import, 570, 1176
Dyadic products, Outer, 918, 1234
Dyads, List, 118, 1199
Dynamic graphics, 170, 617
Dynamic programming, 314
Dynamic scoping, Block, 391, 1091
Dynamical systems theory, 979
1421
1422
Index
Index
1423
1424
Explode Factoring
display of large, 74
elements of, Part, 234, 1238
evaluation of, 324, 1045
exchanging with external programs, 628
for notebooks, 578
in MathLink, 669
indices in, 1040
input, In, 702, 1177
input of, 48, 1021
internal storage of, 221
interpretations of, 231
lambda, Function (&), 249, 1159
levels in, 237, 1041
manipulation like lists, 236
nested, 234
ordering in, Ordering, 255, 1233
output, Out (%), 702, 1234
output of, 425
parts in algebraic, 234
parts of, Part, 234, 1040, 1238
patterns as classes of, 259
patterns for common types of, 278
pieces of algebraic, 73
rational, 69
reading without evaluation, 649
reduction to standard form of, 325
replacing parts in, ReplacePart, 235,
1263
resetting parts of, 235
selecting parts based on criteria, Select,
251, 1273
sharing common parts of, Share, 714,
1279
simplification of, Simplify, 68, 813,
1282
size of, ByteCount, 714, 1095
special input forms for, 232, 1023
storing in external programs, 692
structural operations on, 254
structure of, 237
symbols in, 1041
testing properties of, 267
transforming, 69
traversal of, 1041
trigonometric, 811
types of, 232
writing to streams, Write, 632, 1324
ExpToTrig, 71, 812, 1141
Extend selection, 180
SelectionMove, 582, 1275
Extended character sets, 421
Extended Unix code, 421
ExtendedGCD, 752, 753, 1141
Extensible characters, 456
Extension, 809, 1142
Extensions, field, 809
file name, 1053
Extensions (packages), 59
Exterior faces of three-dimensional objects,
529
Exterior product, \[Wedge] ( ), 1002
Exterior products, Outer, 902, 1234
Index
Index
displaying, 204
encoding of, 626
end of, EndOfFile, 649, 1134
exporting data to, Export, 642, 1141
finding, FileNames, 206, 638, 1145
importing data from, Import, 642, 1176
list of loaded, $Packages, 397, 1335
list of open, Streams, 705, 1290
modification dates for, FileDate, 641,
1145
moving, RenameFile, 641, 1262
names on different computer systems,
207, 639, 1053
naming of, 636
of messages, 482
positions in, StreamPosition, 653, 1290
random access to, SetStreamPosition,
653, 1279
reading data from, Import, 207, 1176
reading data from, ReadList, 644, 1257
reading from, Get (<<), 204, 623, 1162
reading into strings, 655
removing, DeleteFile, 206, 1120
renaming, RenameFile, 641, 1262
search path for, $Path, 206, 637, 1335
searching, 650
splicing into, Splice, 214, 1288
start up, 1056
superscripts in, 177
syntax errors in, 623
system, 1061
turning into strings, ReadList, 647, 1257
types of, FileType, 641, 1145
writing data to, Export, 207, 1141
writing to, Put (>>), 204, 624, 1253
FileType, 641, 1145
Filled boxes, \[SelectionPlaceholder]
( ), 1008
Filled region, Polygon, 492, 1245
\[FilledCircle] ( ) ), 995, 1369
\[FilledDiamond] ( ), 995, 1369
\[FilledDownTriangle] ( A ), 995, 1369
\[FilledRectangle] ( > ), 995, 1369
\[FilledSmallCircle] (
), 995, 1369
\[FilledSmallSquare] ( N ), 995, 1370
\[FilledSquare] ( * ), 995, 1370
\[FilledUpTriangle] ( B ), 995, 1370
\[FilledVerySmallSquare] ( C ), 995, 1370
Filter, external, RunThrough, 630, 1270
Filtering, of data, ListConvolve, 937, 1200
of data read from files,
RecordSeparators, 648, 1259
Filtering lists, Select, 251, 1273
\[FinalSigma] ( O ), 990, 1370
Find, in notebooks, NotebookFind, 584,
1223
Find, 652, 656, 1146
find in Unix, FileNames, 638, 1145
Find link, LinkConnect, 680, 1197
FindFit, 108, 929, 1146
implementation of, 1069
FindInstance, 838, 844, 845, 1147
1425
1426
Floating-point decomposition,
MantissaExponent, 726, 1204
Floating-point hardware, 738
Floating-point numbers, in MathLink, 678
Real, 722, 1258
Floor, 745, 1150
implementation of, 1067
Floquets Theorem, 789
Flow of control, 348
Fluid variables, Block, 389, 1091
Flush left, TextAlignment, 610, 1303
Flush right, TextAlignment, 610, 1303
Fluxion notation, 188
Focus notebook, SelectedNotebook, 579,
1273
Fold, 243, 1151
Folded polygons, 495
Folded surfaces, 537
Folders (directories), 206, 636
operations on, 641
FoldList, 243, 250, 1151
Font, symbol, 422
Font encodings, CharacterEncoding, 421,
1102
Font matching, 1010
Font options, 609
Font size, 453
FontColor, 444, 612, 1151
FontFamily, 444, 558, 612, 1151
FontPostScriptName, 612
FontProperties, 613
Fonts, for plot labels, StyleForm, 558, 1295
for special characters, 613
for text in graphics, 558
in output, StyleForm, 443, 1295
searching for, 612
sizes of, 558
FontSize, 444, 558, 574, 612, 1151
FontSlant, 444, 612, 1151
FontSubstitutions, 612, 1152
FontTracking, 612, 1152
FontWeight, 444, 558, 612, 1152
For, 352, 1152
ForAll, 847, 1152
\[ForAll] ( P ), 1001, 1370
Forcing, page breaks, 609
Forcing evaluation, Evaluate, 337, 1136
Foreign characters, 190, 421, 998
Foreign data, exporting, Export, 208, 642,
1141
importing, Import, 208, 642, 1176
reading, Import, 207, 1176
writing, Export, 207, 1141
Foreign keyboard, xv
Fork, Run, 629, 1269
Formal logic, operations in, 86
pure functions in, 249
Formal manipulation, 63
Formal parameters, in pure functions, 249
scoping of, 385
Formal power series, ZTransform, 879,
1325
Index
Index
1427
1428
Index
Index
1429
1430
Index
Index
dummy, 387
finding, Position, 124, 261, 1247
in expressions, 234
manipulating lists by, 285
of expression parts, 1014
of list elements, 41
part subscript, 184
parts with given number of (levels), 238
permutation of, Transpose, 917, 1313
Inequalities, 835
linear, 975
linear, Minimize, 851, 1212
on parameters, Assumptions, 867, 1084
reducing, Reduce, 92, 1261
Inequality, Unequal (!=), 86, 1315
Inequality, 1033
Inequivalence, logical, Xor, 87, 1324
Inert forms, Hold, 336, 1169
of symbols, 402
Inert functions, Remove, 59, 1261
Infeasible constraints, Minimize, 852, 1212
Inferences, 268
about parameters, Assumptions, 867,
1084
Infimum, Min, 31, 745, 1212
Infinite evaluation, 324
Infinite recursion, 369
Infinite results, 742
Infinity, complex, 743
complex direction of, 743
Infinity, 32, 238, 743, 765, 1177
\[Infinity] ( Z ), 182, 988, 994, 1373
Infix, 474, 1177
Infix notation, 233
Infix operators, 468
Information, about user-defined functions,
110
on functions, 484
on symbols, 484
product, $ProductInformation, 717,
1336
Information, 58, 1038, 1178
\infty (TEX), \[Infinity] ( Z ), 994, 1177
Inheritance, of cell options, 600
Inhibiting, evaluation, 336
line breaks, \[NoBreak], 459
output, 43
page breaks, 609
Inhomogeneous differential equations,
DSolve, 871, 1129
init.m files, 640, 1056, 1065
Initial conditions, for NDSolve, 962
Initial values, in modules, 379
$InitialDirectory, 637, 1330
Initialization, 1056
of front end, 1038
of kernel, 1063
of random number generator,
SeedRandom, 747, 1273
Initialization cells, 205
Initialization files, 1065
for packages, 640, 1065
Indices Integration
1431
1432
Integration JacobiSN
InverseJacobiSN, InverseJacobiCN,
..., 785, 1188
InverseLaplaceTransform, 96, 875, 1188
Inverses in finite fields, PowerMod, 752,
1248
Index
characters, 1008
contents, ShowContents, 455
notebooks, 592
selection, ShowSelection, 619,
Index
1433
1434
Index
Index
1435
1436
Index
Index
1437
1438
Matrices Mistakes
Index
Index
1439
1440
Index
$NetworkLicense, 718
Index
1441
1442
Index
O, 885, 1230
\O (TEX), \[CapitalOSlash] ( ), 998
\o (TEX), \[OSlash] ( ), 998
\[OAcute] ( o ), 998, 1384
Object type, 232
Object-oriented programming, 319
Objective functions, Minimize, 850, 1212
NMinimize, 974, 1220
Objects, alphabetical listing of all built-in,
1073
defining values for, 308
definitions for, 319
notebook, NotebookObject, 579, 1224
strings as, 655
variables as, 378
Oblique, FontSlant, 444, 612, 1151
Oblique fonts, 444, 558, 612
Ocelot image, 570
Octal codes, for characters, 418
Octal digits, IntegerDigits, 725, 1181
Octal numbers, 438, 725, 1021
Octet encodings, 422
Octothorp (#), Slot, 249, 1284
Odd numbers, testing for, OddQ, 267,
1230
OddQ, 267, 723, 1230
ODEs, numerical, NDSolve, 105, 961, 1216
symbolic, DSolve, 93, 869, 1129
\odot (TEX), \[CircleDot] ( ), 1002
\[ODoubleAcute] ( o ), 998, 1384
\[ODoubleDot] ( o ), 190, 998, 1384
Off, 61, 404, 479, 1230
Offset, 506, 507, 1230
Offsets, in graphics, 506
\[OGrave] ( o` ), 190, 998, 1384
\[OHat] ( o ), 998, 1384
Ohm, \[Mho] ( ), 994
\oint (TEX), \[ContourIntegral] ( ),
1000
Old English, characters in, 999
\[Omega] ( ), 175, 990, 1384
Omega-pi, \[CurlyPi] ( 2 ), 990
\[Omicron] ( ), 990, 1384
\ominus (TEX), \[CircleMinus] ( ),
1002
Omitted arguments, 274
Omitted elements, \[Ellipsis] ( + ), 996
Omitted terms, 75
On, 61, 404, 479, 1230
On top, input, 188
On top, overscript, 180
OverscriptBox, 445, 1235
One-line output, Short, 75, 1280
One-origin arrays, Mod, 749, 1213
One-sided functions, UnitStep, 879, 1316
OneIdentity, 271, 272, 329, 1050, 1231
Ones, number of, DigitCount, 755, 1123
Opaque ink, 494
Opcodes, in compiled code, 377
Open, notebook, NotebookOpen, 578,
1224
Open architecture, of Mathematica, 657
Index
Open
Open
Open
Open
1443
1444
Overflow Parts
Index
Index
1445
1446
Index
Polynomials, 797
algebraic operations on, 803
Bernoulli, BernoulliB, 758, 1088
canonical forms, 326
coefficients in, Coefficient, 799, 1105
construction from power series of, 888
cyclotomic, Cyclotomic, 807, 1116
decomposition of, Decompose, 807, 1118
degree of, Exponent, 799, 1138
division of, PolynomialQuotient, 803,
1247
Euler, EulerE, 758, 1135
expansion of, Expand, 797, 1137
exponential, 825
factoring of, Factor, 797, 1143
Fibonacci, Fibonacci, 758, 1144
finding structure of, 799
GCD of, PolynomialGCD, 804, 1246
Gegenbauer, GegenbauerC, 766, 1161
Hermite, HermiteH, 766, 1169
inequalities involving, 835
JacobiP, JacobiP, 766, 1189
Laguerre, LaguerreL, 766, 1191
Legendre, LegendreP, 766, 1192
making lists of factors in, FactorList,
806, 1143
modulo primes, 809
nested, Decompose, 807, 1118
number of roots of, 823
orthogonal, 766
over algebraic number fields, 809
patterns for, 279
pieces of, 73, 74
rearranging, Collect, 797, 1106
restrictions on, 803
resultants of, Resultant, 805, 1264
structural operations on, 797
testing for, PolynomialQ, 267, 1246
variables in, Variables, 799, 1318
with complex coefficients, 807
Polytopes, three-dimensional, 524
Pomeron, \[DoubleStruckCapitalP] ( ),
992
Population count, DigitCount, 755, 1123
Portability, of character encodings, 421
of file names, 639
of Mathematica, 46
of MathLink programs, 676
Portable anymap format, exporting,
Export, 568, 1141
importing, Import, 570, 1176
Portable bitmap format, exporting, Export,
568, 1141
importing, Import, 570, 1176
Portable computers, styles for,
ScreenStyleEnvironment, 197, 1272
Portable graymap format, exporting,
Export, 568, 1141
importing, Import, 570, 1176
Portable pixmap format, exporting, Export,
568, 1141
importing, Import, 570, 1176
Index
1447
1448
Index
Index
1449
1450
Record ReturnExpressionPacket
Index
Index
\[ReturnIndicator] Rules
1451
1452
Rules SelectedNotebook
Index
\[ScriptCapitalL] ( ), 992
\[ScriptCapitalZ] ( ), 993, 1393
\[ScriptL] ( ), 192, 992
ScriptMinSize, 457, 1272
Scripts, for front end,
FrontEndTokenExecute, 593
Scripts (packages), 59
\scriptscriptstyle (TEX),
ScriptSizeMultipliers, 457, 1272
ScriptSizeMultipliers, 457, 1272
\scriptstyle (TEX),
ScriptSizeMultipliers, 457, 1272
\[ScriptZ] ( ), 993, 1393
Scroll notebook, SelectionMove, 582, 1275
Scrolling back, 38
sdb, 691
SDTS importing, Import, 208, 1176
Seams between polygons in three
dimensions, EdgeForm, 528, 1130
Search, for files, FileNames, 638, 1145
for parts, Position, 124, 261, 1247
for substrings, StringPosition, 409,
1292
in notebooks, NotebookFind, 584, 1223
Search path, context, $ContextPath, 394,
1327
for files, $Path, 206, 637, 1335
Searching, for sublists, ReplaceList, 263,
302, 1263
in files, FindList, 207, 650, 1147
in strings, 654
IntervalMemberQ, 741, 1184
\searrow (TEX), \[LowerRightArrow] ( 6 ),
1006
Sec, 761, 1273
Secant method, FindRoot, 1068, 1149
Sech, 761, 1273
Second, Date, 709, 1117
Timing, 711, 1306
Seconds, \[DoublePrime] ( A ), 996
Section, Module, 378, 1213
\[Section] ( ), 996, 1393
Section style, 573
Sections, in notebooks, 51
numbering of, 202
Security, Protect, 321, 1044, 1252
ReadProtected, 330, 1258
Seeding of random generator, SeedRandom,
748, 1273
SeedRandom, 747, 748, 1273
Seek, in files, SetStreamPosition, 653,
1279
in MathLink, MLSeekMark(), 693, 1350
in notebooks, NotebookFind, 584, 1223
Segments, of circles, Disk, 496, 1125
Select, 251, 261, 284, 1273
Selectability, of windows,
WindowClickSelect, 620, 1321
Selectable, 448, 607, 619, 1273
Selected notebook, setting,
SetSelectedNotebook, 591, 1279
SelectedNotebook, 579, 1273
Index
1453
1454
Signals Sounds
Index
Index
1455
1456
Index
Index
Subscript Syntax
1457
Symbolic computation, 63
compared with numerical, 63
Symbolic conditions, 346
Symbolic dynamics, 979
Symbolic expressions, 230
Symbolic frequency analysis,
ComplexExpand, 812, 1110
Symbolic manipulation, of programs, 338
Symbolic mathematics, 79
packages for, 97
Symbolic operators, 471
Symbolic sums, Sum, 83, 890, 1296
Symbolic systems, functional operations in,
241
truth values in, 346
Symbolic vectors, 120
SymbolicXML, exporting, Export, 212, 1141
importing, Import, 212, 1176
SymbolName, 402, 1298
Symbols, 1014
alphabetical listing of all built-in, 1073
as tags, 78, 232
attributes of, 327
built in, 1014
choosing names for, 304
clearing, Clear, 304, 1103
clearing values of, Unset (=.), 39, 1052,
1316
compared to strings, 406
contexts of, 1015
created by Module, 381
creation of, 1015
defining, Set (=), 39, 1277
full names of, 392
in packages, 397
information about, 58
intercepting creation of, 404
internal, 1014
making lists of, Names, 403, 1215
names of, 40, 392, 1014
naming conventions for, 1014
printing of contexts for, 395, 401, 1016
removing completely, Remove, 395, 1261
scoping of, 378
searching for, Names, 403, 1215
stub, 402
unique, Unique, 382, 1316
user defined, 1014
values for, 64
Symmetric functions, 254
in patterns, 270
Symmetric polynomials, construction of, 833
Symmetry, in Fourier transforms, 936
of extensible characters, SpanSymmetric,
456
Symmetry reduction, DSolve, 1071, 1129
RSolve, 1071, 1269
Symplectic integrators, NDSolve, 1216
Synchronization, of programs, LinkReadyQ,
681, 1198
Syntax, in notebook files, 1038
redefining, 475
1458
,
of integrals, 864
of special functions, 791
plotting, ListPlot, 159, 1202
TableSpacing, 442, 1300
Tabs, in strings, 415
Tabular data, exporting, Export, 208, 642,
1141
importing, Import, 208, 642, 1176
reading, Import, 207, 1176
writing, Export, 207, 1141
Tabulation, 439
Tabulation of values, Table, 115, 1299
Tack, \[RightTee] ( F ), 1001
TagBox, 447, 1300
Tagged data, 78
Tags, for expressions, 232
for Sow, Sow, 355, 1286
in cells, CellTags, 607, 1100
in definitions, 319
in TraditionalForm, 195
including in levels, Heads, 238, 1169
tracing based on, Trace, 359, 1310
TagSet, 319, 1029, 1051, 1300
TagSetDelayed, 319, 1029, 1300
TagUnset, 1029, 1052, 1301
Tail area, CDF, 795
Tailed rho, \[CurlyRho] ( " ), 990
Take, 123, 236, 287, 898, 941, 1301
Taking, of definitions, Remove, 59, 1261
Tan, 31, 761, 1301
simplification to, TrigFactorList, 812,
1314
Tanh, 761, 1301
Target notebook, InputNotebook, 579, 1179
TargetFunctions, 813
\[Tau] ( ), 175, 990, 1396
Tautology, \[DoubleRightTee] ( 4 ), 1001
Taylor series, Series, 94, 883, 1276
TCP ports, 682
TCP protocol, LinkProtocol, 677, 1198
Telephone systems, 172
Telescope, levels in lists, Transpose, 918,
1313
Template strings, 434
Templates, for cells, DefaultNewCellStyle,
619, 1119
MathLink, 659
Templates (patterns), 259
Templates (pure functions), 248
Temporary, 329, 383, 1301
Temporary binding, ReplaceAll (/.), 65,
1263
Temporary files, 629
Temporary values, Block, 389, 1091
Temporary variables, 378
Tensor product, \[CircleTimes] ( ' ), 1002
Tensor products, Outer, 902, 1234
Tensors, 915
antisymmetry in, Signature, 920, 1282
contraction of, Inner, 917, 920, 1178
dimensions of, Dimensions, 916, 1124
formatting of, 440, 916
Index
Index
in equations, 196
in graphics, 134, 556, 560
in tables, TableHeadings, 443, 1300
in three-dimensional graphics, 561
matching size of, Offset, 507, 1230
newlines in, 415
of input, InString, 703, 1180
of messages, 479
operations on, 407, 655
orientation of in graphics, 561
positioning of, 561
reading from files, 646
searching for, FindList, 207, 650, 1147
vertical in plots, RotateLabel, 515, 1266
with embedded formulas, 461
Text, 492, 520, 560, 1303
Text files, in MS-DOS, DOSTextFormat,
1054
Text options, 609
Text resource files, 1062
Text strings, 406, 432, 1017
Text style, 573
Text-based interface, 27, 48
animated graphics in, 170
interactive input with, 478
operating system commands with, 630
test for, $Notebooks, 715, 1334
TextAlignment, 574, 609, 610, 1303
Textbook notation, TraditionalForm, 193,
1313
Textbooks, examples from, 225
TextData, 600
TextJustification, 609, 610, 1303
TextLine, 582
TextListPlot, 168
TextPacket, 684, 700
TextParagraph, 582
TextStyle, 556, 1303
$TextStyle, 556, 1338
Textual analysis, 9
Textual input, 424
Textual output, 424
Then, If, 345, 1173
Theorems, establishing, 816
\[Therefore] ( W ), 191, 1001, 1396
\[Theta] ( ), 175, 990, 1396
Theta function, UnitStep, 879, 1316
Theta functions, 785
EllipticTheta, 786, 1133
Thickness, of fraction bars,
SpanLineThickness, 456
Thickness, 501, 1304
in three dimensions, 525
\[ThickSpace], 454, 1008, 1397
ThinFrame window frame option, 621
\[ThinSpace], 454, 1008, 1397
Third-party packages, loading, 207, 640
\[Thorn] ( ), 998, 1397
Thread, 256, 257, 1304
Threading, of expressions, 256
over lists automatically, Listable, 329,
1199
Text Trace
1459
1460
Index
Index
1461
1006
1462
varargs, 273
varargs Width
combining, 900
components of, 118
differentiation of, 900
elements of, 118
generation of, 119
multiplication by scalar of, 901
multiplication of, Dot (.), 118, 1127
notation for, 472
operations on, 118, 900
patterns for, 280
row, 119, 902
symbolic, 120
testing for, VectorQ, 267, 900, 1318
\[Vee] ( \ ), 191, 985, 1002, 1399
Vel, Or (||), 87, 1233
Verbatim, 278, 1318
Verbatim output, WriteString, 632,
1324
Verbatim PostScript, 554
Verbosity, 61, 479
Verification, of Mathematica, 225
Vernal equinox, 991
Versine, 762
Version, new features in current, x
$Version, 717, 1339
$VersionNumber, 717, 1339
\Vert (TEX), \[DoubleVerticalBar] ( ),
1005
\vert (TEX), \[VerticalBar] ( ), 1005
Vertical alignment, in tables, 442
Vertical bar (|), Alternatives, 269, 1079
Vertical bar (||), Or, 87, 1233
Vertical bar characters, 987
Vertical direction, in three dimensions,
ViewVertical, 534, 1319
Vertical lines, in tables, ColumnLines, 446,
1107
Vertical positioning, in output, 452
\[VerticalBar] ( ), 191, 985, 1005, 1399
\[VerticalEllipsis] ( U ), 997, 1399
\[VerticalLine] ( V ), 997, 1399
VerticalScrollBar window element, 621
\[VerticalSeparator] ( ), 191, 985, 987,
1001, 1400
\[VerticalTilde] ( ), 1002, 1400
\[VeryThinSpace], 454, 1008, 1400
Video output, 170
Vieta formulas, RootSum, 827, 1266
ViewCenter, 533, 534, 1318
Viewing angle, ViewPoint, 152, 532, 1319
ViewPoint, 152, 153, 532, 1319
coordinate system for, 532
ViewVertical, 533, 534, 1319
Vinculum, \[HorizontalLine] ( $ ), 997
Virtual memory, 713
Visible, 620, 1319
Visible selection, ShowSelection, 619,
1281
Visual system, human, 153, 563
Volume element, Cuboid, 524, 1116
Volume integrals, Integrate, 82, 1182
Voxel, Cuboid, 524, 1116
Index
Index
Width $MachineEpsilon
1463
$ symbols, 381
$ variables, in tracing, 364
$Aborted, 371, 1048, 1325
$Assumptions, 818, 1325
$BaseDirectory, 637, 1064, 1325
$BatchInput, 715, 1326
$BatchOutput, 715, 1326
$ByteOrdering, 717, 1326
$CharacterEncoding, 420, 421, 422, 1327
$CommandLine, 716, 1327
$Context, 393, 1015, 1327
$ContextPath, 394, 1015, 1327
$CreationDate, 717, 1328
$CurrentLink, 688, 1328
$Display, 554, 705, 1328
$DisplayFunction, 491, 1328
$Echo, 705, 1328
$Epilog, 706, 709, 1328
$ExportFormats, 208, 1328
$Failed, 623, 1329
$FormatType, 556, 1329
$FrontEnd, 592, 1329
$HistoryLength, 703, 1329
$HomeDirectory, 637, 1329
$IgnoreEOF, 706, 707, 1057, 1329
$ImportFormats, 208, 1329
$InitialDirectory, 637, 1330
$Input, 639, 705, 1330
$Inspector, 1330
$InstallationDate, 717, 1330
$InstallationDirectory, 637, 1061, 1330
$IterationLimit, 369, 1048, 1330
$Language, 483, 706, 1331
$LaunchDirectory, 637
$LicenseExpirationDate, 718
$LicenseID, 718
$LicenseProcesses, 718
$LicenseServer, 718
$Line, 702, 703, 1056, 1331
in dialogs, 708
$Linked, 1331
$MachineDomain, 718, 1331
$MachineEpsilon, 739, 1331
1464
$MATHEMATICA_USERBASE environment
variable, 1055
Index