Programming in Mathematica - 3rd Ed.
Programming in Mathematica - 3rd Ed.
Where those
designations appear in this book and Addison-Wesley was aware of a trademark claim, the designations have been printed in initial
caps or all caps. Mathematica, MathLink, and MathSource are registered trademarks of Wolfram Research.
The authors and publishers have taken care in the preparation of this book, but make no expressed or implied warranty of any kind
and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection
with or arising out of the use of the information or programs contained herein.
The author, Wolfram Research, Inc., and Addison Wesley Longman, Inc. make no representations, express or implied, with respect
to this documentation or the software it describes, including without limitations, any implied warranties of merchantability or fitness
for a particular purpose, all of which are expressly disclaimed. Users should be aware that included in the terms and conditions
under which Wolfram Research is willing to license Mathematica is a provision that Wolfram Research, Wolfram Media, and their
distribution licensees, distributors and dealers shall in no event be liable for any indirect, incidental or consequential damages, and
that liability for direct damages shall be limited to the amount of the purchase price paid for Mathematica.
In addition to the foregoing, users should recognize that all complex software systems and their documentation contain errors
and omissions. The author, Wolfram Research, Inc., and Addison Wesley Longman, Inc. shall not be responsible under any
circumstances for providing information on or corrections to errors and omissions discovered at any time in this book or the
software it describes, whether or not they are aware of the errors or omissions. The author, Wolfram Research, Inc., and Addison
Wesley Longman, Inc. do not recommend the use of the software described in this book for applications in which errors or omissions
could threaten life, injury or significant loss.
The publisher offers discounts on this book when ordered in quantity for special sales.
For more information, please contact:
Corporate & Professional Publishing Group
Addison-Wesley Publishing Company
One Jacob Way
Reading, Massachusetts 01867
Maeder, Roman.
Programming in Mathematica I Roman E. Maeder. - 3rd ed.
p. em.
Includes bibliographical references and index.
ISBN 0-20l-85449-X
1. Science-Data processing. 2. Mathematica (Computer programming language). I. Title.
QI83.9.M34 1996
510' .285 I 53--dc20 96-5714
CIP
This book was prepared by the author, using the TEX typesetting language on a Sun SPARCstation 5 computer.
Copyright © 1997 by Addison Wesley Longman, Inc.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by
any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the
United States of America. Published simultaneously in Canada.
ISBN 0-20l-85449-X
2 3 4 5 6 7 CRW 01 00 99 98
2nd Printing July, 1998
II Preface
Mathematica was officially announced in June of 1988. Since then it has found many
uses in very diverse fields. While it is useful to do a few calculations interactively, its
real strength lies in the programming language it offers. Writing programs, one extends
Mathematica with specialized new functions in one's own field of interest. Mathematica's
programming language is unlike any you have encountered before. The language's manual
explains all its features and gives some very basic examples of their use. For writing good
programs, however, this is not enough: there is clearly a need for a book explaining all the
many features in context and giving more extensive examples of their use. The first edition
of this book filled this gap for version 1.2 of Mathematica. Like the second edition, this
third edition was prompted by a major new version of Mathematica, Version 3.
I have been in contact with many early users of Mathematica and I have also given
students at the University of Illinois and the Swiss Federal Institute of Technology an
opportunity to learn about it. I have seen many programs written in Mathematica, good
ones and bad ones. The bad ones invariably solve a particular problem in an unnecessarily
complicated way, perhaps because the programmers were unaware of the elegant constructs
available in Mathematica. Let me point out these constructs and show you how they can
be used to write concise, elegant, and efficient programs.
The best way to teach these Mathematica-specific programming methods is to look at
examples of complete programs that solve some nontrivial problem. Even if the example
chosen does not lie in the particular field of application that you are interested in, you will
be able to use similar ideas for your own programs. Many of the examples presented here
deal with graphics. Graphics applications are especially suited for learning programming,
because it is easy to see whether your code is correct simply by looking at the picture
it produces. Advanced graphics applications are also sufficiently challenging to require
advanced programming methods. Other examples come from symbolic computation,
geometry, dynamics, and numerical mathematics. Along the way, we also develop many
short pieces of code that can be used as parts of larger programs or that help to customize
Mathematica to your particular needs. Many of these found their way into the standard
Mathematica distribution and are now available to all users.
Because there exists an excellent manual, this book does not explain everything from
scratch, but assumes some familiarity with Mathematica. I assume also that you have
access to a computer on which to try out the examples. In this book I want to tell you how
you can use Mathematica for more than just typing in single commands. If you are using
Mathematica for your work, teaching, or solving homework assignments, sooner or later
you will encounter more advanced problems requiring many commands to solve, or you
will be faced with doing the same calculation steps over and over again with different input.
This is the point at which you want to start writing programs. Mathematica includes a rich
and powerful programming language. Unlike the usual languages such as BASIC and C, it
is not restricted to a small number of data types, but allows you to perform all its symbolic
vi Preface
computations. The Mathematica manual can only hint at the possibilities. It explains all
the features but does not show you which ones to use for a particular problem or how to fit
things together into larger programs.
Through design and tradition, each programming language has developed a certain
preferred style of good programming. It is possible to solve the same problem in many
different ways, but there is usually some idea about what is a good or a bad program. In
this book, I want to present examples of what the designers of Mathematica think is good
programming style and show you why this is so. Even if you write your programs strictly
for personal use, you will benefit from following a good style. For developing programs
for others to use, adhering to this style is indispensable.
The programming examples in this book serve two purposes. First, they help explain
concepts and show how things fit together to make up complete programs. Second, they are
designed to be more than mere toy programs and should prove useful in their own right. In
developing an example we always use the same method. We start out with a few commands
or definitions that could be entered directly into Mathematica. We then extract the parts
of the computation that are the same regardless of the input and define some functions or
procedures that automate these steps. Then we apply standard techniques to these functions
to make them into a package, adding documentation and certain programming constructs
that make such a package easier to use. The goal is to write a program that would be
useful not only to its author, who knows how it works, but also to other people. Finally,
we might add a few more functions to the package or look at alternatives to what we did so
far. In Chapter 1 these steps are described in full detail. Later on, when we concentrate on
other aspects, we assume that you are familiar with these basic concepts and we shall not
mention all the steps in detail. All the programs developed in this book are either part of
the standard Mathematica distribution from Wolfram Research, or they are available free
in electronic form.
Version 3 brings major new features. The programming language itself has not changed
all that much, but many problems that required elaborate workarounds and many inconsis-
tencies have been remedied. As a consequence, it is now possible to present the material
on packages in a more logical fashion. The support for developing larger applications
has been improved, and this edition discusses the software engineering issues of writing
and using larger programs in Mathematica. The treatment of exact numeric quantities is
another area of improvement, and the way numerical code should be written has changed.
All programs have been revised to take advantage of the many new built-in functions. I
added more material about functional and structural programming. These techniques are
fundamental to writing good Mathematica code, but they are not available in most other
programming languages and therefore need an expanded treatment.
The most important addition to Version 3 is, of course, the new frontend and the
typesetting capabilities. The fact that notebooks and typeset formulae are represented
as ordinary Mathematica expressions means that they can be manipulated easily with
programs. This capability leads to some fascinating applications, and the new material on
the frontend and typesetting teaches you how to develop such applications.
A complete, larger application (iterated function systems), more exercises, and an
Preface vii
Preface . v
1 Introduction
1.1 From Calculations to Programs 3
1.2 Basic Ingredients of a Package 8
1.3 A Second Function in the Package 12
1.4 Options . . . . . . . . . . 15
1.5 Defaults for Positional Arguments 21
1.6 Parameter Type Checking 25
2 Packages
2.1 Contexts . . . . . . . . . . . 31
2.2 Packages That Use Other Packages 36
2.3 Protection of Symbols in a Package 41
2.4 Package Framework and Documentation 45
2.5 Loading Packages 49
2.6 Large Projects. . . . . . . . . . . 58
3 Defaults and Options
3.1 Default Values . 63
3.2 Options for Your Functions . 67
3.3 Setting Options of Several Commands 74
4 Functional and Procedural Programming
4.1 Procedures and Local Variables 81
4.2 Loops . 83
4.3 Structured Iteration. . . . . 88
4.4 Iterated Function Application . 94
4.5 Map and Apply . . . . . . 103
4.6 Application: The Platonic Solids 107
4.7 Operations on Lists and Matrices 113
5 Evaluation
5.1 Evaluation of the Body of a Rule 123
5.2 Pure Functions . 130
x Contents
Appendix A Exercises
A.I Programming Exercises 337
A.2 Solutions. . . . . . 339
Appendix B Bibliography
B.I Background Information and Further Reading 347
B.2 References . . . . . . . . . . . . . . 350
Index
Programs . . . 355
Subjects and Names 356
II About This Book
This section gives you hints and recommendations for benefitting the most from the material
in this book.
• Chapter Overview
Chapter 1 develops a package from scratch. It starts with a few simple interactive commands
and then explores ways to combine such commands into small programs. Along the way we
learn how to set up package contexts, define defaults for parameters of functions, and also
look at graphics. The example chosen comes from mathematics: functions of one complex
variable. You can follow the material even if you are not familiar with the mathematical
concepts.
In Chapter 2 we look at the theory of writing good packages. The concepts introduced
here are used throughout the rest of the book. Understanding why things should be done in
a certain way might be interesting on its own, but you can also learn to apply the concepts
in a cookbook-style way. A skeletal package is provided, which you can use as a template
for writing your own packages.
Chapter 3 looks at issues of pattern matching and defining options for your func-
tions. Default values for parameters and options can make commands much easier to use.
Mathematica itself makes heavy use of these features.
Chapter 4 looks at different programming styles possible in Mathematica. It is here
that the preferred functional style is explained. Understanding this chapter allows you to
write better programs.
Chapter 5 looks at some aspects of how expressions are evaluated. If you want to write
sophisticated rules and definition.s you need to know about these things. Otherwise, you
can skip this material and return to it later as needed.
In Chapter 6 we introduce mathematical programming, a way of expressing mathe-
matical relations and formulae that is unique to Mathematica. If your application requires
simplification and transformation of symbolic expressions, you should read this chapter.
Numerical computations are the topic of Chapter 7. It explains how numerical compu-
tations are done and what kind of numbers Mathematica supports. You should consult it
as needed.
Mathematica has built-in rules and procedures for performing certain transformations
automatically. Advanced applications may make it necessary to change these built-in rules
or add others. Chapter 8 explains how this can be done. You should have read Chapter 5
before studying the material in here.
Chapter 9 treats input and output. Mathematica interacts with the rest of your computer
system in many ways, and this chapter deals with this interface. A discussion of typesetting
mathematical expressions in the frontend is also contained in this chapter.
xiv About This Book
Chapter 10 is about graphics programming. It presents some graphic utilities and looks
at the package ParametricPlot3D.m and at animations of graphics.
Chapter 11 looks at notebooks, available with the frontend for Mathematica. It looks
at the relationship between notebooks and packages. If you use notebooks or if you want
to write programs that run on machines with or without the notebook interface, you should
read this chapter. The frontend is programmable; we show some useful applications of
frontend programming.
Chapter 12 presents a larger application, iterated function systems. These systems of
affine maps are one aspect of the study of chaos and dynamical systems. Their implemen-
tation in Mathematica poses a number of interesting programming problems.
Appendix A contains programming exercises and their solutions. Appendix B is an
annotated bibliography for further reading about the topics of this book, and it contains the
list of references.
Some sections are marked as "Applications." They introduce a programming example
that makes use of the concepts covered in the preceding sections. They are independent
of the rest of the text. Some sections are marked "Advanced Topic." They have a higher
level of difficulty than the rest of the book or require higher mathematics. They, too, are
optional. The sections "Changes from Earlier Editions" are intended for readers familiar
with earlier editions of this book. They explain some of the major changes introduced with
Version 3 of Mathematica.
All examples were tested with Version 3 of Mathematica. The "live" calculation sequences
in this book were computed on a Sun SPARCstation 5 running SunOS 4.1.4. The examples
will not work with earlier versions of Mathematica. Those examples which interact with
the operating system of the computer on which Mathematica is running are, of course,
machine dependent and will look completely different on computers that do not run UNIX.
Listing init.m shows the commands that have been put into the initialization file init.m for
computing the examples in this book.
Some of the packages in this book depend on other packages. To read them into
Mathematica, you must have all of these imported packages available, too.
In the example Mathematica sessions in the later chapters, we generally no longer
show the command to read in the package that is the topic of the example. This com-
mand of the form «ProgramminglnMathematica 'Package' is assumed at the begin-
ning of every session that uses functions from the package in question. Even better
is Needs ["ProgramminglnMathematica 'Package' "] , which avoids loading a package
more than once.
Many examples developed in this book are now part of the standard Mathematica
packages. They can be found in subdirectories of AddOns/StandardPackages inside your
Mathematica installation. All remaining example programs and notebooks are part of the
Mathematica, Version 3, distribution from Wolfram Research. You can access them directly
About This Book xv
from the Mathematica CD-ROM or install them onto your hard disk using the Mathematica
installer. They will be installed into the directory AddOns/ExtraPackages/Programming-
InMathematica. A list of all programs is shown on page 355.
If the ProgramminglnMathematica directory is installed in AddOns/ExtraPackages
the help browser of Mathematica may be unable to find the on-line help provided. In
this case you should move the directory to AddOnslApplications or put the directory Ad-
dOns/ExtraPackages on the help path using the frontend's option inspector (item Global
Options e- File Locations [> AddOnHelpPath).
A package is identified by a name (the context name, as we shall see), for example
ComplexMap. The files in which we store successive versions of this package will be
called CornplexMap1.m, CornplexMap2.m, and so on. The final version will then simply
be called ComplexMap.m. Much of the text in successive versions of the same package is
the same, and we do not generally reproduce it in full.
Mathematica input and output is typeset in typewriter-like style: Expand [ (x-ry) ,,9] .
Parts of such input that are not literal, but denote (meta-)variables, are typeset in italics:
f [var _] : = body. Functions or commands are referred to by their name followed by an
empty argument list, for example Expand. []. Listings of programs are delimited with
horizontal lines and usually have captions beneath them. Major listings, tables, and figures
are numbered by section. The numbers have the form c.s-n, where c is the chapter number,
s is the section number, and n is a consecutive number within a section.
Names of files containing programs are typeset in this boldface style: Parametric-
Plot3D.m. Genuine dialogue with Mathematica is set in two columns. The left column
About This Book
contains explanations and the right column contains the input and output, including graph-
ics. You should be familiar with these conventions from the Mathematica book.
In the programming examples, I have tried to follow a uniform style for the indentation
of lines in a definition. Because Mathematica allows you to write deeply nested expressions,
lines are often rather long and have to be broken up so as to fit on the printed page.
In most programming languages you can define procedures, subroutines, or functions.
In Mathematica, all of these are just another way of looking at definitions, commands of
the form f [x_] : = body. Often we also use the term global rule. These terms are used
interchangeably, depending on which point of view we want to emphasize in a particular
situation. Rules proper are expressions of the form lhs - > rhs or lhs : > rhs. A substitution
is an expression of the form expr /. rule .
We can call Nf ] ] directly. Note that the numbers are In[2]:= Nf[5]
not converted to approximate numbers. Out[2]= {5, 16}
Nf[x_, prec_:$MachinePrecision] .=
Module[{nx = N[x, prec]},
(* numerical code goes here *)
As we saw in Section 7.2.3, built-in numerical methods typically provide the options
PrecisionGoal, AccuracyGoal, and WorkingPrecision. These options allow fine-
tuning their behavior in numerically critical applications. Let us see how we can add
these options to one of our own numerical methods, the functions defined in the package
Newton1.m from Section 4.4.2. The code described here is in the final package Newton.m.
Let us first turn to NewtonZero [], the main function in this package. The result of
NewtonZero [f, xo] is a number x so that f [x] is close to zero. We can use the value
of the option AccuracyGoal to determine how close to zero we should get. We have
achieved n digits of accuracy if Abs [f [x]] < 10. O"-n. Note that this interpretation
does not mean that x itself has necessarily an accuracy or precision of n. A precision
goal cannot be interpreted in this way, because zero has a precision of O. The default of
AccuracyGoal is Automatic; in this case, we set the accuracy goal to the precision of the
input (bounded below by machine precision, to guard against the case Xo = 0). The default
Automatic of WorkingPrecision translates to the accuracy goal plus a few extra digits
(unless the accuracy goal is smaller than machine precision; in this case we do not want to
perform any computations with arbitrary-precision numbers).
Having determined the working precision, we set the precision of Xo to this value, using
SetPrecision [] . There is one special case: if Xo is 0.0, SetPrecision [0.0, anything]
returns exact O. In this case, we use SetAc curacy [] to get an inexact zero. If the accuracy
of the initial value is smaller than the working precision, this command will increase it. In
most iterative processes, including Newton iteration, the accuracy (and even the value) of
the initial guess is unimportant. The new code of NewtonZero is shown in Listing 7.2-1.
Note that we treat the case where the accuracy goal is infinite specially. We do not need
to adjust any numerical settings, but we test the result for exact zero. The only change
required in NewtonFixedPoint is the treatment of the new options, in the same way that
356 #-Average Index
Mathematica commands are listed in this index only if they are treated in some detail. On
the other hand, you will find here all the commands developed in our example packages.
These commands are not built in and are, therefore, not listed in the Mathematica book.
The main entry for a topic is set in boldface. For typographical conventions, see page xv.
r function, 26 Powers
great dodecahedron, 111 expansion of, 166,224,337
great stellated dodecahedron, 112 negative, 182
hyperbolic sine, 75 PowerSum, 10
icosahedron, 109 $Pre, 217, 219
identity, 23 Pre-evaluation, 217
inversion, 14,20 Precision, 192
logarithm, 14 in numerical procedures, 199
minimal surface, 30, 346 increase of, 96, 195
Mobius transform, 2, 66 machine, 193
oak tree, 329 setting of, SetPrecision, 195
random walk, 336 Predicates
saddle surface, 160,274,275 for a language, 186
saw-tooth curve, 238 in patterns, 180
Sierpiriski gasket, 321, 324 pure functions as, 181
Sierpiriski sponge, 354 $PrePrint, 217, 251
sign function, 128 Prime number theorem, 84
sine function, 5, 276 PrimePi,84
small stellated dodecahedron, 112 primePi,84
sphere, 122,275 Print forms, 240
spherical harmonic, 140 Printing expressions, 181
spiral staircase, 288 PrintTime,135,217,218
square root, 18 Priority
Struve function, 235 of &, 131, 181
in typeset expressions, 265
tetrahedron, 108
of And and Or, 26
Van der Pol equation, 190
Probabilities, 323
Sfunction, 16 Probabilities, cumulative, 100, 322
Placeholder, 300
Procedures, xvi, 81
Platonic solids, 107
auxiliary, 33
Plot3D,273
numerical, 198
PlotLegend, 229 Product, 88, 155
Plots Products, 88
functions of complex variables, 3 expansion of, 166, 223
of several functions, 229 inner, 115
parametric, 39, 273 outer, 116
utilities for, 275 Programming
PlotStyle, 323 bad style, 34, 91
Point, 313 dynamic, 147, 150
Point, decimal, 192 efficient, 139, 173, 224, 234, 253, 276
PolarMap, 337 functional, 91, 347
Polygon, 107 functional in numerical codes, 210
Polyhedra good style, vi, 88, 92
description of, 107 mathematical, 88
regular, 107 numerical, 233
symbolic manipulation of, 109 object-oriented, 36, 347
Polyhedron, 107 procedural, 88, 347
Polynomials system, 279
normal form for, 161 Prompts, 258
Swinnerton-Dyer, 118, 150 Protect, 41
Position, 101, 104 Protected, 41
Position, in mapping, 104 PSDirect.m, 277
Positive, 227 Pure functions, 130,347
$Post,217,259 as predicates, 181
Post-evaluation, 217 constant, 132
364 Pure functions - Sorting Index