Mathematica in Action
Stan Wagon
Mathematica in Action
Problem Solving Through Visualization
and Computation
Third edition
Stan Wagon
Department of Mathematics
and Computer Science
Macalester College
1600 Grand Avenue
St. Paul, MN 55105
USA
Wolfram Mathematica ® is a registered trademark of Wolfram Research, Inc.
ISBN 978-0-387-75366-9
e-ISBN 978-0-387-75477-2
DOI 10.1007/978-0-387-75477-2
Springer New York Dordrecht Heidelberg London
Library of Congress Control Number: 2010928640
© Springer Science+Business Media, LLC 2010
All rights reserved. This work may not be translated or copied in whole or in part without the
written permission of the publisher (Springer Science+Business Media, LLC, 233 Spring Street,
New York, NY 10013, USA), except for brief excerpts in connection with reviews or scholarly analysis.
Use in connection with any form of information storage and retrieval, electronic adaptation, computer
software, or by similar or dissimilar methodology now known or hereafter developed is forbidden.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they
are not identified as such, is not to be taken as an expression of opinion as to whether or not they are
subject to proprietary rights.
Printed on acid-free paper
Springer is part of Springer Science+Business Media (www.springer.com)
Contents
Preface
ix
0 A Brief Introduction
1
0.1 Notational Conventions
2
0.2 Typesetting
3
0.3 Basic Mathematical Functions
5
0.4 Using Functions
7
0.5 Replacements
12
0.6 Lists
13
0.7 Getting Information
15
0.8 Algebraic Manipulations
17
0.9 Customizing Mathematica
19
0.10 Comprehensive Data Sets in Mathematica
1 Plotting
19
23
1.1 Plot
24
1.2 An Arcsin Curiosity
26
1.3 Adaptive Plotting
28
1.4 Plotting Tables and Tabling Plots
31
1.5 Dealing with Discontinuities
34
1.6 ListPlot
37
1.7 ParametricPlot
42
1.8 Difficult Plots
48
2 Prime Numbers
53
2.1 Basic Number Theory Functions
54
2.2 Where the Primes Are
60
2.3 The Prime Number Race
66
2.4 Euclid and Fibonacci
70
2.5 Strong Pseudoprimes
73
3 Rolling Circles
77
3.1 Discovering the Cycloid
78
3.2 The Derivative of the Trochoid
82
3.3 Abe Lincoln’s Somersaults
84
3.4 The Cycloid’s Intimate Relationship with Gravity
3.5 Bicycles, Square Wheels, and Square-Hole Drills
90
98
vi Contents
4 Three-Dimensional Graphs
113
4.1 Using Two-Dimensional Tools
114
4.2 Plotting Surfaces
119
4.3 Mixed Partial Derivatives Need Not Be Equal
130
4.4 Failure of the Only-Critical-Point-in-Town Test
134
4.5 Raising Contours to New Heights
137
4.6 A New View of Pascal ’s Triangle
139
5 Dynamic Manipulations
141
5.1 Basic Manipulations
142
5.2 Control Variations
144
5.3 Locators
148
5.4 Fine Control
151
5.5 Three Case Studies
157
6 The Cantor Set, Real and Complex
169
6.1 The Real Cantor Set
170
6.2 The Cantor Function
173
6.3 Complex Cantor Sets
175
7 The Quadratic Map
179
7.1 Iterating Functions
180
7.2 The Four Flavors of Real Numbers
187
7.3 Attracting and Repelling Cycles
192
7.4 Measuring Instability: The Lyapunov Exponent
199
7.5 Bifurcations
202
8 The Recursive Turtle
209
8.1 The Literate Turtle
210
8.2 Space-Filling Curves
215
8.3 A Surprising Application
223
8.4 Trees, Mathematical and Botanical
233
9 Parametric Plotting of Surfaces
235
9.1 Introduction to ParametricPlot3D
236
9.2 A Classic Torus Dissection
243
9.3 The Villarceau Circles
250
9.4 Beautiful Surfaces
254
9.5 A Fractal Tetrahedron
261
Contents vii
10 Penrose Tiles
267
10.1 Nonperiodic Tilings
268
10.2 Penrose Tilings
270
10.3 Penrose Rhombs
274
11 Complex Dynamics: Julia Sets and the
Mandelbrot set (by Mark McClure)
277
11.1 Complex Dynamics
278
11.2 Julia Sets and Inverse Iteration
284
11.3 Escape Time Algorithms and the Mandelbrot Set
292
12 Solving Equations
301
12.1 Solve
302
12.2 Diophantine Equations
306
12.3 LinearSolve
310
12.4 NSolve
312
12.5 FindRoot
314
12.6 Finding All Roots in an Interval
315
12.7 FindRoots2D
318
12.8 Two Applications
322
13 Optimization
329
13.1 FindMinimum
330
13.2 Algebraic Optimization
333
13.3 Linear Programming and Its Cousins
334
13.4 Case Study: Interval Methods for a SIAM Challenge
346
13.5 Case Study: Shadowing Chaotic Maps
353
13.6 Case Study: Finding the Best Cubic
360
14 Differential Equations
363
14.1 Solving Differential Equations
364
14.2 Stylish Plots
367
14.3 Pitfalls of Numerical Computing
376
14.4 Basins of Attraction
382
14.5 Modeling
385
15 Computational Geometry
399
15.1 Basic Computational Geometry
400
15.2 The Art Gallery Theorem
404
15.3 A Very Strange Room
406
15.4 More Euclid
413
viii Contents
16 Check Digits and the Pentagon
423
16.1 The Group of the Pentagon
424
16.2 The Perfect Dihedral Method
427
17 Coloring Planar Maps
431
17.1 Introduction to Combinatorica
432
17.2 Planar Maps
437
17.3 Euler’s Formula
441
17.4 Kempe’s Attempt
445
17.5 Kempe Resurrected
449
17.6 Map Coloring
458
17.7 A Great Circle Conjecture
468
18 New Directions for Π
473
18.1 The Classical Theory of Π
474
18.2 The Postmodern Theory of Π
480
18.3 A Most Depressing Proof
483
18.4 Variations on the Theme
488
19 The Banach-Tarski Paradox
491
19.1 A Paradoxical Free Product
492
19.2 A Hyperbolic Representation of the Group
495
19.3 The Geometrical Paradox
499
20 The Riemann Zeta Function
20.1 The Riemann Zeta Function
505
506
20.2 The Influence of the Zeros of Ζ on the Distribution of Primes 512
20.3 A Backwards Look at Riemann’s R x
21 Miscellany
519
523
21.1 An Educational Integral
524
21.2 Making the Alternating Harmonic Series Disappear
525
21.3 Bulletproof Prime Numbers
528
21.4 Gaussian Moats
530
21.5 Frobenius Number by Graphs
536
21.6 Benford’s Law of First Digits
542
References
557
Mathematica Index
566
Subject Index
572
Preface
This book is an example-based introduction to techniques, from elementary to
advanced, of using Mathematica, a revolutionary tool for mathematical computation
and exploration. By integrating the basic functions of mathematics with a powerful
and easy-to-use programming language, Mathematica allows us to carry out projects
that would be extremely laborious in traditional programming environments. And
the new developments that began with version 6 — allowing the user to dynamically manipulate output using sliders or other controls — add amazing power to the
interface. Animations have always been part of Mathematica, but the new design
allows the manipulation of any number of variables, an important enhancement.
Mathematica in Action illustrates this power by using demonstrations and animations, three-dimensional graphics, high-precision number theory computations, and
sophisticated geometric and symbolic programming to attack a diverse collection of
problems..
It is my hope that this book will serve a mathematical purpose as well, and I have
interspersed several unusual or complicated examples among others that will be
more familiar. Thus the reader may have to deal simultaneously with new mathematics and new Mathematica techniques. Rarely is more than undergraduate
mathematics required, however.
An underlying theme of the book is that a computational way of looking at a
mathematical problem or result yields many benefits. For example:
Well-chosen computations can shed light on familiar relations and reveal new
patterns.
One is forced to think very precisely; gaps in understanding must be eliminated if
a program is to work.
Dozens (or hundreds or thousands) of cases can be examined, perhaps showing
new patterns or phenomena.
Methods of verifying the results must be worked out, again adding to one's
overall understanding.
Different proofs of the same theorem can be compared from the point of view of
algorithmic efficiency.
x Preface
One can examine historically important ideas from the varied perspectives
provided by Mathematica, often obtaining new insights.
The reader will find examples of these points throughout the book. Here are two
specific cases: Chapter 17 contains a discussion of the four-color theorem that seeks
to turn Kempe's false proof of 1879 into a viable algorithm for four-coloring planar
graphs. And Chapter 15 shows how a certain published construction in computational geometry — the construction of a three-dimensional room that contains a
point invisible to guards placed at every vertex — must be changed if it is to be
correct.
Another point worth mentioning is that a detailed knowledge of some of Mathematica's internal workings can lead to novel solutions to programming problems. As an
example, Chapter 12 shows how an understanding of the data computed by
ContourPlot can lead to a simple and effective routine for finding all solutions in
a rectangle to a pair of simultaneous transcendental equations.
The chapters are written so that browsing is possible, but there is certainly a progression from elementary to advanced techniques, and the novice is encouraged to read
the chapters in order. Even advanced users will benefit from a careful reading of
the first few chapters. Chapter 5 is devoted to the Manipulate command, which is
used throughout the book. The output cannot be appreciated very well on the
printed page and the reader is encouraged to load the files in the electronic supplement and work through the demonstrations in an interactive way.
From its beginning, twenty years ago, the pleasure and power of using Mathematica
arose from the two somewhat separate features: the kernel and the front end. The
kernel does the underlying computations and the front end is the device through
which the user communicates with the kernel. There has always been some communication between the two, especially after version 3 with its many front end enhancements, but the two interfaces had the feel of separate entities. With version 6 the
connection between the two became much stronger, as one can create Manipulate
output that runs on its own. All the code in this book has been designed to work in
both versions 6 and 7, with some small exceptions where use has been made of
functions that are new in version 7. All the timings in the book are from a Macintosh laptop running a 2.16 gigaHertz Intel chip.
There have been important enhancements to the kernel as well. Some are minor, but
together they contribute to making programming smoother, faster, and just more
fun. A brief sampling: Table and Do commands now accept iterators that vary over
a list, as in Do this, x, a, b, c
, where x takes on the values a, b, and c;
RandomChoice s generates a random choice from the list s; Total s sums the
Preface xi
elements of s; Tally s
gives the elements of s with their frequencies;
ZetaZero i gives the ith zero of the Riemann Ζ function. Another nifty enhancement is the inclusion of comprehensive databases, some requiring a web connection
to access. Thus one can get stock prices, currency exchange rates, and data about
many structures in mathematics, physics, chemistry, geography, and even grammar. The data can then be integrated into Mathematica programs, thus allowing the
user to conveniently analyze or present the data using all of Mathematica's tools.
This book includes a CD with Mathematica files containing all the code that appears
in the book, and much code that is not in the book. In some of the chapters one
needs to load code from the disk to enable various sophisticated functions.
From a personal point view I have to emphasize the huge impact that Mathematica
has had on my teaching and research. I have been using the program for almost 20
years and it has led to many new ideas at the forefront of research, in a wide variety
of fields. Math and science are much more fun when one can visualize concrete
examples of the objects being studied; Mathematica gives us the chance to see even
very abstract constructions, and thus to understand them more deeply.
Acknowledgments
I am grateful to the many people who have shared with me
their expertise in mathematics and Mathematica. Of particular help with this edition
have been several members of the Wolfram Research staff, including: Rob Knapp,
Danny Lichtblau, Brett Champion, Ulises Cervantes, Lou D'Andria, Adam Strzebonski, Jeff Bryant, and Oleksandr Pavlyk. For helpful consultation on technical and
style issues, I thank Joan Hutchinson, Ellen Gethner, Mark McClure, and Rob Pratt.
Mark also contributed Chapter 11 on Julia sets. Michael Rogers shared his considerable knowledge of the subtleties of Manipulate. I am grateful to Wayne Hayes
(shadowing), Rachel Fewster (Benford's Law), and Matthias Weber (three-dimensional surfaces) for sharing their expertise on various points. And finally I thank Ed
Packel, with whom I have for fifteen years taught a summer course about Mathematica in the mountains of Colorado.
Stan Wagon, Macalester College, St. Paul, Minnesota
December 2009
0 A Brief Introduction
The image shown is a view of the torus knot known as 83 ; data for this image, and
other aspects of the knot, are available through the KnotData command. Mathematica includes many data sets containing useful and easy-to-use information from
physics, chemistry, astronomy, finance, geography, mathematics, and other areas.
2 Chapter 0 A Brief Introduction
This chapter contains a brief introduction to the syntax of Mathematica, as well as
diverse front-end techniques. Most of the items here are discussed in much more
detail in the main text, but there are a few front-end tips that are mentioned in
this chapter only. The last section is an introduction to some of the data sets
available in Mathematica, which allow the user access to data in diverse fields.
0.1 Notational Conventions
The Mathematica kernel accepts input cells and returns output cells. During a
session these cells are labeled In[1], Out[1], In[1], and so on. In this book we will
suppress these labels, but the input cells are printed in boldface. On most front
ends, input cells are evaluated by either the enter key or the shift-return key. Note
that on Windows computers the enter key on the numeric keypad evaluates while
the other enter key does not.
Built-in Mathematica objects always begin with capital letters. It is good practice for
users to use lowercase letters for their own objects, but one might wish to use
capital letters for functions when writing a comprehensive package.
Function arguments are always enclosed by square brackets,
. Parentheses,
,
are used to group objects together, thus establishing priority of operations. The
standard arithmetic operations are
,
,
,
, and ^. A space is interpreted as
multiplication. Sometimes even a space is unnecessary: 2a and 2Sin[x] work as
expected, but xy is not the same as x
y. Variable names cannot begin with num-
bers, but otherwise numbers can occur and there is no restriction on the length of a
name. One can use typeset input and alternate alphabets. Thus one can enter and
use x as a single variable.
Lists are enclosed by braces,
. List elements are accessed via double square
brackets. Thus, if x is the list a, b, c , then x 3 (same as x
3
) is c. Matri-
ces are lists of lists (rows). Matrix multiplication and dot products are via the dot:
1, 2 , 3, 4
. 5, 0 is 5, 15 . Some of the built-in matrix commands are
MatrixPower, Inverse, Transpose, IdentityMatrix, Eigenvalues, and
Det.
Comments are delimited by
.
One can refer to output later on in a Mathematica session by Out n or by
of which refer to the nth output cell. The symbol
produced;
n, both
refers to the previous output
refers to the second-previous output, and so on.
0.2 Typesetting 3
abbreviates n
n
n
n
n
i; similarly for n
1; similarly n
i, n
abbreviates n
i, and n
can serve as an abbreviation for
. Sin
n
1. n
i denotes
i.
Π and Print
x abbreviate Sin Π
and Print x , respectively. However, this notation should be used sparingly, as
f
x is much less precise than f x
in terms of scope. I use it sometimes when
x temporarily for debugging a program.
adding, say, Print
Postfix notation is sometimes useful. expr
most useful in something like expr
f is the same as f expr
Timing or expr
and is
Simplify.
Iterators occur often, especially in Do loops or when lists are built using the Table
command. An iterator has the form i, n0, n, step . The default step size is 1,
and an iterator of the form i, 200
abbreviates i, 1, 200, 1 . One can use
lists in iterators, such as Table Prime i , i, 10, 100, 1000
, which
causes i to run through the list of three numbers.
There are three usages of the equal sign. An ordinary assignment of one value to a
variable is done via, for example, a
3; one can also use
a, b
3, 7 , for
example, to handle two or more assignments. A delayed assignment is identified by
: ; f : x2 means that whenever f is called it will be replaced by x2 for the value
of x at the time of the call. This is most often used in the definition of functions via
dummy variables, as in f t_ : t2 ; the underscore (blank) indicates that t is an
object that should take on the value of expr whenever f expr is encountered, so
f expr
will always turn into expr2 for any value of expr; in short, t can be
thought of as a dummy variable. Finally, equality is denoted by
such as Solve x
5
x
7, x or If n
in an equation
100, … ) .
0.2 Typesetting
The front end has hundreds of features, and we will not go into all of them here.
But the ability to use typeset mathematics for input and output is very important, so
here is a brief introduction. For more on other aspects of the front end, such as
buttons and palettes, see [GG].
There are three main forms for mathematical expressions: InputForm, Standard-
Form, and TraditionalForm. InputForm is the character-based, single-line
format that is familiar to users of early versions. For example, an integral would be
given as Integrate Sin Sqrt x
Cos x , x, 0, 1
. StandardForm
is a typeset form that differs from traditional mathematics typesetting in that there
are no ambiguities.
4 Chapter 0 A Brief Introduction
An integral would look like
x
1 Sin
0 Cos x
x. TraditionalForm is an attempt to
match traditional mathematical notation, and an integral would look like
1 sin x
0 cos x
x. While it is possible to use TraditionalForm now and then, the
ambiguities that can arise can lead to problems.
I avoid traditional form in my work, though some users do use it a lot. The following table shows several examples of the three forms. One can convert between
forms via the Cell >> Convert To menu item. By default Mathematica input and
output are both in StandardForm. The following table shows how certain expressions look in all three formats.
InputForm
StandardForm
1
0
Integrate f x , x, 0, 1
Sum 1
n ^ 2,
Sqrt 1
x
Product x
i,
3
i, 1, 4
LogIntegral Log x
Floor x
^ 1
Sqrt x
5
1
x
0
1
4
i 1
1 3
x
Log x
x
x
5
li
1
y
4
i 1
i
LogIntegral
Floor
x
x
3
y
x
f x
1
n 1 n2
1
n 1 n2
n, 1, Infinity
Sqrt y
f x
TraditionalForm
i
x
log x
x
x
5
One simple way to enter typeset material is to use InputForm and then convert the
cell to StandardForm. One can also use the standard palettes to create typeset
material directly. And there are various keyboard shortcuts that are useful. The
table that follows shows some of the keyboard shortcuts that I have found most
useful. Note that when one is in an in-line cell in text, perhaps after entering a
subscript, one can get back into normal text mode by using either the right arrow
key twice, or simply
-0. Similarly, the arrow or
superscript or up from a subscript.
Key sequence
a
D
inf
p
elem
e
ce
deg
Result
Α
Π
Ε
°
Full name
\ Alpha
\ CapitalDelta
\ Infinity
\ Pi
\ Element
\ Epsilon
\ CurlyEpsilon
\ Degree
\ Rule
\ Implies
-space gets one down from a
0.3 Basic Mathematical Functions 5
lf
rf
.
'
esc
un
int
and
x
x
6 2
x2
hyphen 1
x1
1
23
9
LeftFloor
RightFloor
Times
CenterDot
Congruent
ThinSpace
Tilde
Prime
EscapeKey
Union
\
\
\
\
Intersection
And
LeftDoubleBracket
RightDoubleBracket
SuperscriptBox "x","2"
SubscriptBox "x","1"
x
2 x
\
\
\
\
\
\
\
\
\
\
SqrtBox "x"
1
FractionBox "1","23"
23
begin an in-line cell
0.3 Basic Mathematical Functions
Pi (Π), I ( ), Infinity ( ), E ( ), EulerGamma, and GoldenRatio are built-in
constants. To turn a symbolic value into a numeric one, use N
. For example, N Π
returns 3.141592653589793 (though only six digits are displayed). N x, d returns
d significant digits. Degree, the radian value of 1°, is also built-in. Thus N i °
returns the value of i°in radians. Note that typeset forms may be used here too. For
example, Sin 41.3 °
deg
works where the degree symbol can be entered by
.
Log refers to log . Log b, x is used for logb x .
Exp z denotes
z
.
Sin, Cos, Tan, Cot, Sec, Csc, ArcSin, ArcCos, ArcTan, and so on are the
common trigonometric functions; the default angular measure is radian. ArcTan
also works in the form ArcTan x, y , in which case it returns the angle in the
correct quadrant.
has several uses (e.g., logical negation), but immediately following an integer it
refers to the factorial of that number (and following any number z it gives
z
1 ).
Some of the two-dimensional plotting commands are Plot, ListPlot, List-
LinePlot, LogPlot, ParametricPlot, ContourPlot, and DensityPlot. In
three dimensions we have Plot3D, ParametricPlot3D, and ListPlot3D.
6 Chapter 0 A Brief Introduction
This logical connectives are && (And, ),
(Or, ),
(Not, ), and Xor (exclusive
or). Logical constants are True and False.
And there are hundreds of built-in mathematical functions. Here is a sampling.
Π
Floor
3
7
FactorInteger[12345679]
37, 1 , 333 667, 1
PrimeQ[1111111]
False
GCD 123 456, 8888
8
Zeta 2
Π2
6
Fibonacci 50
12 586 269 025
LegendreP 6, t
1
16
5
105 t2
315 t4
231 t6
BernoulliB 10
5
66
To define your own function, proceed as follows via the delayed assignment, : .
fcn x_ : x2
The function can then be used as follows.
fcn 3 , fcn x , fcn t
9, x2 , t2
0.4 Using Functions 7
0.4 Using Functions
This section briefly presents some advanced techniques for using functions that will
be useful to anyone writing programs in Mathematica. Although we sometimes fail
to make the distinctions, there are several ways in which functions are traditionally
used in mathematics. We can apply a function to one or more arguments in the
traditional way [ f(x) or f(x, y)]. We can map a function of, say, one variable onto
each element of a set to form { f(x) : x
X}. We can also apply a function of, say, two
variables to a single set consisting of a two-element list, where the elements of the
list are to be treated as arguments; that is, we can interpret f({x, y}) as f(x, y).
Mathematica has the means to perform all these types of transformations, as well as
several higher-level forms.
The following all return f(x): f x , f
x, x
f. The first form is the traditional
notation, the second avoids the buildup of brackets, and the third is useful for quick
typing, as in expr
Simplify. Another way to reduce brackets is to use f for
a function of two variables, as follows.
1, 2, 3
Union
4, 3, 6, 1
1, 2, 3, 4, 6
On the other hand, one can just use the union symbol.
1, 2, 3
4, 3, 6, 1
1, 2, 3, 4, 6
The set-image {f(x) : x
X is called mapping in Mathematica: Map f, X
returns
the set consisting of the f-values applied to the elements of X.
Map f, 1, 2, 3
f 1 ,f 2 ,f 3
This usage is very common and has the abbreviation f
x.
Built-in functions that work on numbers have an attribute called Listable. This
means that, when applied to a list, they automatically move inside the list. Thus
Sqrt
9, 16, 25
9, 16, 25
3, 4, 5
is the same as Map Sqrt, 9, 16, 25
.
8 Chapter 0 A Brief Introduction
The Listable attribute can be added to a user-defined function as follows. In the
example that follows, the attribute makes a big difference. The SmallestDivisor
function picks out the smallest nontrivial divisor of an integer.
SmallestDivisor n_ : First Rest Divisors n
Attributes SmallestDivisor
Listable;
SmallestDivisor 101, 1001, 10 001
101, 7, 73
But without the special attribute, the First command is not interpreted properly
(though Divisors is, since it is Listable).
SmallestDivisor1 n_ : First Rest Divisors n
SmallestDivisor1 101, 1001, 10 001
1, 7, 11, 13, 77, 91, 143, 1001 , 1, 73, 137, 10 001
You can learn the attributes of a function as follows.
??Divisors
n
n
Attributes Divisors
Options Divisors
Listable, Protected
GaussianIntegers
False
Using ?Divisors gets the usage message only.
To apply a function to a list so that the list elements are arguments, one uses Apply.
Apply Plus, x, y
returns Plus x, y , which is just x
for Apply f, X is f
X.
y. An abbreviation
Apply[Plus,{x,y}]
x
y
Functions such as Map and Apply can be made to work only at certain levels. In the
next example, f is mapped onto expressions at the second level only.
Map f, 1, 2, 3, 4
, 2
1, 2, f 3 , f 4
When the level specification is an integer, then the function maps at all levels up to
and including that specified.
Map f, 1, 2, 3, 4
f 1 ,f 2 ,f
,2
f 3 ,f 4
0.4 Using Functions 9
Apply typically applies the function to the 0th level, in the sense that it replaces the
head of the expression with the function being applied. In the next example, we
apply to the first level.
Apply f,
1, 2 , 3, 4
, 1
f 1, 2 , f 3, 4
Some higher-level ways of using functions are Thread, Inner, and Outer. Threading a function causes it to match corresponding entries in lists.
Thread f
a, b, c , x, y, z
f a, x , f b, y , f c, z
Inner is a generalization of the familiar dot product. In the command
Inner f, … , … , … , g , f plays the role of multiplication and g the role of
addition in the dot product. If g is omitted, it is assumed to be addition.
Inner f, a, b, c , x, y, z
f a, x
f b, y
f c, z
Inner f, a, b, c , x, y, z , g
g f a, x , f b, y , f c, z
Inner f, a, b, c , x, y, z , List
f a, x , f b, y , f c, z
The last example is identical to the Thread example just given. Outer is a very
powerful command: it applies a function to all combinations from a sequence of
lists.
Outer f, a, b, c, d , e, f
f a, e , f a, f
f c, e , f c, f
, f b, e , f b, f
, f d, e , f d, f
,
A nice application is to generate all sequences of 0s and 1s.
Outer[List, {0,1}, {0,1}, {0,1}]
0, 0, 0 , 0, 0, 1
1, 0, 0 , 1, 0, 1
,
,
0, 1, 0 , 0, 1, 1
1, 1, 0 , 1, 1, 1
,
We can combine several of the preceding ideas to get all sequences of length n. We
must Flatten the result the right number of times (n
1) to eliminate the matrix
structure that Outer produces.
sequences n_ :
Flatten Outer
sequences 3
Prepend Table
0, 1 , n
, List , n
1
10 Chapter 0 A Brief Introduction
0, 0, 0 , 0, 0, 1 , 0, 1, 0 , 0, 1, 1 ,
1, 0, 0 , 1, 0, 1 , 1, 1, 0 , 1, 1, 1
Distribute is much the same as Outer but often a little faster. Its default mode is
to distribute a function over occurrences of Plus.
Distribute f a
f a, c
b, c
f a, d
d
f b, c
f b, d
But a second argument can control what the function distributes over. Here f
distributes over List.
Distribute f
a, b , c, d
, List
f a, c , f a, d , f b, c , f b, d
Since the full form of x, y is List x, y , we can use the following bit of code
to get all sequences of 0s and 1s.
Distribute
0, 1 , 0, 1 , 0, 1
, List
0, 0, 0 , 0, 0, 1 , 0, 1, 0 , 0, 1, 1 ,
1, 0, 0 , 1, 0, 1 , 1, 1, 0 , 1, 1, 1
While Outer and Distribute are useful here and there, the generation of all
strings is more easily handled with Tuples.
Tuples
0, 1 , 3
0, 0, 0 , 0, 0, 1 , 0, 1, 0 , 0, 1, 1 ,
1, 0, 0 , 1, 0, 1 , 1, 1, 0 , 1, 1, 1
A cute application of Outer is the following, which generates forty possible transliterations of the name of the Russian mathematician P. Chebyshev.
Outer StringJoin, "Ceb", "Tscheb", "Tcheb", "Cheb" ,
"y", "i" , "schef", "cev", "cheff", "scheff", "shev"
Cebyschef, Cebycev, Cebycheff, Cebyscheff, Cebyshev ,
Cebischef, Cebicev, Cebicheff, Cebischeff, Cebishev ,
Tschebyschef, Tschebycev, Tschebycheff, Tschebyscheff,
Tschebyshev , Tschebischef, Tschebicev,
Tschebicheff, Tschebischeff, Tschebishev ,
Tchebyschef, Tchebycev, Tchebycheff, Tchebyscheff, Tchebyshev ,
Tchebischef, Tchebicev, Tchebicheff, Tchebischeff, Tchebishev ,
Chebyschef, Chebycev, Chebycheff, Chebyscheff, Chebyshev ,
Chebischef, Chebicev, Chebicheff, Chebischeff, Chebishev
Another important way of using a function is to iterate it. Traditional program
languages use Do-loops, as follows.
y x;
Do y f y , i, 1, 4
y
;
0.4 Using Functions 11
f f f f x
But Nest and NestList are built in and much more efficient.
Nest f, x, 5
f f f f f x
NestList shows the entire sequence of iterates.
NestList f, x, 5
x, f x , f f x
,f f f x
,f f f f x
,f f f f f x
NestList Cos, 0.31, 10
0.31, 0.952334, 0.579783, 0.836581, 0.670005,
0.783819, 0.708223, 0.759519, 0.725167, 0.748389, 0.732786
Sometimes one wants to apply a function until the result stops changing.
FixedPoint and FixedPointList do that. Recall that six digits are shown,
though more digits are stored internally (use InputForm to see them). Here is the
result of iterating the infamous Collatz function, also known as the 3 x
1 function.
Because the fixed point occurs when we look at every third entry, we define
Collatz3 to iterate three times, and then find a fixed point of that.
n
,3n 1 ;
2
Collatz3 n_ : Nest Collatz, n, 3 ;
FixedPointList Collatz3, 123 456 789
Collatz n_ : If EvenQ n ,
123 456 789, 92 592 592, 11 574 074, 8 680 556, 6 510 418,
4 882 814, 3 662 111, 16 479 502, 12 359 627, 55 618 324, 41 713 744,
5 214 218, 3 910 664, 488 833, 366 625, 274 969, 206 227, 928 024,
116 003, 522 016, 65 252, 48 940, 36 706, 27 530, 20 648, 2581,
1936, 242, 182, 137, 103, 466, 350, 263, 1186, 890, 668,
502, 377, 283, 1276, 958, 719, 3238, 2429, 1822, 1367, 6154,
4616, 577, 433, 325, 244, 184, 23, 106, 80, 10, 8, 1, 1
One can use these ideas to implement Newton's method to find
1
2
iterate the function x
func x_ :
1
2
x
2
x
x
2
x
2 ; one needs to
, which can be done as follows.
;
FixedPoint func, 0.3
1.41421
But it is much more efficient to use what is called a pure function. In Mathematica the
pound symbol, , is used as the generic variable in such a construction, with an
ampersand, &, indicating that the object is to be viewed as a function. One can just
apply such a function to an argument as follows.
12 Chapter 0 A Brief Introduction
2
&
3
9
A typical use of pure functions is inside Nest and other high-level commands.
Here are the approximations to
FixedPointList
1
2
2 generated by Newton's method.
&, 0.3, 7
2
0.3, 3.48333, 2.02875, 1.50729, 1.41709, 1.41422, 1.41421, 1.41421
And finally there are Fold and FoldList. Fold takes a function f, a starting
value a, and a list b, c, d, … and forms f a, b , then f f a, b , c , and so
on.
Fold f, a, b, c, d
f f f a, b , c , d
This is especially useful when f is just Plus, for then the sequence of f-values is
just the sequence of partial sums. Using FoldList shows them all.
FoldList Plus, a, b, c, d, e
a, a
b, a
b
c, a
b
c
d, a
b
c
d
e
But in this special case there is a special function that does the job.
Accumulate
1, 2, 3, 4, 5
1, 3, 6, 10, 15
0.5 Replacements
In a computer algebra system, x is often used as the variable in, say, a polynomial.
Thus setting x to be the number 3 can be a bad thing to do, for if x is subsequently
used to define a polynomial, it will not work. Mathematica allows us to give x
specific values without a permanent assignment by using replacement rules. The .
in the following line stands for Replace, and the rule that follows it has the effect
of replacing x by 2.
x
x3 . x
2
10
When one solves an equation, including differential equations, the result is given as
a set of replacement rules.
sol
Solve 4 x
x3
0, x