Tour of Mathematica - Wolfram Language Documentation

Tour of Mathematica
24
1. Numerical Calculations
You can do arithmetic with Mathematica
just as you would on a calculator. You
type the input 5 + 7; Mathematica prints
the result 12.
In 1]:= 5 + 7
Unlike a calculator, however,
Mathematica can give you exact results.
Here is the exact result for 3100 . The ^ is
the Mathematica notation for raising to a
power.
In 2]:= 3 ^ 100
You can use the Mathematica function N
to get approximate numerical results.
The % stands for the last result. The
answer is given in scientific notation.
In 3]:= N%]
You can find numerical results to any
p
degree of precision. This calculates 10
to 50 digits of precision.
In 4]:= N Sqrt10], 50 ]
Mathematica can also handle complex
numbers. Here is (3 + 4i)10 . In
Mathematica,
p I stands for the imaginary
number ;1.
In 5]:= (3 + 4 I) ^ 10
Mathematica can evaluate all standard
mathematical functions. Here is the
value of the Bessel function J0 (14:5).
In 6]:= BesselJ0, 14.5]
Here is a root of J0 (x) near x = 14:5.
In 7]:= FindRootBesselJ0, x], {x, 14.5}]
Out 1]= 12
Out 2]= 515377520732011331036461129765621272702107522001
47
Out 3]= 5.15378 10
Out 4]= 3.1622776601683793319988935444327185337195551393252
Out 5]= -9653287 + 1476984 I
Out 6]= 0.0875449
Out 7]= {x -> 14.9309}
You can calculate mathematical
functions to any precision. This gives
the Riemann zeta function ( 21 + 13i) to
40 digits of precision.
In 8]:= N Zeta 1/2 + 13 I ], 40 ]
You can do numerical integrals.
Here is
R
the numerical value of 0 sin(sin(x))dx.
In 9]:= NIntegrate SinSinx]], {x, 0, Pi} ]
Mathematica can do many kinds of exact
computations with integers.
FactorInteger gives the factors of an
integer.
In 10]:= FactorInteger 70612139395722186 ]
Out 8]= 0.44300478250536818919789744133284912626 0.65548309832116894305136964919133550622 I
Out 9]= 1.78649
Out 10]= {{2, 1}, {3, 2}, {43, 5}, {26684839, 1}}
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
2. Graphics
25
2. Graphics
Here is a plot of the function sin(exp(x)),
with x ranging from 0 to .
In 1]:= Plot Sin Expx] ], {x, 0, Pi} ]
1
0.5
1
0.5
1.5
2
2.5
3
-0.5
-1
Mathematica provides many options that
you can set to determine exactly how
your plots will look.
In 2]:= Show %, Frame -> True,
FrameLabel -> {"Time", "Signal"},
GridLines -> Automatic ]
1
Signal
0.5
0
-0.5
-1
0
0.5
1
1.5
2
2.5
3
Time
This makes a contour plot of the
function sin(x + sin(y)). The lighter areas
are higher.
In 3]:= ContourPlot Sinx + Siny]], {x, -2, 2}, {y, -2, 2} ]
2
Mathematica generates all its graphics in
PostScript, which can be interpreted for
many kinds of displays and printers.
1
0
-1
-2
-2
-1
0
1
2
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
Tour of Mathematica
26
Here is a three-dimensional surface plot
of the same function.
In 4]:= Plot3D Sinx + Siny]], {x, -3, 3}, {y, -3, 3} ]
1
0.5
5
0
-0.5
.5
-1
2
0
-2
0
-2
2
This generates a three-dimensional
parametric surface. The x, y and z
coordinates of points on the surface are
specified as a function of the parameters
t and u. The space in u Sint] denotes
multiplication.
In 5]:= ParametricPlot3D {u Sint], u Cost], t/3},
{t, 0, 15}, {u, -1, 1}, Ticks -> None ]
Here is a more complicated parametric
surface.
In 6]:= ParametricPlot3D
{Sint], Sin2t] Sinu], Sin2t] Cosu]},
{t, -Pi/2, Pi/2}, {u, 0, 2 Pi}, Ticks -> None ]
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
2. Graphics
27
Mathematica allows you to combine
different pieces of graphics together.
The % stands for the last result; the %%
for the last but one result.
In 7]:= Show%, %%]
Mathematica serves as a graphics
language in which you can build up
graphics from components. In this case,
a three-dimensional graphic is built up
from a collection of cubes placed at
different points.
In 8]:= Show Graphics3D
On computer systems with sound
output, this generates an 8-second long
sound with the specified amplitude as a
function of time.
In 9]:= Play Sin10000 / t], {t, -4, 4} ]
{Cuboid{0, 0, 0}], Cuboid{2, 2, 2}],
Cuboid{2, 1, 3}], Cuboid{3, 2, 1}],
Cuboid{2, 1, 1}]} ]]
Out 9]= -Sound-
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
Tour of Mathematica
28
3. Algebra and Calculus
Mathematica can work not only with
numbers, but also with algebraic
formulas. Here is the formula
9(2 + x)(x + y) + (x + y)2 .
In 1]:= 9 (2 + x) (x + y) + (x + y)^2
This takes the previous expression,
represented by %, raises it to the third
power, and expands out products and
powers. The result is fairly complicated.
In 2]:= Expand %^3 ]
2
Out 1]= 9 (2 + x) (x + y) + (x + y)
3
4
5
6
2
Out 2]= 5832 x + 9720 x + 5400 x + 1000 x + 17496 x y +
3
4
5
2
y + 17280 x y + 3300 x y + 17496 x y +
2
2
3 2
4 2
3
y + 19494 x y + 3930 x y + 5832 y +
30132 x
32076 x
12636 x y
3
2 3
3 3
4
4
+ 8802 x y + 1991 x y + 972 y + 1242 x y +
2 4
5
5
6
393 x y + 54 y + 33 x y + y
Factoring this expression yields a much
simpler form.
In 3]:= Factor % ]
Mathematica can do calculus as well as
Ralgebra. Here is the integral of
x2 sin(x)2 dx.
In 4]:= Integrate x^2 Sinx]^2, x ]
Differentiating the result gives the
original integrand, but in a somewhat
different form.
In 5]:= D %, x ]
The Mathematica function Simplify uses
algebraic and trigonometric identities to
simplify the expression, in this case
recovering the original form.
In 6]:= Simplify % ]
This finds the power-series expansion of
the previous result about the point
x = 0.
In 7]:= Series %, {x, 0, 14} ]
Series can also handle purely symbolic
functions such as f.
In 8]:= Series (fx + h] - fx - h])/(2h), {h, 0, 6} ]
3
3
Out 3]= (x + y) (18 + 10 x + y)
3
2
x
x Cos2 x]
(1 - 2 x ) Sin2 x]
Out 4]= --- - ------------------- + ------------------------------------6
4
8
2
2
x
Cos2 x]
(1 - 2 x ) Cos2 x]
Out 5]= --- - --------------- + ------------------------------------2
4
4
2
2
Out 6]= x Sinx]
6
8
10
12
14
4
x
2 x
x
2 x
2 x
15
Out 7]= x - --- + ------- - ----- + --------- - ----------- + Ox]
3
45
315
14175
467775
(3)
2
(5)
4
(7)
6
f
x] h
f
x] h
f
x] h
7
Out 8]= f'x] + ------------------- + ------------------- + ------------------- + Oh]
6
120
5040
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
4. Solving Equations
29
4. Solving Equations
Here is the algebraic equation
x3 ; 7x2 + 3ax = 0 in Mathematica.
In 1]:= x^3 - 7 x^2 + 3 a x == 0
This solves the equation on the previous
line, represented by %, and gives the
solutions in terms of the parameter a.
In 2]:= Solve %, x ]
2
3
Out 1]= 3 a x - 7 x + x == 0
7 + Sqrt49 - 12 a]
Out 2]= {{x -> 0}, {x -> -------------------------------------},
2
7 - Sqrt49 - 12 a]
{x -> -------------------------------------}}
2
Here is the solution to a simple set of
simultaneous equations.
In 3]:= Solve { a x + b y == 0, x + y == c } , {x, y} ]
NSolve finds numerically the 5 complex
solutions to this fifth-order algebraic
equation.
In 4]:= NSolve x^5 + 2 x + 1 == 0, x ]
b c
a c
Out 3]= {{x -> -(---------), y -> ---------}}
a - b
a - b
Out 4]= {{x -> -0.701874 - 0.879697 I},
{x -> -0.701874 + 0.879697 I}, {x -> -0.486389},
{x -> 0.945068 - 0.854518 I}, {x -> 0.945068 + 0.854518 I}}
FindRoot allows you to solve transcendental equations numerically. This gives
the solution to a pair of simultaneous
equations near x = 1, y = 0.
In 5]:= FindRoot { Sinx] == x - y, Cosy] == x + y },
Mathematica can also solve differential
equations. Here is the closed-form
solution for y00 (x) ; ky(x) = 1.
In 6]:= DSolvey''x] - k yx] == 1, yx], x]
NDSolve finds numerical solutions to
differential equations. This solves for the
function y with x in the range 0 to 20.
In 7]:= NDSolve { y''x] + Sinx]^2 y'x] + yx] == Cosx]^2 ,
This takes the solution found by
NDSolve, and plots it as a function of x.
The solution is given as an
“interpolating function”, which allows
values of y(x) to be found when specific
values of x are supplied.
In 8]:= Plot Evaluate yx] /. % ], {x, 0, 20} ]
{x, 1}, {y, 0} ]
Out 5]= {x -> 0.883401, y -> 0.1105}
1
C1]
Sqrtk] x
Out 6]= {{yx] -> -(-) + ------------------- + E
C2]}}
k
Sqrtk] x
E
y0] == 1, y'0] == 0 }, y, {x, 0, 20} ]
Out 7]= {{y -> InterpolatingFunction{0., 20.}, <>]}}
5
10
15
20
0.8
0.6
0.4
0.2
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
Tour of Mathematica
30
5. Lists
This makes a list of the first 15
factorials.
In 1]:= Table n!, {n, 1, 15} ]
Out 1]= {1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800,
39916800, 479001600, 6227020800, 87178291200, 1307674368000}
This takes the logarithm of each entry in
the list, and evaluates the result
numerically. Functions like Log have the
property of being “listable”, so that they
apply separately to each element in a
list.
In 2]:= N Log % ] ]
Here is a plot of the entries in the list.
The fact that the points lie close to a
straight line is a consequence of the
mathematical result that log n! n log n
for large n.
In 3]:= ListPlot % ]
Out 2]= {0, 0.693147, 1.79176, 3.17805, 4.78749, 6.57925,
8.52516, 10.6046, 12.8018, 15.1044, 17.5023, 19.9872,
22.5522, 25.1912, 27.8993}
40
30
20
10
5
10
15
20
Fit finds least-squares fits to data. This
finds the quadratic formula which gives
the best fit to the list of numbers.
In 4]:= Fit %2, {1, x, x^2}, x ]
This creates a two-dimensional array in
which the i, j element is 1 if i and j are
relatively prime, and is 0 otherwise.
Ending with a semicolon stops
Mathematica from printing the rather
large array.
In 5]:= array = Table IfGCDi, j] == 1, 1, 0],
This makes a plot of the array.
In 6]:= ListDensityPlotarray]
2
Out 4]= -1.48508 + 0.963131 x + 0.06766 x
{i, 30}, {j, 30} ] 30
25
20
15
10
5
0
0
This finds the largest absolute value in
the Fourier transform of the array.
5
10
15
20
25
30
In 7]:= Max AbsFourierarray]] ]
Out 7]= 18.5
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
6. Matrices
31
6. Matrices
This generates a matrix whose i jth
element is 1=(i + j + 1). Mathematica
represents the matrix as a list of lists.
In 1]:= m = Table 1 / (i + j + 1), {i, 3}, {j, 3} ]
Here is the inverse of the matrix.
In 2]:= Inverse m ]
1 1 1
1 1 1
1 1 1
Out 1]= {{-, -, -}, {-, -, -}, {-, -, -}}
3 4 5
4 5 6
5 6 7
Out 2]= {{300, -900, 630}, {-900, 2880, -2100},
{630, -2100, 1575}}
Multiplying the inverse by the original
matrix gives an identity matrix.
In 3]:= % . m
This gives a new matrix, with a
modified leading diagonal.
In 4]:= m - x IdentityMatrix3]
The determinant of the new matrix
gives the characteristic polynomial for
the original matrix.
In 5]:= Det % ]
Using the function Eigenvalues, you
can find the numerical eigenvalues of m
directly.
In 6]:= Eigenvalues N m ] ]
This finds the eigenvalues of a 100 100
matrix of random real numbers. The
semicolon suppresses printing.
This plots the eigenvalues as points in
the complex plane.
Out 3]= {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}
1
1 1
1 1
1
1 1 1
Out 4]= {{- - x, -, -}, {-, - - x, -}, {-, -, - - x}}
3
4 5
4 5
6
5 6 7
2
1
317 x
71 x
3
Out 5]= ----------- - --------- + --------- - x
378000
25200
105
Out 6]= {0.657051, 0.0189263, 0.000212737}
In 7]:= Eigenvalues TableRandom ], {100}, {100}] ] In 8]:= ListPlot Transpose {Re%], Im%]} ] ]
3
2
1
-2
2
4
6
-1
-2
-3
Mathematica can also manipulate
symbolic matrices. This finds the
eigenvectors of a matrix.
In 9]:= Eigenvectors {{a, b}, {-b, 2a}} ]
-2 b
Out 9]= {{---------------------------------------------------------------, 1},
-a + Sqrta - 2 b] Sqrta + 2 b]
-2 b
{---------------------------------------------------------------, 1}}
-a - Sqrta - 2 b] Sqrta + 2 b]
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
Tour of Mathematica
32
7. Transformation Rules and Definitions
This uses the rule x ! 1 + a on the
algebraic expression 1 + x2 + 3x3 .
In 1]:= 1 + x^2 + 3 x^3
/.
x -> 1 + a
2
3
Out 1]= 1 + (1 + a) + 3 (1 + a)
You can give transformation rules for
any expression. This uses a rule for
f2].
In 2]:= {f1], f2], f3]}
/.
f2] -> b
This replaces fanything], where
anything is named n, by n^2.
In 3]:= {f1], f2], f3]}
/.
fn_] -> n^2
Here is a Mathematica function
definition. It specifies that fn] is
always to be transformed to n^2.
In 4]:= fn_] := n^2
The definition for f is automatically
used whenever it applies.
In 5]:= f3] + fa + b]
Here is the recursive rule for the
factorial function.
In 6]:= facn_] := n facn-1]
This gives a rule for the end condition
of the factorial function.
In 7]:= fac1] := 1
Here are the two rules you have defined
for fac.
In 8]:= ?fac
Out 2]= {f1], b, f3]}
Out 3]= {1, 4, 9}
2
Out 5]= 9 + (a + b)
Global`fac
fac1] := 1
facn_] := n*facn - 1]
Mathematica can now apply these rules
to find values for factorials.
In 8]:= fac20]
Mathematica lets you give rules for
transforming any expression. This
defines log of a product to be a sum of
log functions.
In 9]:= logx_ y_] := logx] + logy]
Mathematica uses the definition you have
given to expand out this expression.
In 10]:= loga b c d]
You can set up rules to specify the
behavior of any kind of object. This
defines a rule associated with g for
sums of “g objects”.
In 11]:= g/: gi_] + gj_] := gi + j]
Mathematica now automatically uses the
rule for g objects.
In 12]:= gx] + gy] + gz]
Out 8]= 2432902008176640000
Out 10]= loga] + logb] + logc] + logd]
Out 12]= gx + y + z]
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
8. Advanced Topic: Symbolic Computation
33
8. Advanced Topic: Symbolic Computation
Here are the 6 possible permutations of
the elements a, b and c.
In 1]:= Permutations{a, b, c}]
Out 1]= {{a, b, c}, {a, c, b}, {b, a, c}, {b, c, a}, {c, a, b},
{c, b, a}}
Flatten “unravels” lists.
In 2]:= Flatten % ]
Out 2]= {a, b, c, a, c, b, b, a, c, b, c, a, c, a, b, c, b, a}
This gives the positions at which b
appears in the list.
In 3]:= Position %, b ]
Here are cumulative products of the
positions.
In 4]:= FoldListTimes, {1}, %]
This produces a list of successively
nested cosine functions.
In 5]:= NestList Cos, x, 3 ]
Here are plots of the nested cosine
functions. The curves meet at the point
where cos(x) = x.
In 6]:= Plot Evaluate%], {x, 0, 1} ]
Out 3]= {{2}, {6}, {7}, {10}, {15}, {17}}
Out 4]= {{1}, {2}, {12}, {84}, {840}, {12600}, {214200}}
Out 5]= {x, Cosx], CosCosx]], CosCosCosx]]]}
1
0.8
0.6
0.4
0.2
0.2
0.4
0.6
0.8
1
The Map operator allows you to “wrap”
a function around each element in a list.
In 7]:= Mapf, {a, b, c, d}]
With Function you can create “pure
functions” that do not have explicit
names.
In 8]:= Map Functionx, 1 + x^2], {a, b, c, d} ]
This sets up a Fibonacci function using a
recursive definition.
In 9]:= f0] = f1] = 1
Trace creates a symbolic data structure
which represents the execution history
of a Mathematica program. This shows
the instances of the pattern f_] which
occur in the evaluation of f4].
In 10]:= Trace f4], f_] ]
Out 7]= {fa], fb], fc], fd]}
2
2
2
2
Out 8]= {1 + a , 1 + b , 1 + c , 1 + d }
fn_] := fn-1] + fn-2]
Out 10]= {f4], {f3], {f2], {f1]}, {f0]}}, {f1]}},
{f2], {f1]}, {f0]}}}
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
34
Tour of Mathematica
9. Programming
Here is a simple Mathematica program
which generates an n n Hilbert matrix.
Hilbertn_] := Table1/(i + j - 1), {i, n}, {j, n}]
This program finds the characteristic
polynomial for a matrix. The / clause
at the end checks that m is indeed a
matrix.
CharPolym_, x_] :=
Detm - x IdentityMatrixLengthm]]] / MatrixQm]
Here is a procedural program in
Mathematica for finding the next prime
after a given integer. The pattern
n_Integer matches only integers.
NextPrimen_Integer] :=
Module{k = n}, While!PrimeQk], k++] Returnk]]
You can often avoid using loops in
Mathematica by operating directly on
complete lists. The resulting programs
are usually more elegant and more
efficient. Here are programs for
computing the mean, variance and
quantiles of a list.
This function takes a list of random
numbers, and forms a succession of
cumulative sums, thereby producing a
sequence of points in a one-dimensional
random walk.
Here is an elegant program, written in a
functional programming style, which
finds the first n terms in the continued
fraction decomposition of a number x.
You can mix symbolic programming
constructs with mathematical
operations. Outer yields a matrix in
which D is applied to all possible pairs
of elements from funs and vars.
Meanlist_List] := ApplyPlus, list] / Lengthlist]
Variancelist_List] := Mean (list - Meanlist])^2 ]
Quantilelist_List, q_] :=
Part Sortlist], -Floor-q Lengthlist]] ] / 0 < q < 1
RandomWalkn_Integer] :=
FoldListPlus, 0, TableRandom ] - 1/2, {n}]]
ContinuedFractionx_Real, n_Integer] :=
Floor NestList Function{u}, 1/(u - Flooru])], x, n - 1 ] ]
Jacobianfuns_List, vars_List] := OuterD, funs, vars]
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
9. Programming
It is common to use transformation rules
to build up programs in Mathematica.
Here are some rules for Laplace
transforms.
35
Laplacec_, t_, s_] := c/s / FreeQc, t]
Laplacea_ + b_, t_, s_] := Laplacea, t, s] + Laplaceb, t, s]
Laplacec_ a_, t_, s_] := c Laplacea, t, s] / FreeQc, t]
Laplacet_^n_., t_, s_] := n!/s^(n+1) / (FreeQn, t] && n > 0)
Laplacea_. Expb_. + c_. t_], t_, s_] :=
Laplacea Expb], t, s - c] / FreeQ{b, c}, t]
You can write elegant and efficient
programs using pattern matching. This
rather short program produces a
run-length-encoded form of a list of
integers.
Mathematica programs can create
graphics. This program makes polar
plots.
Here is a program which plots the
solutions to a polynomial equation as
points in the complex plane.
This program makes a 3D plot of a
matrix of numbers read from a data file.
You can write programs which manipulate external data. This program gives a
list of the files in your current directory
which contain a particular string.
RunEncode{rest___Integer, same:(n_Integer)..}] :=
Append RunEncode{rest}], {n, Length{same}]} ]
RunEncode{ }] := { }
PolarPlotr_, {t_, tmin_, tmax_}] :=
ParametricPlot{r Cost], r Sint]}, {t, tmin, tmax},
AspectRatio->Automatic]
RootPlotpoly_, z_] :=
ListPlot{Rez], Imz]} /. NSolvepoly == 0, z]] /
PolynomialQpoly, z]
FilePlot3Dfile_String] :=
ListPlot3D ReadListfile, Number, RecordLists -> True] ]
Wheres_String] :=
Select FileNames ], (LengthFindList#, s, 1]] > 0)& ]
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
Tour of Mathematica
36
10. Mathematica Packages
Mathematica comes with various packages for specialized applications. This
loads the Laplace transform package.
In 1]:= <<Calculus`LaplaceTransform`
Here is the Laplace transform of
tn exp(;c=t).
In 2]:= LaplaceTransformt^n Exp-c/t], t, s]
This loads a package for constructing
Padé approximants.
In 3]:= <<Calculus`Pade`
Here is the (2 3) Padé approximant for
exp(sin(x)).
In 4]:= Pade ExpSinx]], {x, 0, 2, 3} ]
This loads part of the standard
Mathematica data analysis system.
In 5]:= <<Statistics`DescriptiveStatistics`
Here is a report of location statistics for
a table of 20 random numbers.
In 6]:= LocationReport TableRandom ], {20}] ]
c (1 + n)/2
Out 2]= 2 (-)
BesselK1 + n, 2 Sqrtc s]]
s
2
8 x
x
1 + ----- + --15
4
Out 4]= --------------------------------------2
3
7 x
13 x
x
1 - ----- + --------- + --15
60
60
Out 6]= {Mean -> 0.436778, HarmonicMean -> 0.278483,
Median -> 0.374784}
This loads a package for manipulating
permutations.
In 7]:= <<DiscreteMath`Permutations`
Here is a randomly chosen permutation
of 10 elements.
In 8]:= RandomPermutation10]
And here is its cycle decomposition.
In 9]:= ToCycles%]
Out 8]= {3, 1, 2, 6, 5, 7, 8, 10, 4, 9}
Out 9]= {{3, 2, 1}, {6, 7, 8, 10, 9, 4}, {5}}
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
10. Mathematica Packages
37
This loads a package that contains data
on the chemical elements.
In 10]:= <<Miscellaneous`ChemicalElements`
This finds the atomic weight of tungsten
from the data in the package.
In 11]:= AtomicWeightTungsten]
If you ask for the atomic weight of an
unstable element, Mathematica prints a
warning message.
In 12]:= AtomicWeightPlutonium]
This switches off the warning message.
In 13]:= OffAtomicWeight::unstable]
This plots the ratio of atomic weight to
atomic number for all the elements.
In 14]:= ListPlot AtomicWeightElements] /
Out 11]= 183.85
AtomicWeight::unstable: No stable isotope of Plutonium exists
Out 12]= 244
AtomicNumberElements], PlotJoined -> True ]
2.6
2.4
2.2
20
40
60
80
100
1.8
1.6
This loads a package which defines the
geometry of various polyhedra.
In 15]:= <<Graphics`Polyhedra`
This generates a picture of the so-called
“great icosahedron”.
In 16]:= Show PolyhedronGreatIcosahedron] ]
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
Tour of Mathematica
38
11. Interfacing with Mathematica
Mathematica usually prints out
expressions in an approximation to
standard mathematical notation.
In 1]:= (a^2 + b^2)/(x + y)^3
InputForm prints out expressions in a
form that you can use as input to
Mathematica. You can use a standard text
editor to modify expressions in this
form.
In 2]:= InputForm % ]
If you need to typeset the formulas you
get from Mathematica, you can convert
them into TEX input form using
TeXForm.
In 3]:= TeXForm % ]
FortranForm allows you to put
Mathematica expressions in a form that
you can include in Fortran programs.
In 4]:= FortranForm % ]
You can use ReadList to read in data
from files. This returns a list of the
numbers in the file tour.dat.
In 5]:= ReadList"tour.dat", Number]
This executes an external command
called square5, then uses a pipe to read
the list of numbers that it produces.
In 6]:= ReadList"!square5", Number]
This creates a link to the external
program extdata, and installs
Mathematica functions for
communicating with the program.
In 7]:= Install"extdata"]
This calls one of the Mathematica
functions which has been set up to
communicate with the external program.
In 8]:= getdata"probe 1", 5]
Mathematica can also do various kinds of
text manipulation. This searches for
lines containing the string Transform in
the file packages.
In 9]:= FindList"packages", "Transform"]
You can use StringReplace to modify
the strings.
In 10]:= StringReplace%, ".m" -> "`"]
2
2
a + b
Out 1]= --------------3
(x + y)
Out 2]//InputForm= (a^2 + b^2)/(x + y)^3
Out 3]//TeXForm=
{{{a^2} + {b^2}}\over {{{\left( x + y \right) }^3}}}
Out 4]//FortranForm= (a**2 + b**2)/(x + y)**3
Out 5]= {15.6, 23.4, 1.77, 18.9, 20.7}
Out 6]= {1, 4, 9, 16, 25}
Out 7]= LinkObjectextdata, 1]
Out 8]= {1.54144, 11.2447, 6.40071, 2.28119, 2.9387}
Out 9]= {FourierTransform.m, LaplaceTransform.m,
MellinTransform.m}
Out 10]= {FourierTransform`, LaplaceTransform`, MellinTransform`}
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.
12 Front Ends and Notebooks
39
12. Front Ends and Notebooks
On some computer systems, there is a “front
end” for Mathematica which allows you to take
advantage of graphical user interface features.
The Mathematica front end supports “notebooks”, in which you can mix text, animated
graphics, and actual Mathematica input.
Web sample page from The Mathematica Book, Second Edition, by Stephen Wolfram, published by Addison-Wesley Publishing Company (hardcover ISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact Wolfram Research: [email protected];
http://www.wolfram.com/; 1-800-441-6284.
 1991 Wolfram Research, Inc.
Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction, or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.