Mathematica as a Tool: An introduction with practical examples 3764350318, 0817650318, 9783764350314

Mathematica combines symbolic and numerical calculations, plots, graphics programming, list calculations and structured

179 78 25MB

English Pages 439 [438]

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Mathematica as a Tool: An introduction with practical examples
 3764350318, 0817650318, 9783764350314

Citation preview

Stephan Kaufmann Institute of Mechanics ETH Zentrum HGF38.4 8092 Zurich Switzerland e-mail: [email protected]

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Birkhauser was aware of a trademark claim, the designations have been printed in initial caps or all caps. Birkhiiuser and Stephan Kaufmann have used their best efforts in preparing this book. These efforts include the development and testing of the code which appears in this book. We make no warranty of any kind, expressed or implied, with regard to the code or the documentation contained in this book. The author and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of information appearing in this book.

A CIP catalogue record for this book is available from the Library of Congress, Washington D.C., USA Deutsche Bibliothek Cataloguing-in-Publication Data

Kaufmann, Stephan: Mathematica as a tool: an introduction with practical examples / Stephan Kaufmann. - Basel; Boston; Berlin: Birkhauser, 1994 Dt. Ausg. u.d.T.: Kaufmann, Stephan: Mathematica als Werkzeug ISBN 3-7643-5031-8 (Basel...) ISBN 0-8176-5031-8 (Boston) This work is subject to copyright. All rights are reserved, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, re-use of illustrations, recitation, broadcasting, reproduction on microfilms or in other ways, and storage in data banks. For any kind of use permission of the copyright owner must be obtained.

© 1994 Birkhiiuser Verlag Basel, P.O. Box 133, CH-4010 Basel Camera-ready copy prepared by the author Printed on acid free paper Cover design: Markus Etterich, Basel ISBN 3-7643-5031-8 ISBN 0-8176-5031-8 987654321

• Stephan Kaufmann

Mathematica as a tool

An introduction with practical examples

Birkhauser Verlag Basel' Boston' Berlin

• Preface More than ten years ago, I wanted to carry out coordinate transformations for Hamiltonian systems, in order to discuss the stability of certain equilibrium positions. Basically, the calculations only involved rational expressions, but they turned out to be extremely complicated, because the third and fourth order terms had to be included. After several months of filling whole blocks of paper with formulas, I was close to resignation. But, by a lucky incident, I met a colleague who showed me the computer algebra package Reduce. It still required a lot of patience and tricks, but Reduce finally did produce the desired results. After this experience, I wondered, why only a few engineers and scientists were aware of the strengths of such computer algebra programs. The mathematical treatment of scientific problems often leads to calculations which can only be solved "by hand" with a considerable investment of time, while a suitable computer algebra program produces the solution within a couple of seconds or minutes. Even if a closed symbolic solution is not possible, such programs can often simplify a problem, before the cruder tool of numerical simulations is applied. Subsequently, I turned to other work, and put the computer algebra aside. But in 1988, the new program Mathematica instantly impressed me by its combination of computer algebra, graphics, animations, an elegant programming language, and numerical tools. I decided to offer a lecture for the students of mechanical and civil engineering, mathematics, and physics at the Swiss Federal Institute of Technology (ETH Zurich), where I showed them how to use Mathematica as a tool for their work. In the course of three years, the corresponding lecture notes became quite bulky. They were inspired by the book by Stephan Wolfram [WoI88], and this relationship still shines through. When Thomas Hintermann from Birkhauser Verlag asked me to write a German book based on my lecture notes, I decided to take him up on it. During my work with Mathematica users, I had noticed that few of them really had studied the book by Stephen Wolfram. This has a positive and a negative side: On the one hand, it shows that Mathematica is designed in a very intuitive way. But on the other hand, the full strengths of the tool can only be used if one knows them. Many tasks can be simplified by small Mathematica programs; others require a detailed knowledge. This book presents a compact introduction to Mathematica. Some nontrivial examples are used as a motivation to study several aspects of the program. Readers who are not interested in the mathematical or physical aspects of these exam-

vi pIes, can simply skip these, and concentrate on the treatment of the equations with Mathematica. There is no intention to present a complete list of all the features and applications of Mathematica. I do not see much need for such a book because the documentation which comes with the program is well written, complete, and always up to date-and the field of applications is infinite. My intention is rather to bring you to the point where you know enough to help yourself and to solve your own problems. This English translation of my book contains several improvements to the first German edition. The major changes concern the Sections 1.8.2, 3.2.3, and 3.3.1, while minor adjustments and improvements have been made at many places.

o

Acknowledgments

Many people have helped to bring this to a good end. They all deserve my grateful acknowledgment. • First comes my wife Brigitta. Without her patience and understanding, I never could have tackled such a time-consuming task. • Paul Wellin corrected my English and added many valuable suggestions. • Leszek Sczaniecki from Wolfram Research, Inc. provided some useful hints. • Mahir Sayir always supported my work very generously. • The discussions with my colleagues at the Institute of Mechanics (ETH), especially Stefan Messmer, have added many fruitful thoughts. • Valuable criticism and constructive suggestions have come from the very patient students of my lectures. • All people I met at Birkhauser Verlag are highly motivated. My special thanks go to Thomas Hintermann for the general and Justin Messmer for the technical support. • And finally, I would like to thank the Napier families in Menard, Keller, and Dallas (Texas). They were my hosts when I was an AFS foreign exchange student and gave my a unique chance to learn at least some English. Stephan Kaufmann Zurich, Switzerland July 1994

• Table of Contents Introduction .......................................................................................

Part 1.

1

Basics

1.1 Getting Started ........................................................................... 1.1.1 Starting and Quitting .......................................................... 1.1.2 Interrupting and Quitting ...................... ..............................

9 9 12

1.2 Help! ...........................................................................................

14

1.3 Numerical Calculations...... ...................... ...................... ............. 1.3.1 Simple Examples .......... .......................... .................. ......... 1.3.2 External Packages: Units ................................................... 1.3.3 Large Numbers: The RSA Public-Key Cryptosystem .........

17 17 25 32

1.4 Symbolic Calculations ........... ....................... ...................... ........ 1.4.1. Polynomials .............. ...................... ........ ................ ............ 1.4.2 Equations ............... ...................... ...................... ................ 1.4.3 Calculus ..... ............... .......................... ................... ............

44 44 54 66

1.5 Plots: Different Pendulums......................................................... 81 1.5.1 Two-Dimensional Plots ...................................................... 81 1.5.2 Example: The Triple Pendulum .......................................... 89 1.5.3 Three-Dimensional Graphics and Animation: A Rotating Double Pendulum ............................ ................. 106 1.5.4 Parametric Plots: A Rotating Double Pendulum ................. 121 1.5.5 Plotting Data: The Random Generator .............. ................. 130 1.6 Lists ............................................................................................ 1.6.1 Creating and Formatting Lists .......................... .................. 1.6.2 Calculations with Lists, Pure Functions ............................. 1.6.3 List Manipulation: The Cross Product ................................ 1.6.4 Vectors, Matrices, Tensors: The Jacobian ......................... 1.6.5 Eigenvectors and Eigenvalues: An Oscillator ............ ........

138 138 143 148 158 164

1.7 Graphics Programming .............................................................. 1.7.1 The Structure of Graphics .................................................. 1.7.2 Example: Animation of the Triple Pendulum ...................... 1.7.3 Example: The Oscillator .....................................................

172 172 178 184

1.8 More Selected Tools...... ................................ .................. ........... 190

viii

1.8.1 Graphics and Sound .......................................................... 1.8.2 Complex Numbers ................ .................... ..... .................... 1.8.3 Sums, Products, Series ............................... ...................... 1.8.4 Data Analysis, Interpolation ............................................... 1.8.5 Transformations ................................................................. 1.8.6 Mathematical Functions ..................................................... 1.8.7 Polynomials ........................................................................ 1.8.8 Linear Algebra, Linear Programming ................................. 1.8.9 File Manipulation ................................................................ 1.8.10 Custom Configuration ......................................................... 1.8.11 Resources ..........................................................................

Part 2.

190 195 198 201 207 213 214 216 217 219 222

Structure

2.1 Expressions ................................................................................ 229 2.1.1 The Structure of Expressions ............................................. 229 2.1.2 Working with Parts of Expressions ..................................... 231 2.2 Patterns ...................................................................................... 2.2.1 Simple Patterns .................................................................. 2.2.2 Restricted Patterns ............................................................ 2.2.3 More Complicated Patterns ............................................... 2.2.4 Example: A Simple Integrator .............................................

233 233 237 242 248

2.3 Transformation Rules and Definitions ........................................ 2.3.1 Transformation Rules ......................................................... 2.3.2 Definitions .......................................................................... 2.3.3 Attributes ............................................................................

251 251 255 263

2.4 Evaluation and Tools for Programming ...................................... 2.4.1 Standard Evaluation ........................................................... 2.4.2 Special Evaluation ............................................................. 2.4.3 Conditionals, Loops, and Control Structures .....................

268 268 271 277

2.5 Modularity ................................................................................... 290 2.5.1 Local Variables and Constants ........................................... 290 2.5.2 Contexts and Packages ..................................................... 297 2.6 Strings, Text, Messages ............................................................. 2.6.1 Printing Text ....................................................................... 2.6.2 Arranging Text .................................................................... 2.6.3 Built-in Formats .................................................................. 2.6.4 Formats for Numbers ......................................................... 2.6.5 Subscripts and Superscripts ..............................................

308 308 309 310 313 315

ix

2.6.6 Custom Formats ................................................................ 318 2.6.7 Strings ................................................................................ 321 2.6.8 Messages ........................................................................... 323

Part 3.

Programming

3.1 Programming Methodologies ..................................................... 3.1.1 Procedural Programming ................................................... 3.1.2 Recursive Programming .................................................... 3.1.3 Functional Programming .................................................... 3.1.4 Rule-Based Programming .................................................. 3.1.5 Programming with Constraint-Propagation ........................ 3.1.6 Data Types, Object-Oriented Programming .......................

331 331 332 335 336 337 340

3.2 Developing Programs ................................................................. 3.2.1 Debugging .......................................................................... 3.2.2 Example: NonNegati veQ \ ............................................... 3.2.3 Example: AbsArg \ ............................................................ 3.2.4 Example: RSA \ .................................................................. 3.2.5 Example: Perturbation \ ...............................................

342 342 348 353 355 359

3.3 Numerics .................................................................................... 3.3.1 Compiling Expressions: Fractals ........................................ 3.3.2 Precision and Accuracy ...................................................... 3.3.3 Controlling Numerical Built-in Functions ............................

368 368 376 378

3.4 Long Calculations: RSA ............................................................. 3.4.1 Primes for RSA .................................................................. 3.4.2 Saving Results in a File ..................................................... 3.4.3 External Programs, Calculations in the Background ..........

384 384 386 389

References ....................................................................................... 395 Index ................................................................................................. 399

I

Color Plate 1: The potential of a rotating double pendulum (page 112)

Color Plate 2: The potential of a rotating double pendulum in configuration

space (page 124)

II

f

1 f

?

f

r

1

7

) s

c

Color Plate 3: Some positions of the triple pendulum (page 183)

?

III

/ J\

J\

/\

J\

/\

/\

/\

J\

/\

/\

/~

I

/\

I

/~

I

I

I

Color Plate 4: Some positions of the oscillator (page 189)

IV

Color Plate 5: A fractal for z7-1 (page 374)

Color Plate 6: A fractal for z-7-1 (page 374)

1

• Introduction o

What is Mathematica?

The software program Mathematica combines the following features into a unified, interactive environment: • numerical calculations, • symbolic calculations, • plots, • list calculations, • functional, procedural, and rule-based programming, • graphics programming, • animations, • structured documentation. It is therefore an ideal tool for people who use any kind of mathematics in their work. Mathematica is available for the Macintosh, the PC (386 or better), and for practically every computer using an operating system based on UNIX or VMS. The software has been and is further developed by Wolfram Research, Inc. (100 Trade Center Drive, Champaign, IL 61820-7237, USA). It is available from every software distributor.

o

About this Book

This book is primarily written for engineers, scientists, and applied mathematicians. It is an introduction, showing the aspects of Mathematica which are principal for such users. It it neither meant to be a complete reference manual (as [WoI91] or [Wol92]) nor a complete guide through all possible applications of the software-no book could provide that. The main goal is rather to gain enough skill such that after working through the book, the reader can solve his or her own problems independently. To get an idea of the strength of the software, we will discuss several practical examples. They are mostly taken from mechanics, since this is the author's main field of research-but also because it belongs to the common knowledge of most

2

readers. The examples give motivation to study different techniques of working with Mathematica. Readers in a hurry can simply skip the derivation of the equations and concentrate on their solution with the help of the program. The book is divided into three parts. The first part gives an overview of the main built-in commands of Mathematica. These commands will allow us to solve a vast array of problems without possessing a detailed knowledge of the exact structure of the program. In the second part, we will study the detailed syntax and the evaluation process. We will learn that many calculations can be described with the help of patterns, transformation rules, and definitions. This knowledge will be the base for programming in Mathematica. The third part is fully dedicated to programming. We study several techniques and then apply them to examples. Every section contains a summary of the new commands. Together with the detailed index at the end, the book can therefore also be used as a small reference to Mathematica. As already mentioned, the reference manual is the Mathematica book [WoI91] by Stephen Wolfram, which comes with every copy of the program. Most sections contain small exercises at the end. These are deliberately kept very simple, and serve to deepen the subjects. The reader will surely find enough further, much more interesting and important examples in his or her daily work. Some paragraphs are printed with small letters. They contain more specialized thoughts or techniques and can be skipped at the first reading.

D

Conventions

Examples of Mathematica input and output are found throughout the text. They are printed very much as they are displayed by the program, for example: In[1]:=

Prime [1000000)

Out[1}=

15485863

The labels In[1}, Out[1}, etc. are generated automatically by Mathematica. They should not be inserted when an example is reproduced by the reader.

A new Mathematica session is started for every section-the line numbers (In[I], etc.) restart with 1. The exact reproduction of the sessions is only possible

by starting a fresh kernel for every section.

3

Introduction

The names of objects in Mathematica can be quite long. It sometimes happens that a name is hyphenated in the text. In such cases, the hyphen does not belong to the name. Table 0-1 shows the meaning of the fonts and styles used throughout this book. Meaning

Format Integrate[x 2, xl

Mathematica expressions in the text

expr

variable parts to be filled in by the user, e.g., Integrate [expr, xl

Help

commands of the notebook interface

math

commands of the operating system

filename

names of files

A

Table 0-1: The fonts and styles used in this book

o

More about Mathematica

The Mathematica kernel-the part of the program which actually performs the ca1culations--consists of several 100000 lines of source code, written in an object oriented extension of C. Standard C code is produced by a precompilation. Because only very few assumptions about the target computer are made, it is possible to compile essentially the same source code on all systems. In this way, the same program can be used on a large variety of computers, from the Macintosh and the PC to high performance systems. On most platforms (Macintosh, NeXT, PC with Windows, X-based window systems), there exist/ront ends, which handle the interaction between the user and the kernel. Even though many forms of front ends are possible, the most common ones use interactive documents, called notebooks. These notebooks can consist of Mathematica input and output, text, graphics, animations, and sound, organized in hierarchical cells (see Figure 0-1 for an example). As in a word processor, the documents can be formatted in a sophisticated fashion. This makes notebooks an ideal tool for presenting pedagogical material or research results, and for keeping the daily work in a clear form.

4

,

,

File

EIIII

Cell

10

Graph

Finll

Rclion

Style

Winllow

Help

01

Perl Notebook .ma

]

• Examples

o AIIlifuuy Fungously to tbe puom .. e,. of DSolve

,iii! ",+

~ .. ..

Iii,: "m,

I:Ii

:.:

1

q'4// .•

PolyOrderSolutionLi st I ( ~ .. I t ) + eps (x ' ItJ)'2 + xlt)

{t

== o.

,1:1:

,[I,

II:,' J

,>

xIOI •• 1. x ' 101 •• 0 I. xl tl. t. eps . 2) 0 q"U/.

PlotlEvaluatel " 1121l / . eps -)

. 11.

(t .

o. SIll

] I

Figure 0-1: A notebook on the Macintosh front end

The kernel and the front end can work independently. It is even possible to run them on different machines. One can therefore, for instance, have the front end on a Macintosh Plus and the kernel on a high-end workstation, combining the userfriendliness of the first with the computing power of the second. The notebook interfaces have a common set of basic features--evaluation of commands, organization of cells, formatting, etc. The details of the available commands may differ. Since the aim of this book is the discussion of the Mathematica kernel, we will not give an extensive discussion of the different front ends. A very good overview can be found in the documentation that comes with the program. The reader is advised to look into this booklet, because a good knowledge of the front end greatly simplifies the work with Mathematica.

Introduction

D

5

More about this Book

This book is based on notes and notebooks which the author used for an introductory lecture on Mathematica at the Swiss Federal Institute of Technology (ETH Zurich). It was held for students of the engineering, mathematics and physics departments. The Mathematica input and output was produced on Macintosh computers (often in connection with a kernel on Sun SPARCstations). The results were then moved to FrameMaker. The formatting was chosen to resemble the original notebooks. The output was produced with Version 2.2 of Mathematica. lIE

The examples using the Timing function are consistent only within the single sessions, because kernels on different machines were used. Some graphics were scaled to a reasonable size with an arbitrary scaling factor.

D

Mathematica Material

Wolfram Research, Inc. maintains an information service for Mathematica material, called MathSource. It can be used with electronic mail,ftp, or gopher. After sending a message with content he 1 pin t r 0 to the address rn at hsou r c e@wri . corn, one automatically receives an introduction to the service. The title (S U bj ec t) is irrelevant in all mail to MathSource. Anybody interested in Mathematica can register to an electronic mail distribution list by sending a short note to rna t hg rou p - req ues t@yoda . phys i cs . un c . ed u. The subscribers regularly get mail from users worldwide, with discussions, questions, and answers around Mathematica. The usenet information system contains a conference on symbolic calculation. It is called sci. rna t h . syrnbo 1 i c. Quite a lot of the talk there is also about Mathematica.

D

Software

All packages developed in this book, as well as all the Mathematica input from the examples, is available from MathSource. The corresponding message numbers (nnnn-nnn) can be found by sending a mail with content

Find Author:"Stephan Kaufmann" to the address ma t hsou rce@wri . com. A mail containing Sen d nnnn-nnn provides the desired data.

6 Readers who do not have access to electronic mail might get the files directly from the author (on a 3.5" floppy disk) by sending $10 in cash to: Stephan Kaufmann Institute of Mechanics ETHZentrum CH-8092 ZUrich Switzerland Please add a short note explaining the desired format (Macintosh or MS-DOS).

Part 1.

Basics

8

1. Basics

In this first part of the book, we study Mathematica from a "naive" point of view. Without worrying much about the details of its input syntax, we can learn to use a great number of its tools by simple (and some sophisticated) examples. The first two chapters (1.1 and 1.2) cover the basics-how to start and quit the program, and how to get help. In Chapter 1.3, we study the techniques of numerical calculations and of using extensions of Mathematica in the form of packages. Symbolic calculations are treated in Chapter 1.4. The results of such calculations need to be visualized qualitatively. This brings us to the graphics capabilities of the program (Chapters 1.5 and 1.7). The very important subject of lists is treated in between (Chapter 1.6). Lists are not only needed for the construction of custom graphics, they are also used to represent vectors and matrices, and they are the prerequisites of elegant programs. The introductory part of the book is completed by covering a selection ofJurther tools (Chapter 1.8). In some sections, we let us guide by practical examples. Many of these will be used several times throughout the book. We will not try to fully understand the underlying mathematics and physics of the examples. The emphasis is put on their treatment with the help of Mathematica. If the derivations of the equations are too sketchy, the reader might just accept the results and concentrate on the work done with Mathematica, or refer to the literature (e.g., [Fli.i62]).

o

About the Picture

The "cushion" on the previous page can be produced by the command: In[1]:=

ParametricP1ot3D [ {

Cos [v] Sin [u] , Sin[v] Cos[u], Cos[u] },

{u, 0, Pi}, {v, 0, 2 pi}, ViewPoint -> {3, -1, 1}, Boxed -> False, Axes -> False, P1otPoints -> {30, 30}]

1.1 Getting Started

9

• 1.1 Getting Started This chapter briefly explains the basic handling of Mathematica. We will learn how to start a session, how to quit it, and how to interrupt calculations. Some details depend on the interface used, and those should be looked them up in the documentation that came with the program.



1.1.1 Starting and Quitting

Users of a notebook front end will start the program and enter their input slightly different from users of a text-based interface.

o

Mathematica with Notebook Interface

As happy users of a notebook front end (see Subsection "More about Mathematica" on page 3) we start Mathematica in the window-based environment, typically by a double mouse click on the corresponding icon. As soon as the program has loaded, which may take some time, an empty notebook window appears. The Mathematica commands (e.g., 1 + 1) may be typed into it. In{1j:=

1 + 1

Out[1]=

2

They evaluate as soon as we select the corresponding menu (Evaluate Selection), or press the key, or (simultaneously) the and the keys. It may take some time to load the kernel for the first evaluation.

The result of the evaluation (in our example, hopefully 2) will appear in a new cell on the next line. The cells automatically are labelled In[1], Out[1], In[2], Out[2], etc. We can use these labels to reference previous results within a session (see Subsection "Using Previous Results" on page 19). Hitting the key alone will not evaluate a line; it simply breaks the line. This allows us to produce input cells containing many lines.

Notebooks are very attractive, because they not only allow us to save and reuse Mathematica sessions in a practical manner, but they also allow us to add titles, text, graphics, and sound. By using the hierarchical structure of the cells,

10

1. Basics

notebooks can be turned into "live" documents, suitable to be given to other users, or for presentations.

o

Mathematica with Text-Based Interface

Unfortunately, working with Mathematica is a little less comfortable without a front end. We start the program in a terminal window by typing the corresponding command, usually mat h. After some messages about the program version, the first input line appears.

fafner% math Mathematica 2.2 for Solaris Copyright 1988-93 Wolfram Research. Inc. -- Open Look graphics initialized -In[IJ := We can now enter a first command. Usually, the normal line editing facilities of the window system can be used to change the current input line. After pressing the key-the insert mark has to be at the end of the line-the current line is analyzed by Mathematica. If it contains a full command, it is evaluated. If it does not contain a full command, we either get an error message

In[IJ:= IJ Syntax::bktx: "1" has extra "J" after it. In[IJ:= or nothing happens (see the example below). The first case means that our line contains a syntax error. It must be retyped-hopefully, this time right. The second case means that the input was syntactically right, but incomplete. We are then expected to supply the rest of the input on the next line(s). I@>

Input containing multiple lines can be produced by leaving each line syntactically incomplete. We achieve this by ending the lines with arithmetic operators (e.g., +, -, *, I), or if we open a parenthesis and close it on a subsequent line.

11

1.1 Getting Started In[1]:= 1 + 2 + 3 Out[l]= 6 In[2]:= (1 + 2 + 3) Out[2]= 6

The lines are automatically labelled (In [1] , Out [1] , In [2] , Out [2] , etc.), so that results, and input, can be referenced and reused later on in a session (see Subsection "Using Previous Results" on page 19). For lengthy input lines, the line editing functions often do not suffice. Several editing techniques can be used: • For normal work, it might be a good idea to have an editor running in a separate window. We can then edit the input in the editor window and use the Copy and Paste features of the window system to move it to the Mathematica window. • Alternatively, we can save our input, which was created in an editor, to a file (e.g., with the name filename) and read it into Mathematica with the command l:n

The tangent function is written as Tan, and its parameters must be put into brackets. Your input is interpreted as the symbol Tg times the number 0 . 5.

". Why does Mathematica leave the expression n [ 1/7] unevaluated? In[2}:=

n [1/7 ]

Out[2}=

n [ '7 1

>l:n

1

Everything works fine, if you use a capital N.

23

1.3 Numerical Calculations In{3]:=

N [ 1 /7 ]

Out{3]=

0.142857

All function names in Mathematica start with capital letters. Upper and lower cases are distinguished.

o

Summary

• Parameters of Mathematica functions must be put into brackets. Bracketing Meaning ()

grouping

[1

arguments of functions

{}

lists

Table 1-5: Parentheses, Brackets, Braces Expression

Example

Notation

Number of Arguments

f[xl

N[Pil

standard

any number

N

prefix

one

postfix

one

f x

@

/I

x f

@

pi

Pi /IN

x - f - y Pi - N - 10 infix

two

Table 1-6: Different notations of Mathematica functions Abbreviation

Meaning

%

the last result

%% ... % (n times)

the nth previous result

%n

the result of the output line Out{n]

Table 1-7: Using previous results Expression Full Notation

Meaning

x+y

Plus [x, yl

add

-x

Times [-l, xl

minus

Table 1-8: Arithmetic

24

1. Basics

Expression Full Notation x y x*y

Times [x, yl

x/y

Times [x,

x"y

Power [x, yl

Power [y,

Meaning multiply

-Ill

divide power

Table 1-8: Arithmetic Expression

Meaning

N[exprl

a numerical approximation of expr

N[expr,

a numerical approximation with n digits

nl

Rationalize [exprl

convert numerical approximations, which are close enough to rationals, into rationals

Rationalize [expr, dxl

convert numerical approximations into rationals, with an error of at most dx

Sqrt [xl

the square root

Exp [xl

the exponential function

Log [xl

the natural logarithm

Log[b, xl

the logarithm of x to the base b

Sin [xl, Cos [xl, Tan [xl

the trigonometric functions

Csc [xl, Sec [xl, Cot [xl

more trigonometric functions: Csc = l/Sin, Sec = l/Cos, Cot

ArcSin [xl, ...

the inverse trigonometric functions

Sinh [xl, ...

the hyperbolic functions

ArcSinh [x], .,.

the inverse hyperbolic functions

n!

the factorial function (product of 1, 2, 3, ... , n)

Abs [xl

the absolute value

Round [xl

round to the next integer

Min[x, y,

... l

the smallest number in (x, y, ... )

Max [x, y,

... l

the largest number in (x, y, ... )

Table 1-9: Simple functions

= l/Tan

25

1.3 Numerical Calculations

Constant

Meaning

Degree

the scale factor from degrees to radians

pi

1t ""

E

e"" 2,71828

I

the imaginary unit, ~

Infinity

00

3,14159

Table 1-10: The most important constants

o

Exercises

1. Does Mathematica round up or down at .5?

2. Find the smallest and the largest number in the triple

(

1 7' 1O!, e 15 ). arctan 10-

3. How good does the square root of 10 approximate the value of 1t? What about the square root of 9.8696044? Find an even better approximation of 1t by a square root. 4. Study empirically the precision of Stirling's formula: In(n!)



=(n+~}nn-n+ln(J21t).

1.3.2 External Packages: Units

A common application of pocket calculators is the conversion of physical units. If the necessary tables are not within reach, Mathematica should be. One cannot expect that every conceivable application is already built into Mathematica. The program would become much too large, and the memory, necessary to run it, even more demanding. Instead, we have the possibility to load extemalpackages. These are files containing ordinary Mathematica code with definitions of new functions or extensions of existing functions.

26

1. Basics

Packages are available from several sources (e.g., from MathSource, see page 5) or can be written by the user. A set of standard packages is distributed with Mathematica. We find it, organized by subject, in the directory Pac k age s. We can use the command True]

Oulf1~=

xl 29 - Cos[2 ---2----

+ 4 Sin[xl

The same option does the opposite, when Factor is used. In[16}:=

Factor [%, Trig -> True]

Oulf1~= (2

+ Sin[xl)2

Through two alternative steps, we ended up with the same result that already was produced by Simplify. Writing mathematical expressions "as simple as possible" is quite a tricky task. Let us look at the following polynomial:

=

In[17):=

poly1

Out[17}=

(1 + x) 7

(1 + x) "7

Written in this factored form, it surely is simpler than expanded. In[1S}:=

Expand [poly1]

Oulf1~= 1

+ 7 x + 21 x 2 + 35 x 3 + 35 x4 + 21 x 5 + 7 x 6 + x 7

But another example shows the opposite effect: In[19}:=

=

poly2

1 - x"7

x7

Out[19}= 1 In[20}:=

Factor [poly2]

Out[20}=

(1

-

x)

(1 + x

+ x

2

+ x

3

+ x

4

+ x

5

Simplify is smart enough to handle both situations:

+

48

1. Basics

In[21}:=

Simplify [polyl]

Out[21}=

(1 + x) 7

In[22}:=

Simplify [poly2]

Out[22}= 1 - x 7

We pay for this with considerable response times of Simplify in the case of more complicated expressions.

o

Rational Functions

Let us consider the following rational expression: In[23}:= Out[23}= In[24}:= Out[24}=

quotl = poly2 /

(1 - x)

1 - x7

I-:-x-

S impl i fy [quot 1]

1 - x7

I-:-x-

Its numerator and denominator can be cancelled with Cancel. In[25}:=

Cancel [quotl]

Ouq2~= 1

+

x + x 2 + x 3 + x4 + x 5 + x 6

Simplify does not convert the polynomial back into a fraction-would that be a simplifi-

cation? In[26}:=

Simplify [%]

Ouq2~= 1

+

x + x 2 + x 3 + x4 + x 5 + x 6

We study the most important functions for calculations with polynomials by looking at some examples: In[27}:=

quot2 = (a + b) "21 (a - b) "3 + 1/ (a - b) "2

Ouq2~=

(a - b)-

2

(a + b) 2 + -------(a - b) 3

To expand the denominators, we use:

49

1.4 Symbolic Calculations In[2B}:=

ExpandDenominator [quot2] (a + b) 2

1

Oulf2~= ~2-=-2-~-b-:-b2

+

~3-=-3-~2-b-:-3-~-b2-=-b3

and for the numerators: In[29}:=

ExpanciNumerator [quot2]

o

(a _ b)-2 + a 2 + 2 a b + b 2 ---(~-=-b)3----

ulf2~=

Both, the numerators and the denominators, are expanded by: In[30):=

ExpandAll [quot 2]

1

Oulf3~= ~2-=-2-~-b-:-b2

a2

+

~3-=-3-~2-b-:-3-~-b2-=-b3

2 a b

b2

+

~3-=-3-~2-b-:-3-~-b2-=-b3 + ~3-=-3-~2-b-:-3-~-b2-=-b3

Maybe everything should be brought over the common denominator: In[31}:=

Together [quot2]

a + a2 - b + 2 a b + b2 Out[31}= - - ---- - (~-

=-b) r- ------

Apart constructs a decomposition into partial fractions: In[32}:=

Apart [quot2, a]

-4 b 2

Ouq3~= (=~-:-b)3

1 - =a-+-5

+

1 + 4 b

(=~-:-b)2

Because the fraction contains two variables, we have to tell which one should be used for the decomposition. Some more elementary functions for the manipulation of polynomials and rational expressions are FactorTerms, PowerExpand, and ComplexExpando Short explanations are listed in Table l-2l.

50

o

1. Basics

Values, Rules, Lists

We now want to evaluate expressions by substituting numbers for the variables. We do this by giving a rule, which shall be used for the expression. Rules have the form lhs - > rhs, where, in the simplest case, the left hand side is a variable and the right hand side a value. Setting options (e.g., Trig -> True) is another example for rules. An expression is evaluated with a rule, if we write a / . between the two. Let us substitute the value 3 for a in quot2. In[33}:= Out[33)=

quot2 /. a -> 3 (3

-

b)

-2

+

(3+b)2

(]-=-1;)3

Several substitutions can be combined into one rule, if they are separated by commas and put into curly braces { } . This defines a list of rules. Such a list of single rules acts like a rule. In[34}:=

quot2 /.

31

Out[34}= - ( 4: -

{a - > 3, b - > 5}

)

Lists are a very important structure in Mathematica. Among other things, they are used to construct vectors and matrices (see Chapter 1.6).

The rule can be given a name:

=

{a -> 3, b -> 5}

In[35}:=

numRule

Oulf3~=

{a -> 3, b -> 5}

In[36}:=

quot2 /. numRule

Out[36}= -

(4:31- )

A single element of a list is referenced by using double square brackets. In[37}:=

numRule [ [2] ]

Out[37}= b

-> 5

The elements are numbered from left to right, beginning with 1.

1.4 Symbolic Calculations

o

51

Unwanted Infinite Recursions

We close with a remark for programmers. Anyone who has already written procedural programs (in Pascal, C, Fortran, etc.), might soon use the following definition: In{38}:=

y = y

+ 1

$RecursionLimit: :reclim: Recursion depth of 256 exceeded. Out{38}= 250 + Hold[l + y]

There seems to be a problem with that. We will return to this in the Sections 2.3.2 and 2.4.2. At the moment, the following short explanation shall suffice: A definition like In{39}:=

x = a

Out{39}= a

is interpreted in such a way, that the symbol x shall from now on be replaced by the value, which a has now. In a calculation like In{40}:=

Y = Y + 1

$RecursionLimit: :reclim: Recursion depth of 256 exceeded. Out{40}= 249 + Hold[l + y]

Mathematica tries to find the value of y. To do this, y has to be taken and 1 added to it. Because y is a symbol, and has no value, this leads to the recursion.

After setting an initial value, everything works fine: In{41}:=

Y =

a

Out{41}= a In{42}:=

Y

Y + 1

Out{42}= 1 + a

In Chapter 2.4, we will discuss how procedural programs are written properly.

1. Basics

52

o

Summary

• Mathematica expressions are not changed automatically. Exceptions to this are only the most simple rewrites. Expression

Meaning

... } a list with elements x, y, ...

{x, y,

the nth element of a list

list [ [n]]

Table 1-18: Lists Expression

Meaning

lhs -> rhs

a simple rule

{lhs l -> rhsl' Ihs2 - > rhs2'

... } a rule consisting of several sub-rules evaluate the expression expr by using the rule

expr /. rule

Table 1-19: Rules Expression

Short Form Meaning

Clear [x]

x

=

Clear["Global'·"]

clear the definitions for x clear all definitions (in the global context) of the current session

Table 1-20: Clearing definitions Expression

Meaning

Expand [expr]

expand products and powers

Expand [expr , Trig -> True]

expand, and replace products of trigonometric functions by functions of multiple angles

ExpandAll [expr]

apply Expand to all parts of expr

ExpandNumerator [expr]

expand the numerator

ExpandDenominator [expr]

expand the denominator

ComplexExpand [expr]

expand complex expressions, by assuming that all variables are real (see Table 1-90 on page 197 for more details)

Table 1-21: Manipulations with polynomials

53

1.4 Symbolic Calculations

Expression

Meaning

PowerExpand [expr]

transform (x if to xPyP, etc.

Factor [expr]

factor (over the ring of the integers)

Factor [N [expr]]

factor numerically (over the approximated real numbers)

Factor [expr, Trig -> True]

factor, and replace trigonometric functions of multiple angles and sums by products of trigonometric functions

Factor [expr, Gaussianlntegers -> True]

factor over the ring of the Gaussian integers

FactorTerms [expr]

pull out common numerical factors

Simplify [expr]

simplify the expression

Cancel [expr]

divide the numerator and the denominator by their gcd

Apart [expr]

the partial fraction decomposition

Apart [expr , var]

the partial fraction decomposition, where all variables, except var, are treated as constants

Together [expr]

write a sum of rational expressions over their common denominator

Collect [expr, x]

collect the powers of x

Table 1-21: Manipulations with polynomials

o

Exercises

1. Factor a + 2JaJb + b.

2. Why does a + 2J;ib + b not factor? How can you make it factor? 3. Why does ax 2 + bx + c not factor? 4. The polynomial x 2 - 3 does not factor over the integers or the Gaussian integers. Find another factorization. 5. Consider ( a-I) (b 2 + 1) (b-2)5

54

1. Basics

Expand the numerator and the denominator separately, and together. Write the result as a single fraction. What is the partial fraction decomposition of it? Evaluate it for a = 7 and b = 11. 6. Write sin (x) + cos (y) and sin (x) cos 2 (y) as functions of sums and differences of the angles. 7. Study the functions FactorTerms, PowerExpand, and ComplexExpando 8. Clear all definitions of the current session.



1.4.2 Equations

o

Single Equations

Mathematica can handle equations, as well. To differentiate between equations and definitions, equations are written with a double equal sign (= =). In{1]:=

a x"2 + 7 b x + 15

Out[1}=

15 + 7 b x + a x 2

== ==

0 0

We can name equations by using name= for the definition and lhs==rhs for the equation. In[2]:=

equation1

Oulf~= 15

+ 7 b x

=

a x"2 + 7 b x + 15

+ a x2

==

0

0

Equations can be solved with the help of the function Solve. Its first parameter must be the equation; the second parameter is the variable, for which the equation shall be solved. In[3}:=

Solve [equation1, xl

Oulf~=

{{x -> =1_~_=_§g~~!=~Q_~_~_~~_~_1},

2

2

{x -> =1_~_~_§g~~1=§Q_~_~_~~_~_1}} 2 a

55

1.4 Symbolic Calculations

The result is a list of two rules (see Subsection "Values, Rules, Lists" on page 50) for the variable, corresponding to the two solutions. The rules themselves are put into lists. This is necessary to handle the possibility of more than one variable (see below). To test the result, we substitute it into the equation (by using a / .). In[4]:=

equationl /. %

Out[4]=

{15 + --------------2-a--------------- +

7 b

(-7 b - Sqrt[-60 a + 49 b 2 ]) 2

(-7 b - Sqrt[-60 a + 49 b ])2 __ -------------4-a--------------

15 +

0, 2

~_~_l:~_~_±_§g~~l:§Q_~_±_~~_~_ll +

2 a

2

2

1:~_~_±_§9~~1~§~_~_±_~~_~_11_

==

O}

That does not look convincing. Because Mathematica does not simplify automatically, we have to ask for it. In[5]:=

Simplify [%l

Out[5]=

{True, True}

Both solutions, if inserted into the equation, yield equations which simplify to True. Note that we have substituted two solutions-a list of lists-into one equation. This gives us two equations. The reader surely could have solved this simple quadratic equation by hand. This might not be true for the following cubic equation.

= x A3

+ 3 xA2 - x + 1

==

In[6]:=

equation2

Out[6]=

1 - x + 3 x2 + x3

In[7]:=

solution2

Out[7]=

4 21/3 {{x -> -1 + ----------------------- + (-108 + 12 Sqrt[33])1/3

==

0

Solve [equation2, xl

1:1Q~_±_1~_§9~~1~~11:~~} 3 21/3

{x -> -1 -

0

'

~_~:~~_11_±_!_§g~~1~11_ (-108 + 12 sqrt[33])1/3

11_:_!_§g~~1~11_1:1Q~_±_1~_§g~~1~~11:~~} 6 21/3

'

56

1. Basics

Is the result correct? Inf8]:= Outf8]=

subst

=

equation2 I. solution2 4 21/3

{2 -

(=108-:-1;-~;~~[331)173 i=~Q~_!_~~_eg~tl~~ll:~: + 3 21/3

4 21/3 3 Power[-l + ----------------------- + (-108 + 12 sqrt[33])1/3

i=~Q~_!_~~_eg~tl~~ll:~: 3 21/3

2] +

'

4 21/3 Power[-l + ----------------------- + (-108 + 12 Sqrt[33])1/3

i=~Q~_!_~~_eg~tl~~ll:~: 3 21/3

'

3]

==

0,

2 1/3 (1 + I Sqrt[3]) 2 + 2 ----------------------+ (-108 + 12 Sqrt[33])1/3

i~_=_~_eg~tl~ll_i=~Q~_±_~~_eg~tl~~ll:~~ 6 21/3

3 Power[-l -

+

~_~:~:_i~_!_~_eg~tl~ll_ (-108 + 12 sqrt[33])1/3

i~_=_~_eg~tl~ll_i=~Q~_!_~~_eg~tl~~ll:~:

6 2 1/3 2 1/3 (1 + I Sqrt[3]) Power[-l - 2----------------------(-108 + 12 Sqrt[33])1/3 (1 - I Sqrt[3])

(-108 + 12 sqrt[33])1/3

----------------6-;173----------------, 2 +

~=~~~::ii;=~;~~~;;f~t73

+

(1 + I Sqrt[3]) (-108 + 12 sqrt[33])1/3 --------------------------------------- + 6 21/3

3 Power[-l -

2 2 1/3 (1 - I Sqrt[3])

(=108-:-1;-~;~~[331)173

-

'

2] +

3]

0\

57

1.4 Symbolic Calculations

(1 + I Sqrt[3))

(-108 + 12 sqrt[33))1/3

----------------6-;173----------------Power[-l -

2)

+

~_~~~:_l~_=_!_§g~~l~ll_ (-108 + 12 Sqrt[33))1/3

l~_±_!_§g~~l~ll_l=~Q~_±_~~_§g~~l~~ll~~: 6 21/3

O}

3)

That is a lengthy expression, which we do not really need, since it must be simplified. We could have suppressed displaying the result by ending the input with a semicolon ( ; ). In[9]:=

subst

=

equation2 I. solution2;

Because the result is suppressed now, we are not sure that the calculation has been done all right. The functions Short and Shallow help us here; they return a short form of the result. In[10]:=

subst = Short [equation2 I. solution2]

Out[10jl/Short=

{2 + «3» In[11]:=

+

(-1 + «2»)3

==

0, «2»}

Short[equation2 I. solution2, 2]

subst

Out[11 jI/Short=

«1», «2»}

Short produces a one-line output, where the number of suppressed elements is put into brackets « ... ». By entering a second parameter, the number of lines was chosen to be two. Short does not retain the structure of the result. This can be surveyed better by using Shallow. In[12]:=

subst

=

Shallow [equation2 /. solution2]

Out[12j1/Shallow=

{Plus[«5»)

==

0, Plus[«5»)

==

0, Plus[«5»)

==

O}

Short and Shallow only affect the printing of the output, not the actual evaluation of the result. Let us now simplify it.

58 ~

1. Basics Warning: The next calculation takes some time.

In[13]:=

Simplify [subst] I I Timing

Oulf1~=

{506.533 Second,

{True, True, True}}

It can be speeded up with a little help from the user. In[14]:=

ExpandAll [subst]

I I Timing

Out[14]= {111.217 Second,

{Plus[«3»] Plus[«3»] == OJ}

In[15]:=

Simplify[%[[2]]] II Timing

Oulf1~=

{1.45 Second,

0, Plus[«3»]

0,

{True, True, True}}

Remember: % [ [2]] selects the second element of the list (in our case: the actual result, without the timing). No large program such as Mathematica, can be perfect. In case of difficulties, the user can give it a little help, like the auxiliary calculations above. One cannot expect the program to be bug-free, either. Every important result should be checked carefully. Maybe, the following types of bugs and "bugs" can be distinguished: 1.

Some apparent "bugs" are not bugs at all. These are unexpected results, for which the program is blamed by a healthy human reflex. They often are caused by typing errors, misunderstandings, or they even are documented features. The function Solve can serve as an example for this, as we will discuss below. Before sending bug reports to Wolfram Research (e.g., by electronic mail to sup p 0 r t@wr i . c om), it is a good idea to carefully study the detailed documentation [Wo191] of the function in question and to reduce the effect to its essentials.

2.

The first type of real bugs are the ones which crash the program. They are very annoying, but, at least, they are identified easily.

3.

We also have to take errors of the algorithms into account. An example for this was the calculation of Sqrt [x" 2] in version 1.2 of Mathematica. It simply returned x, which is obviously wrong (or, at least, does not follow the normal convention), if x stands for a negative number. Such errors show up in simple examples. They often can be found by carefully checking the results, by testing their consistency, by substituting numerical values, or by comparing with the results of other programs.

4.

There might also exist errors which only show up in large calculations. These can be dangerous, because the user finds the program trustable when doing tests with small examples, and he or she looses his or her critical attitude. This makes it necessary to really check every crucial result by the methods mentioned above.

There are algorithms which Mathematica uses at a very basic level (long number arithmetic, polynomial arithmetic, gcd, etc.). So many routines are based on these algorithms that their bugs have been eliminated with a very high probability. Other algorithms (integration, solving differ-

59

1.4 Symbolic Calculations

ential equations, etc.) have a place at the leaves of the hierarchical tree of algorithms. They must be used with much more care. The user will gain a feeling for his or her tool after using it for some time. The internal need for consistency in symbolic calculations gives a much greater safety than any numerical simulation, where some numbers are returned in almost every case (with the exception of numerical overflow, etc.).

Let us now return to the first equation. In[16]:=

Solve [equationl, xl

Oulf1~=

{{x -> {x ->

2

-7 b - Sqrt[-60 a + 49 b ] -----------2-a------------}, 2

-7 b + Sqrt[-60 a + 49 b ] -----------2-a------------}}

After so many invitations to carefully check the results, the reader surely has noticed that the solution of equationl can cause problems: What happens if we set a = O? In[17]:=

% /. a -> 0 1

Power: :infy: Infinite expression - encountered.

o

1

Power: :infy: Infinite expression - encountered.

o

Infinity: :indet: Indeterminate expression ComplexInfinity + «1» encountered. 1

Power: :infy: Infinite expression - encountered.

o

General: :stop: Further output of Power::infy will be suppressed during this calculation. Infinity: :indet: Indeterminate expression ComplexInfinity + «1» encountered. Oulf1~=

{{x -> Indeterminate},

{x -> Indeterminate}}

60

1. Basics

In the above "classification" of bugs, this is not a bug (point 3) but a useful feature (point 1) of Solve. The function only returns the generic solutions and dismisses any special cases. These are taken into account by the function Reduce. In[1B]:=

Reduce [equation1, x]

Ouq1~= a

!= a

b

0 && x

!= !=

2

-7 b - S rt[-60 a + 49 b ] == --------g--2-a-----------II -7 b + Sqrt[-60 a + 49 b 2 ]

-----------2-a------------ I I

0 && x

-15 7-5 && a

0 && x

==

0

This result is presented as a logical expression. The double equal sign for "equal", ! = for "unequal", I I for "or" and && for "and".

o

==

stands

Systems of Equations

As the reader surely expects, Mathematica can also handle systems of equations. They must be written as a lists. In[19]:=

eqnList1 = {a xA2 + y == 1, b y - x == 15}

Ouq1~= {a x 2

+ y

==

1, -x + b y

15}

To solve for x and y, we write:

This gives us a list of two solutions, each of which contains a list of rules for x and y. We can check the correctness of the result as above. In[21]:=

eqnList1 /. solution / / Simplify

Out[21]= {{True, True},

{True, True}}

61

1.4 Symbolic Calculations

Each solution, when substituted into each equation, simplifies to True. We can as well eliminate x from the system, to get an equation for y. The function Eliminate does this for us. In[22}:=

Eliminate [eqnList1, x]

Oulf2~= -30 a b y + a b 2 y2

o

1 -

225 a - y

Unsolvable Equations

Equations containing transcendental functions are much harder than polynomial equations. In[23}:=

Solve [Sin[x]

==

1, x]

Solve::ifun: Warning: Inverse functions are being used by Solve, so some solutions may not be found. Out[23}= {{ x ->

~~}}

2

We get a message, telling us that "some" solutions may not be found-in his case, "some" stands for "infinitely many". Transcendental equations usually are beyond reach. In[24}:=

Solve [Tan [x]

==

-x, x]

Solve: : tdep: The equations appear to involve transcendental functions of the variables in an essentially non-algebraic way. Out[24}= Solve [Tan [xl

==

-x, xl

Except for the solution x = 0, one would not get much further with calculations "by hand", though. In such cases, we must resort to numerical approximations of the solutions. Mathematica is at our disposal with two tools for this task. For general equations (not necessarily polynomial) and systems of equations, we choose the function FindRoot. In[25}:=

FindRoot [Tan [x] + x -- 0, {x, 1}]

Out[25}= {x -> O.}

62

1. Basics

The function expects the equation(s) and a list containing the variable and a starting value. Another starting point may result in another solution. In[26]:=

FindRoot [Tan [xl + x == 0, {x, 2} 1

Ouq2~=

{x -> 2.02876}

Numerical approximations for the solutions of systems of equations can be found by: In[27]:=

eqnList2 = {Sin [xl + Tan [y] + 1 == 0, Cos [yl - Sin [xl -- O}

Ouq27]= {1 + Sin[xl

+ Tan[yl

==

0, Cos[yl - Sin[xl

In[2B]:=

FindRoot [eqnList2, {x,

• 5},

Ouq2~=

{x -> -11.9915, Y -> -0.99597}

{y,

• 5}

==

O}

1

Finding the roots of polynomial equations is much easier. The function NSol ve returns all solutions in one step. In[29]:=

NSolve[x A6 + XAS - 3 xA2 + x - 5 == 0, xl

Out[29]= {{x -> -1. 82712 L {x -> -0.594186 - 1. 223 IL {x -> -0.594186 + 1.223 I}, {x -> 0.353936 - 1.00335 I}, {x -> 0.353936 + 1. 00335 IL

{x -> 1. 30762}}

We get the same result by trying to solve the equation with Sol ve and applying the function N to the transformed expression: In[30]:=

Solve[x A6 + XAS - 3 xA2 + x - 5 == 0, xl

Ouq3~= {ToRules[Roots[x - 3 x 2 In[31]:=

+ x5 + x6

==

5, xll}

N [%l

Out[31]= {{x -> -1. 82712 L {x -> -0.594186 - 1. 223 IL {x -> -0.594186 + 1.223 I}, {x -> 0.353936 - 1.00335 I}, {x -> 0.353936 + 1.00335 I}, {x -> 1.30762}}

The functions for such numerical approximations allow a detailed control over many aspects of the algorithms involved (e.g., the precision). This will be the subject of Section 3.3.3.

63

1.4 Symbolic Calculations

o

Questions and Answers How do I substitute the solution of an equation into an expression or into the equation itself?

'a'

The solutions are returned as a list of rules for the variables. These can be applied with / ..

(l:JJ

In[1):=

Solve [x"3

Out[1}=

{ {x ->

In[2}:=

x"2 /

Out[2}=

{l,

1},

.

1, xl {x -> (_1)213},

{x -> (_1)413}}

%

(_1)413,

(_1)213}

'a'

This gives me a list. I only want to substitute a single solution.

(l:JJ

Choose the desired solutions with [ [ ... ] ] .

In[3):= Out[3}=

x" 2 /. %% [ [2 1 1 ( -1 ) 4 13

I solve an equation which has a single solution. Why is it put into double braces?

'a'

In[4}:=

Solve [x == a, xl

Out[4}=

{{x -> a}}

ibJ

Mathematica consistently returns a list (for the several possible solutions) of lists (for the several possible variables). It is therefore necessary to pull out the single solution with [[ 1] ] . For instance, to assign the solution to the variable, you can write:

In[5}:=

x = x

Out[5}=

a

/. % [ [1 1 1

Doing this is possible, but not a very good idea. It is preferable to avoid such "fixed" definitions, because they might confuse you later on in the session, when you may have forgotten that such a definition has been made before (see the remark on page 255).

64

o

1. Basics

Summary Relational Operator Meaning --

equal

!=

unequal


=

greater than or equal

Table 1-22: Relational operators Logical Operator

Meaning

II

or

&&

and

Table 1-23: Logical operators . Expression

Meaning

expr;

do not display the result

Short [expr]

display a one-line short fonn of the result

Short [expr, n]

n-line short fonn

Shallow [expr]

display only the "top level" of expr

Table 1-24: Displaying short forms of results Expression

Meaning

Solve [eqns, vars]

solve an equation or a system of equations eqns for the variable(s) vars; several equations or variables must be given as lists

Solve [eqns, vars, elims]

solve for the variable(s) vars, eliminate the variable(s) elims

Reduce [eqns, vars]

return a simplified system of logical expressions, which represents all solutions

Eliminate [eqns, vars]

eliminate the variable(s) vars

Table 1-25: Symbolic solutions of equations

65

1.4 Symbolic Calculations

Expression

Meaning

Roots [eqn, var)

generate a disjunction of equations which corresponds to the roots of a polynomial equation

AlgebraicRules [eqns,

generate a list of rules, in which variables appearing early in the list {xI' x2' ... } are replaced by variables appearing late

{xI'

x2'

.. , } )

generate a list of rules from a logical combination of equations (e.g., the result of Roots or Reduce)

ToRules [eqns)

Table 1-25: Symbolic solutions of equations Expression

Meaning

FindRoot [eqn,

{x,

xo} )

search a numerical approximation by starting at the values Xo and x I; this form must be used if the necessary symbolic derivatives cannot be found

FindRoot [eqn, {x,

{xo,

xI} } )

FindRoot [eqn, {x,

Xstart'

xminl

search a numerical approximation to the solutions of the equation eqn by starting with the variable X at the value Xo

xmax} )

search a numerical approximation by starting at x start; the search ends, if the interval [xmin' xmax] is left

... }, search a numerical approximation to the solutions of ... ) {eqnl' eqn2' ... } with the given variables and start

FindRoot [ {eqnj' eqn2' {x,

xo},

{Y,

Yo},

points NSolve [eqn, var) N[Solve[eqn,

var))

give all solutions of the polynomial equation eqn in the variable var acts like NSol ve [eqn, var)

Table 1-26: Numerical solutions of equations

o

Exercises

1. Try to solve

with the computer and by hand. 2. Equations of degree five or more generally cannot be solved with radicals. What does Mathematica do in such a case?

66

1. Basics

3. Solve the system { (x + y)

(1 + xy)

= a,

(x- y) (l-xy)

= b}

for x andy. Depending on what computer you are using, this might take some time. The following is a good exercise: Try to solve the first equation for x, to substitute the result into the second equation, and to solve it for y. What are the final results for x and y? 4. Find solutions of tanlxl + x



= O.

1.4.3 Calculus

So far so good. A critical reader will not be overwhelmed by what we have seen so far-equations can be solved numerically; no computer is needed for his or her polynomials; long number arithmetic is useless since all physical measurements are inexact, .... But maybe this reader has already spent valuable time searching for integrals in a 1000-page handbook. This motivates us to study Mathematica's abilities in calculus.

o

Derivatives

Before dealing with integrals, one has to be able to calculate derivatives. The function D does that. In[1]:=

D [x'" (x"'x),

Out[1J=

x-

1 + x

xl

+ XX + xxx

Log[x]

(x

x

x +x Log[x])

We can get higher derivatives by passing a list containing the variable and the order of the derivative:

67

1.4 Symbolic Calculations {x,

In[2]:=

D [XAX,

Oulf~=

(-1 + x) x- 2 + x + x- 1 + x +

3}] XX +

x- 1 + x Log[x] +

x x XX Log[x] + ~ __ ~_~ __ ~~gl~l + x

Log[x]

(xx + XX Log[x]) + Log[x] (x -1 + x + x x + x x Log[x] + Log[x] (xx + XX Log[x])) In[3]:=

Simplify[%]

Out[3]=

x -2 + x (-1 + 3 x + x 2 + 3 x Log[x] + 3 x 2 Log[x] + 3 x 2 L09[x]2 + x 2 L09[x]3)

Derivatives with respect to several variables are possible, as well. In[4]:=

D[1/Sqrt[x A2 + yA2 + z A2], x, y, z]

Out[4]=

----:~~-~-y-~---(x2 + y2 + z2)7/2

Mathematica even knows the relations concerning derivatives of Bessel functions. In[5]:= Out[5]=

D[BesselJ[n, x], x] BesselJ[-l + n, x] - BesselJ[l + n, x]

------------------2-------------------

Let us now look at the following calculation: In[6]:=

D [xAn, x]

Out[6]=

n x

-1 + n

What happens, if n depends on x? This case requires the total derivative Dt. In[7]:=

Dt [xAn, x]

Out[7j=

n x

-1 + n + xn Dt[n, x] Log[x]

The same function, without a second parameter, returns the total differential. In[B]:=

Dt [xAn]

Oulf~= n x- 1

+

n Dt[x] + xn Dt[n] Log[x]

68

1. Basics

o

Defining Functions

So far, we have only dealt with symbolic expressions. In calculus, we also want to be able to define functions. We can define, for instance, a function square, which returns for any argument x the value 2: In[9}:=

square [x_]

:

=

XA 2

The blank C) stands for a pattern, representing any argument. The sequence x_ can therefore be read as "anything, for which we will use the name x" (see also: Section 2.2.1). The function defined in this way acts just like any built-in object (e.g., Sin). For instance, it can be evaluated for the value of 10. In[10}:=

square [10]

Out[10j= 100

1&

Note that the definition of the function was written with a : =, and not with a single =.

Let us look at the following two definitions, to have a first glance at the difference between the two forms of definitions: In[11}:=

gl[x_]

:= D[x y,

y]

In[12}:=

g2 [x_] = D [x y, y]

Out[12}=

x

As long as we evaluate the functions for constants, no difference shows up. In[13}:=

gl [a]

Out[13}= a In[14}:=

g2 [a]

Out[14}=

a

But, if we insert the symbol y, the following happens: In[15}:=

gl [Sin [y] ]

Oulf1~=

Y Cos[y] + Sin[y]

69

1.4 Symbolic Calculations In[16}:=

g2 [Sin [yl 1

Out[16}= Sin [yl

Why? By writing an equal sign, the right hand side of the definition is evaluated immediately. This can be seen from the result Out[12}= x. On the other hand, if a : = is used, the right hand side will only be evaluated when the function is called. Therefore, no result shows up after In[ll}:= gl [x_l : = D [x y, yl-nothing has been calculated yet. For these reasons, definitions with with: =.

= are called immediate, in contrast to delayed definitions

If mathematical functions are translated into Mathematica, the evaluation is (in most cases) meant to be delayed. Therefore, it is a good rule of the thumb, to use : = in function definitions.

We will discuss the differences in more detail in Chapter 2.3. This will allow us to make the right choice with the help of a full understanding of what happens.

Functions of several variables can be constructed in a similar fashion: In{17}:=

r[x_, y_, z_l

:= 1/Sqrt[x"2 + y"2 + z"2l

We might now search the second derivative with respect to each of the variables: In[18]:= Out[18}=

If a derivative cannot be transformed any further, it is returned in a symbolic form. In[19}:=

D [f [xl,

Out[19}= f' In[20}:=

xl

[xl

D [Log [f [xl l, {x, 2} 1 f' [xl 2

OUlf20= -(f[~12-)

+

f' , [xl -I[x]-

70

1. Basics

This shows us that derivatives can also be written in the natural way (f etc.). In[21}:=

I

[x],

Sin I [x]

Out[21}= Cos [xl

Partial derivatives are displayed by putting the order of the derivatives with respect to the variables into upper parentheses. The sequence of the numbers corresponds to the sequence of the variables. In[22]:=

D[g[x, y, Z],

Oulf22}=

g(2,1,O) [x, y, zl

o

{x, 2}, y]

Integrals

Derivatives are easy to calculate, because they result from applying a couple of simple rules-sum, product, chain rules, plus the derivatives of the elementary functions. Calculus courses usually do not teach similar algorithms for integrals. That is why integration by hand requires mathematical artistry (and/or good knowledge of integral tables). Risch [Ris68] has developed an algorithm, which can solve a large class of integrals. Together with extensions, this algorithm is implemented in Mathematica.

The integration function in Mathematica is called Integrate. (a + xA2 + x A3)/(x - b)AS

In[23]:=

sillyFunc[x_]

In[24):=

Integrate[sillyFunc[x], x]

Out[24}=

-a - b 2 - b 3

:=

2 b + 3 b2

-4-(b-=-~)4- + 3-(b-=-~)3

To make the result easy, the (additive) constant of integration is set to zero. Is this result correct? In[25}:=

D [%, x]

/ / Simplify

a + x2 + x3 Oulf2~= -(=b-:-~)5-

A more complicated example is:

71

1.4 Symbolic Calculations In{26}:=

Integrate[{Log[x] + Sin[x]) {x"-2 + Exp[x]), x]

Out{26}= i=1_~_~

x

__ ~L_~Qgl~1 x

+

(-2 - EX x Cos [x] +

2 x CosIntegral[x] - 2 x ExpIntegralEi[x] 2 Sin[x] + EX x Sin[x]) / (2 x)

Multiple integration is possible in one step. In{27}:=

Integrate [sillyFunc [x], x, y]

-

Oulf2~= ~_i~_~_~_~~_Y 3 (b - x)

i1_~-~-~L2Y + 2 (b - x)

Y_i~_~~_~_~_~:_~_YL 8 (b - x)4

If we want to calculate a definite integral, the variable and the boundaries must be given as a list. In{2B):=

Integrate[sillyFunc[x],

Out{2B)=

=1-:;:-5 - 5 -

1

1

2 b + 3 b2

---;-b3 ---

{x, 0, 1}]

1 + 3 b 1 + 3 b 2 b + 3 b2 ----------- + 2-+ 2 (-1 + b)2

-;-b

-

~~-~-~:-~-Y 4 (-1 + b)4

;-(=i-:-b)3 -

2 + b3 + Y + b----------4 b4

Mathematica's knowledge exceeds the author's: In{29}:=

Integrate [Log[x] Exp[-x"2],

{x, 1, Infinity}]

Oulf2~= =i~~1§~Q~~~_§9~tl~~ll +

HYPergeometricPFQ[{~, ~}, §g~U~~L~QgHl

4

Versions 2.2 and later of Mathematica even find non-integrable singularities in the range of integration. In{30}:=

Integrate [1 Ix" 2,

{x, -1, 1}]

Integrate: :idiv: Integral does not converge. OUlf30= Indeterminate

Earlier versions returned the difference of the values of the indefinite integral at the boundaries, that is:

72

1. Basics

In[31]:=

(Integrate [1/xA2, xl /. x -> 1) (Integrate[1/x A2, xl /. x -> -1)

Out[31]= -2

This also was not a bug but a documented "feature" (see [Wo19l], page 812).

Of course, many integrals cannot be written in terms of elementary functions-no program can do the impossible. In[32]:=

Integrate [Sin [xl/Log [xl, xl

Oulf3~= Integrate

Sin [xl [Log[xl'

xl

Analogous to the equations, there is a numerical version for definite integrals, which helps in such cases. It can be activated either by directly calling Nln tegrate or by applying the function N to the unevaluated integral. In[33]:=

Integrate [Sin [xl/Log [xl,

Oulf3~=

Sin [xl Integrate [Log[xl'

In{34]:=

N [%l

{x, 2, 3} 1

{x, 2, 3}l

Out{34]= 0.674381 In{35]:=

NIntegrate [Sin [xl/Log [xl,

{x, 2, 3} 1

Out{35]= 0.674381

As with solving equations, there are cases, where getting some help from the user is appreciated by Mathematica. For instance, the following integral does not evaluate, because the denominator cannot be factored over the integers: In{36]:=

Integrate[1/(x A5 + 2 x A3 + 3 x + 5), xl

Oulf3~=

1 Integrate[-------------]----S' xl 5 + 3 x + 2 x + x

A factorization is possible over the real numbers. In{37]:=

den = Factor[N[x A5 + 2 x A3 + 3 x + 5]]

Out{37]=

(0. 922014 + x)

(2. 16797 - 1. 88641 x + x (2.50138 + 0.964392 x + x 2 )

2

)

73

1.4 Symbolic Calculations

With the help of this auxiliary result, Mathematica returns the integral, using numerical values for the roots:

o

In[38}:=

Integrate [lIden, x]

Oulf3~=

0.0189781 ArcTan[0.442229 (-1.88641 + 2 x)] + 0.0956498 ArcTan[0.331945 (0.964392 + 2 x)] + 0.0853672 Log[0.922014 + x] 0.0448948 Log[-2.16797 + 1.88641 x - x 2 ] + 0.00221122 Log[2.50138 + 0.964392 x + x 2 ]

Limits, Residues

The function Limi t calculates limits (what a surprise). In[39}:=

Limit [Sin[x] I x, x -> 0]

Out[39}= 1

If the values of the limits by approaching from below and from above are different, it is necessary to calculate them separately. This is done by setting the option Direction -> +1 (below) or Direction -> -1 (above). In[40):=

Limit[Tan[x], x -> Pi/2, Direction -> +1]

Out[40}= Inf ini ty In[41}:=

Limit [Tan[x], x -> pi/2, Direction -> -1]

Out[41}= -Infinity

The residue (at a given point) is found by:

o

In[42}:=

Residue[1/Sin[x]A3,

Out[42}=

~

{x, Ol]

Differential Equations

We usually model nature by differential equations. These are therefore a central field of concern, and sometimes puzzle, for any engineer or scientist. Mathematica helps us to solve ordinary differential equations by supplying two great tools.

74

1. Basics

Like algebraic equations, differential equations are written with the == sign. It does not matter if the derivatives are typed in the form D [ f [ t] , t] or f [t]. But obviously, the second version is easier to read and write. I

Let us start with the definition of a differential equation. In[43]:=

ode

Out[43]= x[t]

= x'

==

[t] + x[t]

I

+ x"[t]

==

t

t

Sin[t)A2 Cos[t]

Cos[t] Sin[t]2

As a first step, we look for a symbolic solution, by using the function DSol ve. It expects the equation(s), the unknown function(s), and the independent variable(s) as parameters. In[44]:=

= Simplify[DSolve[ode,

genSol

->

Out[44]= {{x [t]

t

Cos [t]

---1:6--- +

Sin[t]

--32--

+

C [2]

2

t Sin[t] ---16----

x[t], t]]

Cos [t] C[l]

+

t

Cos [3 t] ----32----

Sin[t]

-

3 Sin[3 t] ---12S----}}

As we can see, the constants of integration are written as C [ 1] , C [2 ] , etc. This is a convention (which can be changed). If initial conditions shall be taken into account, they must be formulated as equations and passed as a list, together with the differential equation(s). In[45]:=

specSol = Simplify [ DSolve[{ode, x[O] ->

Out[45]= {{x[t]

==

1,

X'

+ 8 t

(128 Cos[t]

[0]

+ 8 t 2 Sin[t]

3 Sin[t]

==

Cos[t] -

O}' x[t], t]] + 4 t

Cos[3 t]

3 Sin[3 t])

-

/128}}

Why do the results have two braces? One of them is obvious: We can also solve systems of equations, containing several unknown functions. But it can also happen that a solution has more than one branch: In[46]:=

DSolve[x[t]

Out[46]= {{x[t]

{x[t]

X'

[t]

==

-> -Sqrt[2 t -> Sqrt[2 t

1, x[t], t]

+ C[l]]}, + C[l]]}}

The outer list is reserved for this case, just as in Solve.

Of course, systems of differential equations must be written as lists. In[47]:=

sys

=

{X

[t] +

X

I

[t]

==

y [t],

X

[t] + y

I

[t]

==

I};

75

1.4 Symbolic Calculations In[48):=

sysSol

Out[48}= {{x[t]

=

Simplify[DSolve[sys,

{x[t], y[t]}, t]]

(2 + E(-(1/2) - II2 Sqrt[3]) t e[l] + I Sqrt[3] E(-(1/2) - 1/2 Sqrt[3]) t e[l] + EI/2 (I + Sqrt[3]) t e[2] _ ->

I Sqrt[3] EI/2 (I + Sqrt[3]) t e[2]) / 2, y[t] -> 1 + E(-(1/2) - 1/2 Sqrt[3]) t e[l] + EI/2 (I + Sqrt[3]) t e[2]}}

Let us now try to verify the result. In[49}:=

sys /. sysSol

Ouq4~= {{(2 + E(-(1/2)

- 1/2 Sqrt[3]) t e[l] + I Sqrt [ 3] E ( - ( 1/2 ) - II 2 Sqrt [3]) t e [ 1] + EI/2 (I + Sqrt[3]) t e[2] _

I Sqrt[3] EI/2 (I + Sqrt[3]) t e[2]) / 2 + x' [t] 1 + E(-(1/2) - 1/2 Sqrt[3]) t e[l] + EI/2 (I + Sqrt[3]) t e[2], (2 + E(-(1/2) - 1/2 Sqrt[3]) t e[l] +

==

I Sqrt[3] E(-(1/2) - 1/2 Sqrt[3]) t C[l] + EI/2 (I + Sqrt [3]) t e [2] _

==

I Sqrt[3] EI/2 (I + Sqrt[3]) t e[2])

/ 2 + y' [t]

1}}

At first sight, there is something wrong here: Only the functions, but not their derivatives, have been substituted. This is because we are communicating with a computer program, which does pattern matching, and not with a mathematician. Since the internal representation of the derivative x' [t] does not match the pattern x [t] , Mathematica will not perform the substitution as expected. To get a suitable form of the result, we must glance at Section 1.6.2. There, we will learn something about pure functions. Let us not try to understand them here, but only look at what we need. DSo1ve returns the result in the form of a pure function, if we insert {x, y} instead of {x [t] , Y [ t] } as (function) parameters. In[50):=

sysSolPure

=

Simplify[DSolve[sys,

{x, y}, t]]

Out[50}= {{x -> Function[t,

(2 + E ( - (1/2) - 1/2 Sqrt [ 3]) t C [ 1] +

I Sqrt[3] E(-(1/2) - 1/2 Sqrt[3]) t e[l] + EI/2 (I + Sqrt[3]) t e[2] _ I Sqrt[3] EI/2 (I + Sqrt[3]) t e[2]) / 2], Y -> Function(t, 1 +

76

1. Basics E(-(1/2) - 1/2 Sqrt[3]) t C[l] + EI/2 (I + Sqrt[3]) t C[2]]}}

This solution can be substituted: In[51}:=

sys /. sysSolPure / / Simplify

Out[51}= {{ True,

True}}

The DSo 1 ve function (of Version 2.2) even solves some simple nonlinear differential equations. But many others might not be evaluated: [tl + (l - t"2) x' [tl - t x[tl

In[52}:=

DSolve[t x" x [t], tl

Out[52}=

DSolve[-(t x[t]) + (1 - t 2 ) x' [t] + t x" x[t],

t]

0,

[t]

0,

The package Calculus' DSol ve' extends the abilities of DSol ve to a larger class of differential equations. In[53}:=

Needs ["Calculus' DSolve' "l

In[54]:=

DSolve[t x" x[tl, tl

[tl + {l - t"2} x' [tl - t x[tl

0,

i-]

2 2 Et /4 BesselI[O, C[l] Out[54}= {{x[t] -> --------------,---------- + Sqrt[Pl] t 2 ;4 _t 2 BesselK[O, -4-] C[2] E --------------------------}} Sqrt[Pi] One might ask why this package is not loaded automatically. The main reason is the response time. Checking for all the many special cases takes time, while the built-in function can decide rather quickly that it cannot solve a certain equation. Therefore, the user can decide if he or she wants to accept the longer response time for every calculation or not.

Of course, Calcul us' DSol ve' also cannot do the impossible. For instance, the solution of the mathematical pendulum cannot be expressed by elementary functions.

77

1.4 Symbolic Calculations In[55]:=

DSolve[x"

[tj + Sin[x[tjj == 0, x[tj, tj

Out[55]=

Because we have loaded Calculus' DSol ve' , the solution is given in terms of elliptic integrals. Without the package, the input would be returned unchanged.

In analogy to Solve and NSol ve, the numerical version of DSol ve is called NDSol ve. To perform the integration, it needs to know the initial conditions and the desired range. In[56]:=

Oulf5~=

mathPendRule = NDSolve [ {x" [t] + Sin[x[t]] == 0, x[O] x, {t, 0, lOll

==

0, x' [0]

==

l},

{{x -> InterpolatingFunction[{O., 10.}, ]}}

The result is given as an interpolating function. It represents the approximate solution (within the chosen precision, see Section 3.3.3) by pieces of polynomial curves. This has the great advantage that the solution can be evaluated at any point, independent of which sample points were produced by the algorithm, which internally uses discrete steps. For instance, to construct a graph, we do not have to worry about getting the necessary data points. At the time t = 1 . 5, the solution has the value: In[57]:=

x [1. 5]

/. mathPendRule [ [1]]

Out[57]= 1. 03228

Of course, it is tedious to discuss the results in this way. Therefore, it is time to study one of the most attractive aspects of Mathematica in the next chapter: graphICS.

Partial differential equations are much more difficult to handle, mathematically and conceptually. For instance: How should the boundary and the initial conditions be passed to the program? The package Calculus' PDSol vel' extends DSol ve to some first-order partial differential equations. To go beyond that, one has to wait for forthcoming versions of Mathematica or to use special purpose programs, e.g. finite element codes.

1. Basics

78

o

Summary Expression

Meaning

lhs = rhs

an immediate definition; the right hand side is calculated immediately

.-

a delayed definition; the right hand side is calculated when the definition is used

lhs

rhs

.-

/[x_l

rhs the definition of a function/with the variable x

Table 1-27: Immediate and delayed definitions, functions Expression

Short Form

Meaning

D[/, xl

f'

the derivative of/with respect to x

D[/,

{x,

2}

1

[xl

/' '[xl

the derivative of/with respect to xl, x2, ...

D[/, xl' x2, ... J D[/,

{x,

the second derivative of/with respect to x

the nth derivative

n}J

Dt[/J

the total differential of/

Dt [/, xJ

the total derivative of/with respect to x

Table 1-28: Derivatives Expression

Meaning

Integrate [I, xJ

the indefinite integral

Integrate [j, x, Y, Integrate [I,

{x,

f/ (x) dx the multiple indefinite integral fdx fdy .. .f (x, y, ... )

... J

Xminl

x max } J

Integrate [I, {x, Xmin l xmax } , {y, Ymin, Ymax} , ... J NIntegrate [j,

{x,

xminl

the definite integral f::~J (x) dx

r

maxd . x fmaxd . y.../( x,y, ... )

x m1n

Ymln

x max } J the numerical evaluation of a definite integral

NIntegrate [j, {x, xmin' x max } , {y, Ymin' Ymax } , ... 1

the numerical evaluation of a multiple definite integral

Table 1-29: Integration

79

1.4 Symbolic Calculations

Expression

Meaning

Limi t [expr , x -> xo]

the limit when x approaches Xo

Limi t [expr, x -> xo, Direction -> 1]

x approaches Xo from below

Limi t [expr, x -> xo' Direction -> -1]

x approaches Xo from above

Limi t [expr , x -> xo, Analytic -> True]

unknown functions are assumed to be analytic (Version 2.1 and later)

Table 1-30: Limits Expression

Meaning

Residue [expr,

{x,

xo} ]

the residue of expr at x = Xo

Table 1-31: Residues Expression

Meaning

DSol ve [eqns, x

[t] ,

DSol ve [eqns, {x [t] DSol ve [eqns,

{x,

solve the differential equation(s) eqns for the function x [t] , with the independent variable t; initial conditions are put into the list eqns

t]

y [t]

,

,

... }, t]

y, ... } , t]

NDSol ve [eqns, x, {t,

tmin'

solve differential equations(s), return the solution as a pure function (see Section 1.6.2) solve the differential equation(s) and initial conditions in x (combined in the list eqns) numerically for values of the independent variable t from tmin to t max

t max } ]

NDSolve[eqns, {x, {t, tmin' t max } ]

solve a system of differential equations

y, ... },

the numerical solution of a system of differential equations

Table 1-32: Differential equations Package

Contents

Calculus'DSolve'

extensions of DSol ve to more complicated differential equations

Calculus'PDSolve1'

partial differential equations of order 1

Calculus'EllipticIntegrate'

elliptic (and related) integrals

Table 1-33: Standard packages

80

o

1. Basics

Exercises

1. Integrate x arctan(x) with respect to x. Verify the result. 2. Calculate the integral 21t

J o

cos2x d 1 - k 2 sin2 x x.

Substitute the values 0.5, 1 and 2 for k. Compare with a numerical integration.

3. Check some complicated results of your integration table. 4. What result does Mathematica return, if you try to calculate lim sin (x) , X--7

OO

or lim sin(!)?

X--70

X

5. Solve the differential equation

and verify the result. 6. Solve the system of differential equations ) ( x'(t) +y'(t) =y(t) -x(t) x' (t) -2y' (t) = x (t) + y (t) + sin2t

and verify the result. 7. Calculate a numerical solution for the damped pendulum x" (t) + .1 x' (t) + sin (x (t))

= 0,

= 1 and x' (0) = o. What are the values of the solution at t = 2, 4, 6, 8, 10? with initial conditions x (0)

81

1.5 Plots: Different Pendulums

• 1.5 Plots: Different Pendulums In this chapter, we study the graphical representation of functions and data with the help of different types of two- and three-dimensional plots. The first section describes the most important techniques of creating and customizing two-dimensional plots, by working with simple examples. Afterwards, we will use different types of mUltiple pendulums as examples for more sophisticated plots in two and three dimensions-the pendulums will also serve as examples in some of the forthcoming chapters. The last section covers plotting discrete data, such as imported lists of numbers.



1.5.1 Two-Dimensional Plots

The Mathematica command for two-dimensional plots is called Plot. We pass the expression or function to be plotted and then-as a list-the variable, with its start and end values. In[1}:=

Plot [Sin[x] Sin[3x] Sin[5x],

Out[1}=

-Graphics-

{x, 0, 2 pi}]

Several functions can be plotted simultaneously, by grouping them as a list.

82

1. Basics

In[2]:=

Plot[{Sin[x], Sin[3x], Sin[Sx]},

Oulf~=

-Graphics-

{x, 0, 2 Pi}]

Of course, we can plot user-defined functions as well. In[3]:=

j3jS[x_]:= BesselJ[3, x] BesselJ[S, x]

In[4]:=

j3jSGraph = Plot [j3jS [x],

{x,

0, 4Pi}]

0.075 0.05 0.025 2

-0.025 -0.05 -0.075

Out[4]=

-Graphics-

Many options to Plot are available to allow us to "fine tune" the details of our plots. We can study the default values of these options by typing: In[5]:=

Options [Plot]

Out[5]=

{AspectRatio -> GoldenRatlo' -----~---T- Axes -> Automatic , AxesLabel -> None, AxesOrigin -> Automatic, AxesStyle -> Automatic, Background -> Automatic, ColorOutput -> Automatic, Compiled -> True, DefaultColor -> Automatic, Epilog -> {}, Frame -> False,

1.5 Plots: Different Pendulums

83

FrarneLabel -> None, FrameStyle -> Automatic, FrarneTicks -> Automatic, GridLines -> None, MaxBend -> 10., PlotDivision -> 20., PlotLabel -> None, PlotPoints -> 25, PlotRange -> Automatic, PlotRegion -> Automatic, PlotStyle -> Automatic, Prolog -> {}, RotateLabel -> True, Ticks -> Automatic, DefaultFont :> $DefaultFont, DisplayFunction :> $DisplayFunction}

This gives a survey over all the possibilities. When generating graphics, Mathematica replaces all options set to Automatic with a value of its choice. We can look at them by: In[6]:=

FullOpt ions [j 3 j 5Graph]

Oulf~=

{AspectRatio -> 0.618034, Axes -> {True, True}, AxesLabel -> {None, None}, AxesOrigin -> {O., O.}, AxesStyle -> {{GrayLevel[O.], Thickness[0.002]}, {GrayLevel[O.], Thickness[0.002]}}, Background -> Automatic, ColorOutput -> Automatic, DefaultColor -> Automatic, Epilog -> {}, Frame -> {False, False, False, False}, FrameLabel -> {None, None, None, None}, FrameStyle -> {None, None, None, None}, FrameTicks -> {None, None}, GridLines -> {None, None}, PlotLabel -> None, PlotRange -> {{-0.314159, 12.8805}, {-0.0775165, 0.0995155}}, PlotRegion -> Automatic, Prolog -> {}, RotateLabel -> True, Ticks -> {{{12.8, , {0.00107416}, {GrayLevel[O.], Thickness[O.OOl]}}, {12.4, , {0.00107416}, {GrayLevel[O.], Thickness[O.OOl]}},

(Many definitions of tick marks are suppressed.) DefaultFont -> {Courier, 10.}, DisplayFunction -> (Display[$Display, #1] & )}

This output gives us an idea of the syntax of the options. We can use the help features (see Chapter 1.2), especially the function browser (see Figure 1-2 on page 14), or we can check in [WoI91], to get more detailed documentations. In this chapter, the most common options are introduced by example.

It is not necessary to recalculate everything from scratch to change some options. The function Show displays any graphics of the current session with changed options, if desired. Let us give our plot a title.

84

1. Basics

In[7]:=

Show[j3j5Graph, PlotLabel -> "J3 J5"] J3 J5

0.075 0.05 0.025 2

-0.025 -0.05 -0.075 ou~n=

-Graphics-

Instead, we might add a grid and label the axes: In[B]:=

Show [j 3 j 5Graph, GridLines -> Automatic, AxesLabel -> {"x", "J3 J5"} J3 J5

O.O~--~c----~---4~--~----~--~-

0.02

-0.02~--~r----r----~---h~--~--+r-O.O.~----f----~----~~~----~~

- 0 . 075+---- +-----+-------+----'"'--f--.-----+----+__ Ou~~=

-Graphics-

Mathematica starts by calculating as many data points as given in the option PlotPoints, by default, 25. Afterwards, the plot is refined by an adaptive algorithm, until the angle between two successive segments is smaller than a value controlled by the option MaxBend, or until the maximum number of subdivisions given in PlotDivision is reached. It might happen that the initial plot points are chosen unhappily, resulting in an unusable, "aliased" figure.

85

1.5 Plots: Different Pendulums In[9]:=

Plot[Cos[2Pi x],

{x, 0, 24}l

1.4 1.2

5

10

15

20

0.8 0.6

Ouq~=

-Graphics-

After changing the number of PlotPoints, this effect disappears. In[10}:=

Plot [Cos [2Pi xl,

{x, 0, 24}, PlotPoints - > 40 1

1

0.5

-0.5

-1

Ouq10= -Graphics-

In the following example, the plot range is limited automatically:

86

1. Basics

In[11]:=

Plot[Sin[x] Exp [X], {X, 0, S pi} ] 600000 500000 400000 300000 200000 100000 2.5

5

7.5

1

15

-100000

Out[11}= -Graphics-

To see the entire range of values, we reset the value of PlotRange: In[12}:=

Show[%, PlotRange -> All]

2. 10 l.5 10 1.

10

6 6 6

500000

2.5

5

7.5

10

Out[12}= -Graphics-

How are graphics printed? • Within a notebook interface, this is very easy: Select its corresponding command-Print Selection ... for a chosen selection, or Print ... for the whole notebook. Additionally, the Graph menu contains several possibilities to change the appearance of the graphics, for instance, to draw all lines very thin. • Without afront end, we have to use the kernel's PSPrint command. It sends the graphics object given as its argument to the printer. In[13}:=

PSPrint [j 3 j SGraph]

Oulf1~=

-Graphics-

1.5 Plots: Different Pendulums

87

Of course, graphics can be exported as well. • Again, this is easiest in a notebook/rant end: Depending on the operating system, we copy the graphics to the clipboard and save it as a file in the selected format (Convert Clipboard ... ), or we move it by clipboard to the desired application-usually, after changing its format with a Convert to ... command. It is highly recommended to use a format based on the resolution independent PostScript language. By using a suitable application, we can even edit the graphics file to match any exotic demands.

• Without a front end, we might use the following command to save the graphics in a PostScript file: In[14]:=

Display ["mathpsfile", j 3j SGraph]

Oulf1~=

-Graphics-

In this format, some initializations of the PostScript definitions are missing. We have to use the program pS fix (or p r i n t ps or r a s t e r ps), which is distributed with Mathematica, to generate a regular PostScript or EPS file. For instance, the UNIX command

psfix -epsf

< mathpsfile > psfile.eps

creates a regular EPS file "ps fi 1 e. eps" to be used by another application. Both steps can be combined within Mathematica, if desired:

o

In[1S]:=

Display["!psfix -epsf > psfile.eps", j3jSGraph]

Oulf1~=

-Graphics-

Summary

• The option PlotPoints should be changed, if a plot looks funny. Expression Plot [j, Plot[

{x,

Meaning

xmax } ]

xminl

{iI, h, ... } ,

{x, xmin' xmax} ]

Show [graphics, options]

plot the function/with the variable x, from Xmin to Xmax plot several functionsiI,f2, ... show the graphics, possibly with different options

Table 1-34: Two-dimensional plots

88

1. Basics

Expression

Meaning

Options [symbol]

a list of the default values of the options for symbol

FullOptions [expr]

the explicit list of all options set of expr

Table 1-35: Information about the options of functions and objects Option

Default Value Other Values

AxesLabel

None

label {xlabel, ylabel}

the labels for the axes

GridLines

None

Automatic {xgrid, ygrid}

the grid

MaxBend

10.

number

the maximum bend between successive curve segments

PlotDivision 20.

number

the maximum number of subdivisions

PlotPoints

25

number

the number of primary sample points

PlotRange

Automatic

All {min, max} { {xmin' x max } ,

the range(s)

PlotLabel

label (e.g., "title")

None

Meaning

... } the title

Table 1-36: Some important options of Plot Expression

Meaning

PSPrint [graphics]

print the given graphics (without front end)

Display ["file" , graphics]

write graphics into a (reduced) PostScript file; the file can be converted into a regular PostScript file (or other file types) with the program p S fix (or p r i n t p S or r a s t e r p s)

Table 1-37: Printing and exporting graphics (without a front end) Expression

Meaning

BesselI[n, z]

the modified Bessel functions of the first kind: In(z)

BesselJ[n, z]

the Bessel functions of the first kind: In(z)

Table 1-38: Bessel functions

89

1.5 Plots: Different Pendulums

Expression

Meaning

BesselK[n, zJ

the modified Bessel functions of the second kind: KnCz)

BesselY[n, zJ

the Bessel functions of the second kind: Yn(z)

Table 1-38: Bessel functions

o

Exercises

1. Plot the Bessel function II (x) , for x from 0 to 2n. Compare it to the sine function. 2. Compare the Bessel functions Ii (x) with index i from 1 to 5. 3. Label the plots from Exercises 1 and 2. Also label their axes. 4. Generate a clean plot of the function

f

(x) =

sin(~) x

(for x from 0 to 1). 5.

The potential function

("Wintner's potential") has a singularity at the origin, not a minimum. Despite that, the origin is a stable equilibrium position of the corresponding mechanical system. This shows that the opposite of Lagrange's theorem, which states that a minimum of the potential is a stable equilibrium position, is not valid. Try to plot this potential function. Why is it so hard to see its main qualitative properties?



1.5.2 Example: The Triple Pendulum

Let us now tum to a less trivial example and look at a planar triple pendulum (see Figure 1-7). It consists of three homogeneous rods of equal1engths (I) and masses (m). The rods shall be joined by cylindrical joints, such that they are allowed to move in a

1. Basics

90

InterpolatingFunction[{O., 1.}, ] [t], phi3[t] -> InterpolatingFunction[{O., 1.}, ] [t]}}

... but not accurate enough; let us look at some plots to make that clear.

1.5 Plots: Different Pendulums

99

We study the angle phi 1 [ t] first. To get a plot of its time-dependency, we must substitute the solution for phi 1 [t] , which was returned as a rule, and plot the resulting function. We also request the computing time, to again learn something new. In[29j:=

Plot [phi1[tl

I. lagSolRule, {t, 0, l}l II Timing

0.9 0.8 0.7 0.6 0.5 0.4 0.3 Oulf2~=

{4.65 Second, -Graphics-}

Let us note how the plot command works: The graph is produced by evaluating the function-the argument of the Plot command-for the necessary sample points. In our case, the substitution phi 1 [t] /. lagSolRule has to be evaluated at every point. This is not necessary, because the substitution can be done once, and the resulting expression can be used to draw the plot. We enforce such an evaluation with the function Evaluate. On some computers, this saves time: In[30]:=

Plot [Evaluate [phil [tl I. lagSolRule], {t, 0, l}l II Timing

0.9 0.8 0.7 0.6 0.5 0.4 0.3

OUlf30= {1.75 Second,

-Graphics-}

100 I&'

1. Basics

Wherever possible, the arguments of plot commands should be evaluated first, by using the function Eval ua teo

The actual plot is the second element of the above result list. We pull it out and give it a name. In[31]:=

lagl

= %[ [2]]

Out[31]= -Graphics-

The solution of the linearized equations look quite different: In[32]:=

linl = Plot[Evaluate[phi1[t]

Oulf3~=

-Graphics-

/. linSolRule],

{t, 0, l}]

Mathematica has used different ranges and axes for these two plots-it does not know that we want to compare them. We could set the ranges by hand, using PlotRange, but it is even simpler to compare the two plots by combining them.

101

1.5 Plots: Different Pendulums In[33}:=

linLagl

= Show [ {linl,

lagl}, PlotLabel - > "phil"] phil

Out[33}= -Graphics-

For these initial conditions, the linearization is obviously not very trustworthy. Let us compare the displacements of the other angles by combining the two solutions in one step. In[34}:=

linLag2 = Plot [Evaluate [ {phi2[t] /. lagSolRule, phi2[t] {t, 0, 1}, PlotLabel -> "phi2"] phi2

O.B 0.6 0.4 0.2

Out[34}= -Graphics-

/. linSolRule}],

102

1. Basics

In[35}:=

linLag3 = Plot [Evaluate [ {phi3[t] /. lagSolRule, phi3[t] /. linSoIRule}], {t, 0, i}, PlotLabel -> "phi3"] phi3 0.2 0.15 0.1 0.05

-0.05 -0.1

Out[35}= -Graphics-

We can put all three graphics into a single GraphicsArray. The option Frame -> True draws a frame around it. In[36}:=

Show [GraphicsArray [{linLagi, linLag2, linLag3}], Frame -> True] phi2

0.8

0.15

0.6

0.6 0.4

0.4

0.2

0.2

0.2

Oulf3~=

phi3

0.2

0.8

0.4

0,6

0.8

0.1 0.05

0.2

0.4

0.6

0.8

-0.05 -0.1

-GraphicsArray-

The situation is very different, if we choose an initial displacement which is 20 times smaller. In[37}:=

In[38]:=

In[39}:=

small Initials {phil [0] == 0.05, phi2[0] phil' [0] == d, phi2' [0]

== 0, phi3[0] == 0, phi3' [0]

smallLagEquInits = Flatten [{lagEquations, smaIIInitials}] /. valueRule; smallLinEquIni ts Flatten[{linEquations, smaIIInitials}] /. valueRule;

0, O};

103

1.5 Plots: Different Pendulums ~

Patience. In{40}:=

smallLagSolRule NDSolve[smallLagEquInits, angles, {t, 0, l}];

In{41}:=

smallLinSolRule = NDSolve[smallLinEquInits, angles, {t, 0, l}];

We now want to produce the array without showing all the auxiliary plots. The display of graphics can be suppressed with the setting DisplayFunction -> Identity. In{42}:=

smallLinLagl = Plot [Evaluate [ {phil[t] /. smallLagSolRule, phil[t] /. smallLinSolRule}], {t, 0, 1}, PlotLabel -> "phil", DisplayFunction -> Identity];

In{43}:=

smallLinLag2 = Plot [Evaluate [ {phi2[t] /. smallLagSolRule, phi2[t] /. smallLinSolRule}], {t, 0, l}, PlotLabel -> "phi2" , DisplayFunction -> Identity];

In{44}:=

smallLinLag3 = Plot [Evaluate [ {phi3[t] /. smallLagSolRule, phi3[t] /. smallLinSolRule}], {t, 0, l}, PlotLabel -> "phi3" , DisplayFunction -> Identity];

The three plots are now combined in an array. In{45}:=

Show [GraphicsArray [ {smallLinLagl, smallLinLag2, smallLinLag3}], Frame - > True] phi2

phil

phi3

0.05 0.04

0.04

0.01 0.0075 0.005 0.0025

0.03

0.03 0.02

0.02

0.01

0.01 0.2

0.4

0.6

0.8

Out{45}= -GraphicsArray-

-0.0025 -0.005 0.2

0.4

0.6

0.8

104

1. Basics Because we have produced a new graphics object, it is not necessary to explicitly change the

DisplayFunction, in order to display the graphics. To show a single plot (e.g., smallLinLagl), we would have to set DisplayFunction -> $DisplayFunction.

With these "small" displacements, no visible difference can be seen between the linearized and the nonlinear system, proving that linearization can be usedwith care.

o

Graphics without a Notebook Interface

The X windows system has the great advantage that Mathematiea does not need to be running on the user's machine. The graphics can be sent over the network and displayed in full quality. This allows to access powerful workstations for time-consuming tasks. In such a situation, some things have to be set up right for the graphics to work correctly. Let us assume that we are sitting in front of the machine "Ioealhost", and that we have made a remote login (r log in) to the machine "remotehost". If we now start M athematiea on remotehost, we will get a message, telling us that graphics will only be displayed in text quality ("Terminal graphics initialized"). That is not what we want. We better go through the following steps: First, we tell/oealhost that the machine remotehost is allowed to display the graphics on our screen. This is done by typing X h0 s t

remotehost

into a terminal window of loealhost. This will return a message of the form: remotehost added to access control 1 i st.

Afterwards, we r log into remotehost and tell the machine that we want to send the graphics to loealhost, by setting the environment variable DIS P LA Ycorrectly: r log i n remotehost setenv DISPLAY localhost:O We can now start Mathematiea on remotehost. If everything went fine, we will see a message like "Motif graphics initialized". All graphics will be displayed in full quality on the screen.

105

1.5 Plots: Different Pendulums

o

Summary

• Wherever possible, the first argument of plot functions should be evaluated with Evaluate. Expression

Meaning

Join [list1' list2)

combine two (or more) lists

Fla t ten [list)

flatten a nested list by removing all inner braces

Evaluate [expr)

evaluate expr, even if it appears in a function whose attributes (see Section 2.3.3) specify that it should not be evaluated

Save [ "filename" ,

append the definitions of the symbols symhi to a file

symhj, symh2' ... )

Table 1-39: New functions Expression

Meaning

GraphicsArray [ {gj, g2' GraphicsArray [ { {gj, g2'

... } )

a row of graphics

... }, ... } ) a two-dimensional array of graphics

Table 1-40: Arrays of graphics Option

Values

Meaning

DisplayFunction

$DisplayFunction Identity Display [channel, #)&

• display on the screen (default) • suppress the display of graphics • display on channel

Frame

True False

• draw a frame around the plot • do not draw a frame (default)

Table 1-41: More options for graphics

o

Exercises

1. Compare the total CPU times needed for the simplification of the EulerLagrange equations, either by simplifying the Lagrange function first (as in In[1S]:= and In[16]:=), or by only simplifying the equations (Out[13]=). 2. Calculate and plot the movement of the triple pendulum for different initial conditions.

106

1. Basics

3. Compare the solutions of the linearized and the nonlinear triple pendulum for the following two sets of initial conditions: CPl (0)

= 0.35589, ~l (0)

CP2 (0)

= 0, CP3 (0) = -1.0677,

= ~2(0) = ~3(0) = 0

and CPl (0)

= 0.03559, ~1 (0)

CP2 (0)

= 0, CP3 (0) = -0.l068 ,

= ~2(0) = ~3(0) = O.

Discuss the results.



1.5.3 Three-Dimensional Graphics and Animation: A Rotating Double Pendulum

o

A Rotating Double Pendulum

To discuss the potential of a double pendulum rotating around the vertical axis (see Figure 1-10), we need three-dimensional plots. This mechanical system is a nice example for the introduction of such plots.

Figure 1-10: A double pendulum, rotating around the vertical axis

107

1.5 Plots: Different Pendulums

If the speed of rotation 0) vanishes, the system obviously has four equilibrium positions: one "hanging" and one "standing", and two more, where one of the rods is standing and the other is hanging. The hanging equilibrium position is stable, the other three are unstable. This behavior changes with a large enough speed of rotation 0).

The equilibrium positions and their stability can be discussed by looking at the potential function with respect to a coordinate system which is rotating with the pendulum. To derive this potential, we first choose a coordinate system at rest. With respect to this inertial system, the potential energy turns out to be (see In[2]:= on page 91): In[1]:=

epStat = -

(m 1 9 /2) (3 Cos [phil] + Cos [phi2] ) ;

We suppressed the time-dependency here, since there is no need to calculate any derivatives.

The kinetic energy is composed of one part containing the derivatives of the angles, and another (ekRo t) containing 0). The first part corresponds to the triple pendulum of the last section (ekl + ek2). We do not need it explicitly here. A correct calculation of the second part gives: In[2]:=

ekRot = 1/2 (m l"2 / 3 omega"2 Sin [phil] "2 + m 1"2 / 12 omega"2 Sin[phi2]"2 + m 1"2 omega"2 (Sin[phi1] + 1/2 Sin[phi2])"2);

We have denoted the rotational speed co by omega.

The Lagrange function of our system is ekl + ek2 + ekRot - epStat. Because ekRot does not contain any derivatives of the angles, we might as well consider it to belong to the potential energy, with a negative sign. The EulerLagrange equations (1.7) are not affected by this change of interpretation. We thus get the following effective potential in the rotating system: In[3]:=

epStat - ekRot

Oulf~=

:ig_1_~_i~_~Q§12~~~1_~_~Q§12b~~lll +

(:i1~_~_Q~~g~~_§~~12b~~1~l 1

2

m omega

2.. Sin [phi2] 2 (Sln[phll] + ----2----) -

1~-~-Q~~g~~2§~~12b~~1~) /

2

108

1. Basics

The mass, length, and time can again be scaled such that m, I, and g each become l. This reduces the effective potential, as a function of phi 1, phi 2, and omega, to:

= epStat

In[4]:=

epEff

- ekRot /.

Oulf~=

:~_~Q§lPg~1~_:_~Q§lpg~~1 +

{m -> 1, 1 -> 1, g -> I}

(:lQ~§9~~_~~~12g~11~l omega

2

. . Sin[phi2j 2 (Sln[phllj + ----2----) -

Q~§g~~-r~~lPg~~l~) /

2

The function epEff will be our starting point for the discussion of the equilibrium positions of the system. The Euler-Lagrange equations (l.7) show that the equilibrium positions correspond to a vanishing gradient of the potential function. A theorem of Lagrange proves that a minimum of the potential function corresponds to a stable equilibrium position. (The opposite is not true, see Exercise 5 on page 89.) Saddle points and maxima are unstable.

o

Surface Plots

We first produce a three-dimensional plot of epEff, for a vanishing angular velocity CD. The Mathematica function for surface plots is called plot3D. In analogy to Plot, it expects the function to be plotted as its first argument, and then two lists of the variables, together with their boundaries. In[5]:=

Plot3D[Evaluate[epEff /. omega -> 0]' {phil, -pi, Pi}, {phi2, -Pi, Pi}]

1.5 Plots: Different Pendulums

Oulf~=

109

-SurfaceGraphics-

On color monitors, this picture will appear in color.

The minimum at {3,

ouq~=

-SurfaceGraphics-

-1, l}l

We now look at the plot from the point with coordinates (x, y, z) = (3, -1, 1). On some notebook front ends (e.g., on the Macintosh), the view point can be selected with a nice interactive tool (3D ViewPoint Selector ... , under the Action menu Prepare Input). On other machines (e.g., SiliconGraphics) the plots can be rotated in real-time. Let us look at the other options of Plot 3 D. In[8]:=

Options [Plot3D]

Ouq~=

{AmbientLight -> GrayLevel[O] , AspectRatio -> Automatic, Axes -> True, AxesEdge -> Automatic, AxesLabel -> None, AxesStyle -> Automatic, Background -> Automatic, Boxed -> True, BoxRatios -> {I, 1, 0.4}, BoxStyle -> Automatic, ClipFill -> Automatic, ColorFunction -> Automatic, ColorOutput -> Automatic, Compiled -> True, DefaultColor -> Automatic, Epilog -> {}, FaceGrids -> None, HiddenSurface -> True, Lighting -> True, LightSources -> {{{I., 0., I.}, RGBColor[l, 0, OJ}, { {I., 1., I.}, RGBColor [0, 1, O]}, {{O., 1., I.}, RGBColor[O, 0, I]}}, Mesh -> True, MeshStyle -> Automatic, PlotLabel -> None, PlotPoints -> 15, PlotRange -> Automatic, PlotRegion -> Automatic, Plot3Matrix -> Automatic, Prolog -> {}, Shading -> True, SphericalRegion -> False,

111

1.5 Plots: Different Pendulums

Ticks -> Automatic, ViewCenter -> Automatic, ViewPoint -> {1.3, -2.4, 2.}, ViewVertical -> {O., 0., l.}, DefaultFont :> $DefaultFont, DisplayFunction :> $DisplayFunction}

We use some of them to label the axes, to rescale the box, to move the ticks and the label of the phi 1 axis down, and to produce a title. In[9j:=

Show [%%, AxesEdge -> {{-1, -1}, {1, -1}, {1, 1}}, AxesLabel -> {"phil", "phi2", "epEff"}, BoxRatios -> {1, 1, .S}, PlotLabel -> "omega = 10"] omega

=

10

-50

epE f

phi2

ouq~=

o

-SurfaceGraphics-

Contour Plots

Contour plots often are a useful alternative to surface plots. The corresponding function is called ContourPlot. It expects the same arguments as Plot3D, but some of its options are different.

1. Basics

112 In[10}:=

ContourPlot [Evaluate [epEff /. omega -> 10], {phil, -pi, pi}, {phi2, -Pi, pi}]

OUlf10= -ContourGraphics-

ContourPlot has the following options: In[11}:=

Options [ContourPlot]

Out[11}= {AspectRatio -> 1, Axes -> False, AxesLabel -> None, AxesOrigin -> Automatic, AxesStyle -> Automatic, Background -> Automatic, ColorFunction -> Automatic, ColorOutput -> Automatic, Compiled -> True, ContourLines -> True, Contours -> 10, ContourShading -> True, ContourSmoothing -> None, ContourStyle -> Automatic, DefaultColor -> Automatic, Epilog -> {}, Frame -> True, FrameLabel -> None, FrameStyle -> Automatic, FrameTicks -> Automatic, PlotLabel -> None, PlotPoints -> 15, PlotRange -> Automatic, PlotRegion -> Automatic, Prolog -> {}, RotateLabel -> True, Ticks -> Automatic, DefaultFont :> $DefaultFont, DisplayFunction :> $DisplayFunction}

By giving a suitable color function, the picture can be colored. The predefined function Hue is very useful. If given one argument, it produces the color circle in full saturation and brightness. In[12]:=

ContourPlot [Evaluate [epEff /. omega -> 10], {phil, -pi, pi}, {phi2, -Pi, Pi}' PlotPoints -> 40, ColorFunction -> Hue]

1.5 Plots: Different Pendulums

113

This plot is shown as Color Plate I on page 1. Oulf1~=

-ContourGraphics-

By default, the contour lines are not smoothed; this could be requested with the option ContourSmoothing -> True. Because we have increased the number of PlotPoints, smoothing is not necessary here. Instead, we redraw the plot with more and thinner lines (option Make Lines Thin in the Graph menu of the notebook front end). In[13]:=

Show[%, ColorFunction -> Automatic, Contours -> 25] 3

:) o -1

-2

(

-3

Oulf1~=

-ContourGraphics-

The option Contours allows us to control the contour lines to be drawn. We can pass their number, or a list of the chosen lines (e.g., Contours -> {O} for the zero level). The generalization of contour plots to the dimension three-i.e., drawing surfaces of constant values of functions of three variables-is implemented in the function ContourPlot3D of the standard package Graphics' ContourPlot3D'. It can be used to plot implicitly defined surfaces. Implicitly defined functions of two variables can be visualized with the function Irnplici tPlot from the package Graphics' Irnplici tPlot '.

1. Basics

114

D

Density Plots

Instead of drawing contour lines, one can put a grid onto the plane of variables and display each rectangle with a gray-level or color corresponding to the value of the function at that point. This produces a density plot. In[14}:=

DensityP10t [Evaluate [epEff /. omega -> 10], {phil, -Pi, pi}, {phi2, -pi, Pi}] 3

2 r-t-t-t-t-t-t-t-+-

o -1

-2

Out[14}= -DensityGraphics-

This plot (with a 15x15 grid) is not very useful. We improve it by increasing the number of PlotPoints and by removing the grid lines. In[15}:=

DensityP10t [Evaluate [epEff /. omega -> 10], {phil, -pi, Pi}, {phi2, -pi, pi}, P1otPoints -> 50, Mesh -> False]

115

1.5 Plots: Different Pendulums

3

2

o -1

-2

-3 -3 Oulf1~=

3

-DensityGraphics-

When changing between the different types of plots, it is not necessary to recalculate everything; they can be converted into each other. For instance, the above density plot is turned into a surface plot by: In{16]:=

Show [SurfaceGraphics [%]]

Oulf1~=

-SurfaceGraphics-

1. Basics

116

Other possible conversions are listed in Table 1-43.

o

Animations

We now have seen different graphical representations of the potential function of our pendulum, for the two values 0 and 10 of the rotational speed omega. How does the potential depend on this parameter? Let us study the most interesting range, from (0 = 0 to 2. We can use the Table command to produce a list of plots for different values of (0, e.g., from 0 to 2, with steps of 0.1. It is useful to choose equal plot ranges for all pictures, e.g., from -6 to 2. Let us also label the plots, by joining the string "omega = "with the current value of omega, which must be converted into a string by ToString. In[17]:=

Oulf1~=

plots = Table [Plot3D [Evaluate [epEff] , {phil, -pi, pi}, {phi2, -pi, pi}, PlotRange -> {-6, 2}, BoxRatios -> {1, 1, 1}, ViewPoint-> {O.7, -2, 2.6}, PlotLabel -> StringJoin["omega {omega, 0, 2, . 1} ]

ToString[omega]]],

{-SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-, -SurfaceGraphics-}

The 21 plots are not shown here, because we are mainly interested in their animation. Still, for readers who do not reproduce our calculations on their computer, we add an array of all the plots:

1.5 Plots: Different Pendulums In[18]:=

Show [GraphicsArray [ Table[plots[[7(i-l) + j]], {i, 3}, {j, 7}]])

OUlf1~=

-GraphicsArray-

117

• On a notebook front end, we can now animate the grouped plots (Out[17J=) by selecting them and choosing the command Animate Selected Graphics in the Graph menu (see Figure 1-11). • Without a notebook front end, we can produce the same animation with the command ShowAnimation from the package Graphics' Animation' . In[19]:=

«Graphics' Animation'

In[20]:=

ShowAnimation [plots]

It will display a "movie" consisting of the above plots. Rulers and buttons allow us to change the speed, direction, etc. of the animation. By using such animations, the study of parameter dependencies can be increased by one dimension. The additional parameter is mapped onto the time dimension. In our example of the pendulum, we can clearly see how the original minimum in the middle turns into a saddle point and finally into a maximum, when (J) is increased. The minimum is replaced by two minima. This is called a bifurcation. We end by saving the effective potential for later use. In[21]:=

Save [lrotDoublePend.m", epEff]

118

1. Basics

10

Chapter 1.5 1r(t7J;.

plots . Table(Plot3D[ Evaluate ( epEf:f(. (phil . -Pi. Pil. (phi2. - Pi. Pi). PlotRange - > ( - 6. 2). BoxRatios - > (1. 1. 1). Vle\IPolllt- > (O.7. - 2. 2.61. PlotLabel - > StringJoin[ - ""ega • - . ToStrlllg( ""ega) II. {.",ega. O. 2. .111

q:>

"

IOO False, Axes -> False

Oulf~=

-Graphics3D-

We have used two options to suppress the surrounding box and the axes. By suppressing the lines, the torus can be displayed "naked". • In a notebook front end, the Show Lines command in the Graph menu can be used to achieve this. • Without a notebook front end, the task is a little more complicated: The graphics object must be shown again, together with the graphics directive EdgeForm [ J , which suppresses the edges. The graphics primitives that make up the plot are contained in %[ [lJJ . If we prepend EdgeForm [J to it, combine the two into a list, and put the list into a Graphics3D object, the desired graphics can be displayed with a Show command (see Section 1.7.1).

1.5 Plots: Different Pendulums In{3]:=

torus = Show [Graphics3D [{EdgeForm [], % [ [1] ] }] , Boxed -> False]

Oulf~=

-Graphics3D-

123

We now reload the definitions for the rotating double pendulum from the last section. In{4]:=

«rotDoublePend.m;

Let us visualize the potential in configuration space, first. We do this by coloring the torus according to the values of the potential. This is achieved by adding a fourth element to the list of the coordinates, which defines a color or a gray-level. For omega = 0, the range of the potential reaches from -2 to 2. We can therefore produce a gray-level between 0 and 1 by adding 2 and dividing by 4. The option Lighting -> False turns the automatic lighting off, assuring that it will not compete with our given shading. In{5]:=

ParametricPlot3D [ Evaluate [ {

]

,

Cos [phi1] (r1 + r2 Cos[phi2]), Sin[phi1] (r1 + r2 Cos[phi2]), r2 Sin[phi2], GrayLevel[(epEff + 2)/4] } I. {m -> 1, 1 -> 1, g -> 1, omega -> O}

{phil, 0, 2Pi}, {phi2, 0, 2Pi}, Lighting -> False

124

1. Basics

Oulf~=

-Graphics3D-

The minimum of the potential corresponds to the darkest point at the right, the maximum to the lightest, inside, at the left. We now draw the potential for a rotational speed of omega = 10. For a better visualization, we use colors instead of gray-levels. The color function Hue (see Table 1-48) makes this task easy. If we give it one parameter, the interval [0, 1] is mapped onto the color circle, using the hue values with full saturation and brightness. We therefore have to find the maximum and the minimum values of the effective potential at = 10. The function FindMinimum, which searches for a (local) minimum, does that for

omega

us. In[6]:=

FinCiMinimum[epEff /. {m -> 1, 1 -> 1, g -> 1, omega -> 10}, {phil, -2}, {phi2, -2}]

Out[6]=

{-133.341,

In[?]:=

FinCiMinimum[-epEff /. {m -> 1, 1 -> 1, g -> 1, omega -> lO}' {phil, pi}, {phi2, Pi}]

Out[?]=

{-2.,

{phil -> -1.56261, phi2 -> -1.5648}}

{phil -> 3.14159, phi2 -> 3.14159}}

Notice that we can find a maximum by looking for the minimum of the negative expression. The potential ranges from -133.3 to 2. By adding 133.3 and dividing by 135.3, the mapping to the desired range of [0,1] can be achieved. To make the grid more even, we use three times as many sample points for the first angle as above. In[8):=

ParametricPlot3D [ Evaluate [

1.5 Plots: Different Pendulums

125

{

]

Cos [phil] (r1 + r2 Cos[phi2]), Sin[phi1] (r1 + r2 Cos[phi2]), r2 Sin[phi2], Hue[(epEff + 133.3)/135.3] I. {m -> 1, 1 -> 1, g -> 1, omega -> 10}

,

{phil, 0, 2Pi}, {phi2, 0, 2Pi}, Lighting -> False, PlotPoints -> {45, 15}

This plot is shown as Color Plate 2 on page I. Oulf~=

-Graphics3D-

Let us now take the movement of the pendulum into account. It corresponds to a curve on the torus. To set up the Euler-Lagrange equations (as for the triple pendulum in Section 1.5.2), we have to write the angles phi 1 and phi 2 as functions of the time-otherwise, the time derivatives would not be calculated correctly. In[9]:=

epT

=

epEff I.

{phil -> phil [t], phi2 -> phi2 [t] };

The kinetic energy in the rotating reference system corresponds to the first two terms of the kinetic energy of the triple pendulum (see Section 1.5.2). In[10]:=

ek1

(1/2)

In[11]:=

ek2

(m

(m lA2 1 3) phil' [t]"2;

1"2/2) * «phi2' [t]"2/12) + (phil' [t] Cos [phil [t]] + phi2' [t] Cos[phi2[t]]/2)"2 + (phil' [t] Sin[phi1[t]] + phi2' [t] Sin[phi2[tll/2)"2

) ;

In[12]:=

ek = ek1 + ek2;

The Lagrange function turns out to be: In[13]:=

lag = ek - epT;

The equations of motion (see Equation (1.7)) therefore are:

126

1. Basics

In[14}:=

lagEquations {

D[D[lag, phil'[t]], t] D[D[lag, phi2' [t]], t]

- D[lag, phil[t]] - D[lag, phi2[t]]

0, 0

} ;

We now define a vector for the two angles and select initial conditions. In[15]:=

angles = {phil [t], phi2 [t] };

In[16}:=

initials {phi1[0] == 0, phi2[0] == 0, phil' [0] == 0, phi2' [0] == 5};

As parameter values, we choose: In[17]:=

valueRule = {m -> 1, 1 -> 1, 9 -> 1, omega -> O. 5};

The equations and the initial conditions (with the selected parameter values) are combined in a list: In[1B}:=

lagEqulnits valueRule;

Join [lagEquations, initials]

/.

This system can be solved with NDSol ve. ~ The simulation might take some time. In[19}:=

NDSolve[lagEqulnits, angles,

{t, 0, 10}];

NDSolve: :rnxst: Maximum number of 500 steps reached at the point 8.73558.

The default value of 500 for the maximum number of integration steps (MaxSteps) was not sufficient. To be on the safe side, we set it to 2000. In[20}:=

lagSolRule = NDSol ve [lagEqulni t s, angles, MaxSteps -> 2000];

{t, 0, 10 } ,

This solution can, for instance, be visualized by a planar parametric plot. We use the function ParametricPlot to draw it. In contrary to plots showing the time dependency of phi 1 [t 1 and phi 2 [t 1, we can see both angles in one picture-but the information about the velocities is lost.

1.5 Plots: Different Pendulums In[21]:=

127

ParametricPlot [Evaluate [angles I. lagSolRule], {t, 0, lO}, AxesLabel -> {"phil", "phi2"}] phi2 15 12.5 10 7.5 5

2.5 ;------72------4~----~6~--~78----phil

Out[21]= -Graphics-

As said before, the configuration space of the system is a torus. The two angles in the above plot should therefore be reduced modulo 21t. To draw the curve on the torus, we define expressions for the two angles, first. This makes things easier to grasp. In[22]:=

phi 1

(phi1[t] I. lagSolRule[[l]]);

In[23]:=

phi2

(phi2[t] I. lagSolRule[[l]]);

We now map the curve onto the torus by using the parametric representation from above. In[24]:=

ParametricPlot3D [ {

Cos [phil] (rl + r2 Cos[phi2]), Sin[phil] (rl + r2 Cos[phi2]), r2 Sin[phi2] } II Evaluate, {t, 0, lO}]

128

1. Basics

Out[24}= -Graphics3D-

This picture shows some comers. Let us redraw it with more plot points. At the same time, we slightly increase the radius r2. This will move the curve above the torus in the following plot. In[25]:=

sol = ParametricPlot3D [ {

Cos [phil] (rl + (r2 + .05) Cos[phi2]), Sin[phil] (rl + (r2 + .05) Cos[phi2]), (r2 + .05) Sin[phi2] } II Evaluate, {t, 0, 10}, PlotPoints -> 500]

Out[25}= -Graphics3D-

We can now view the curve and the torus in one picture.

129

1.5 Plots: Different Pendulums In[26]:=

Show [torus, sol, Boxed -> False, Axes -> False]

Oulf2~=

-Graphics3D-

o

Summary Expression

Meaning

ParametricPlot[ifx' iyL {t, tmin' lmax} 1

draw a planar parametric curve

ParametricPlot3D[lfx' i y ' izL {t, lmin' lmax} J

draw a parametric curve in threedimensional space

ParametricPlot3D[ifx' i y ' izL

draw a parametric surface in threedimensional space

{u, {v,

umin ' vminl

u max } , v max } 1

ParametricPlot3D[{ix ' i y ' iz' s},

draw a parametric surface with a given shading function s

ParametricPlot3D[{ifx' i y ' iz}, {gx' gy' gzL ... L ... J

create several objects simultaneously

{u, umin ' u max } , {v, Vminf v max } 1

Table 1-50: Parametric plots Option

Meaning

Axes

• True: show axes • False: do not show axes • {False, True}: show the y-axis only, etc.

Boxed

show the bounding box (True) or not (False)

Lighting

the lighting is turned on (True) or off (False)

Table 1-51: More options of three-dimensional graphics

130

1. Basics

Graphics Directive

Meaning

EdgeForm [ J

do not draw edges in three-dimensional graphics

Table 1-52: Control over the edges (see also: Table 1-83 on page 177) Expression

Meaning

FindMinimum [j,

{x,

xo} J

FindMinimum [j,

{x,

{xo,

FindMinimum [j,

{x, xo},

find a local minimum off, by starting with the variable x at Xo two starting values

xl} J } J

{x, xl },

•.• J

find a local minimum in several variables

Table 1-53: Local minima of functions Option

Meaning

MaxSteps

controls the maximum number of integration steps (default: 500)

Table 1-54: An option of NDSol ve

o

Exercises

1. Create some Lissajous figures. 2. Draw the surface of a sphere. 3. Integrate and visualize the movement of the rotating double pendulum for other speeds of rotation and initial conditions. 4. Create the picture on the cover of this book. It contains the above solution of the rotating double pendulum (see In[20]:=) and the corresponding potential, visualized on the torus.



1.5.5 Plotting Data: The Random Generator

We now want to learn how discrete data can be plotted. They may have been produced within Mathematica, or read in as external data. In Section 1.5.3, we have seen that the Table command can be used to generate lists of data. We use it together with Random (see Section 1.3.3) to produce the following data:

131

1.5 Plots: Different Pendulums

= Table[Sin[x]

In[1]:=

data

Out[1}=

{0.0376276, 0.139954, 0.288671, 0.349041, 0.438319, 0.542541, 0.646935, 0.655175, 0.775171, 0.85537, 0.919055, 0.967019, 0.982212, 1.03198, 1.04543, 1.0061, 1.05848, 1.04368, 1.0631, 0.947517, 0.987474, 0.893585, 0.88028, 0.801503, 0.716012, 0.688727, 0.597284, 0.429657, 0.426637, 0.266388, 0.24061, 0.132901, -0.0245409, -0.10265, -0.233636, -0.335275, -0.35886, -0.443163, -0.549933, -0.680867, -0.732051, -0.783619, -0.798902, -0.910484, -0.905027, -0.973247, -0.992801, -0.950039, -0.990139, -0.968424, -0.939816, -0.878207, -0.869078, -0.745378, -0.753146, -0.649253, -0.550723, -0.518892, -0.366889, -0.333098, -0.182532}

+ Random[Real, {O, .i}], {x, 0, 6, .i}]

The data consist of samples of the sine function, with superimposed "noise". Let us save them to a file, by using Save (see Section 1.5.2). In[2}:=

Save ["data-file .m", data]

In this way, they can be loaded at any time, using: In[3}:=

«data-file.m;

A similar set of data could have been produced by an experiment or some other computer program. In such a case, it would not be formatted as a list and would not already have a name. Rather, the numbers would be separated by tabs, returns or other characters. The file raw - d at a - f i 1 e . m contains a sample of this: In[4}:=

! ! raw-data-file.m

0.07969920798244439641 0.1787077119611948357 0.2830460518433956467 0.3739062229241107927 0.4766450587944032154 0.5347970425969157563 0.6430007733633298818 0.7098414663893140734 (Further numbers are suppressed.)

We use the function ReadList to read the file. In our example, it contains real numbers, separated by tabs. We therefore write: In[S]:=

expData

= ReadList ["raw-data-file.m",

The function ListPlot generates a plot of data.

Real];

132

1. Basics

In[6J:~

ListPlot [expData] 1

..

... ... .. .... '.

0.5

10 -0.5

20

.. 30

..

40

..

-1 Oulf~~

50

60

. .. .. .... .'

-Graphics-

By setting the option PlotJoined -> True, the points are connected by straight lines. In[7]:~

ListPlot [expData, PlotJoined -> True]

Oulf~~

-Graphics-

The horizontal axis corresponds to the position of the numbers in the list. Therefore, the curve starts with the value one. We could have given a list of (x, y)-values, to produce another scale. We will see how this can be done elegantly in Section 1.6.4, after having learned more about handling lists. The data points can be interpolated with Interpolation, if required (see Section 1.8.4).

Let us now use such list plots to study the random generator in Mathematica. In[8]:~

ListPlot [Evaluate [Table [Random [],

{100}]]]

133

1.5 Plots: Different Pendulums

..

. . ..

1 0.8 0.6

..

..

0.4

..

0.2

... .

.. ...

. 20

Oulf~=

.

..

40

60

80

100

-Graphics-

We could make the list longer; the resulting plot would not become much more useful. It makes more sense to plot pairs of random numbers. They should evenly fill up the unit square. In[9]:=

ListPlot [Evaluate [Table [{Random [], Random [] }, {lOa}]]] 1 ••

0.8 0.6

o. 4 0.2

.. •

• ••

:

..

.. 0.2

Oulf~=

..

.. 0.4

0.6

.' 0.8

1

-Graphics-

By default, Mathematica displays graphics using the golden ratio between the horizontal and the vertical axis. This does not make sense here. This ratio can be matched to the parameter ranges, by setting AspectRatio -> Automatic.

134 In[tO}:=

1. Basics ListPlot [Evaluate [Table [{Random [], Random [] }, {100}]], AspectRatio -> Automatic]

0.8

'.'

.'

.

o. 6

0.4

0.2

0.2

0.4

0.6

0.8

OUlft0= -Graphics-

We get a denser picture, if we choose more points. In[tt}::

ListPlot[Evaluate[Table[{Random[], Random[]}, {l0000}]], AspectRatio -> Automatic]

Out[tt}= -Graphics-

135

1.5 Plots: Different Pendulums

This plot looks good: No structure is visible. Of course, a specialist in statistics probably would find something wrong in it. The functions ListPlot3D, ListContourPlot, and ListDensityPlot plot threedimensional data sets. All of them expect the data to represent z-values, corresponding to an (equidistant) array in the (x, y)-plane. If this is not true, we can use the functions ScatterPlot3D and ListSurfacePlot3D from the package Graphics' Graphics3D' . They work with tables consisting of triples of (x, y, z)-values. The (x, y)-values do not need to be on an array. If the triangulation of the (x, y)-plane presents a problem, because the data points are not ordered, the package DiscreteMath' CornputationalGeornetry' can be very helpful.

o

Summary

Expression

Meaning

ListPlot [ {YI' Y2, ... } 1

draw a plot of the y-values, where I, 2, ... are chosen as x-values

ListPlot [ { {xI' YI },

{x2' Y2},

... } 1 draw a plot of a list of (x, y)-values

ListPlot3D [ { {zll' z12' ... } , {z21' z22, ... } , ... } } 1

draw a surface plot of the given z-values, for an (equidistant) array of (x, y)-values

ListContourPlot[{{zll' z12' ... }, {z21' z22' ... } , ... }} 1

draw a contour plot for an array of z-values

... } ,

draw a density plot for an array of z-values

ListDensityPlot[{{zll' Z12, {z21' z22' ... } , ... } } 1

Table 1-55: Data plots Option

Meaning

Aspec tRa t i 0

the ratio of height to width

Table 1-56: An option of Show Option

Meaning

PlotJoined

the plot points are joined (True) or not (False)

Table 1-57: An option of ListPlot

136

1. Basics

Expression

Meaning

ReadList ["file"]

read the remaining data fromjile (the structure of the data can be defined with the options of Table 1-60 and/or by giving a sequence of types)

ReadList ["file" , type]

read data of type type (see Table 1-59); generate a list

ReadList ["file" , {typel' typ e2'

... } ] read data of different successive types

ReadList ["file" , types, n]

read the first n data points

Table 1-58: Reading external data Type

Meaning

Byte

a single byte, represented as integer code

Character

a single character

Expression

a Mathematica expression

Number

an exact or an approximate number

Real

an approximate number

Record

a record, delimited according to the setting of RecordSepara tors

String

a string, terminated according to the setting of Record Separators

Word

a sequence of characters (according to WordSeparators)

Table 1-59: Data types for ReadList Option

Default Value

Meaning

NullRecords

False

put empty records between successive record separators

NullWords

False

put empty words between successive word separators

RecordLists

False

create a sublist for the objects in each separate record

RecordSeparators

{" \n"}

the word separators; other examples are: ·{"\t"}:tab • { { " < " } , { " > " } } : entries of the form

Table 1-60: Options for ReadList

137

1.5 Plots: Different Pendulums

Option

Default Value

Meaning

TokenWords

{}

the token words to be used to delimit words

WordSeparators

{

" " , "\t"}

the strings to be taken as delimiters for words

Table 1-60: Options for ReadList Package

Contents

Graphics'Graphics3D'

plots of general three-dimensional data (and more)

DiscreteMath' , ComputationalGeometry

tools from computational geometry; e.g., list surface plots with Delaunay triangulation

Table 1-61: Further tools for three-dimensional graphics

o

Exercises

1. Create a text file containing data. Read it into Mathematica and create a plot.

2. Create a surface plot of the values of y mod x (for x, y = 1, ... ,20). 3. Create a contour plot of the values of 2Y mod x (for x, y = 1, ... ,20). 4. Create a density plot of the values of 3Y mod x (for x, y = 1, ... , 20).

138

1. Basics

• 1.6 Lists Lists are an important "data type" in Mathematica. Until now, we have used them to collect rules (Section 1.4.1) and arguments of built-in functions (Section 1.4.2). We also have learned that results, which consist of several parts, are combined into lists (e.g., the solutions of equations or differential equations). In this chapter, we will study the creation, formatting, and manipulation of lists in a more systematic way. As a side-result, we willleam how to use them for vectors and matrices, and how problems of linear algebra can be solved.



1.6.1 Creating and Formatting Lists

There are different methods to create andformat lists. This section covers the most important ones.

o

Making Lists

We have already seen that a list can be defined by putting its elements, separated by commas, into curly braces.

Out[1}=

, x3, 4 x , x5} {x, x 2

The above result can as well be produced by a Table command (see Section 1.5.3). In[2}:=

Table [xAn, {n, 5}]

Out[2}=

{x, x 2 , x 3 , x 4 , x 5 }

The possible forms of index ranges are given in Table 1-63 on page 141. One often needs parts of arithmetic sequences. They can be produced with the function Range. In[3}:=

Range [ 5 ]

Out[3}=

{1 ,

2,

3, 4,

5}

1.6 Lists

139

Range also allows the specification of a start and an end value, as well as a step size.

o

In[4]:=

Range [ . 1, 1. 1,

Out[4]=

{0.1,

.2]

O. 3, O. 5,

O. 7, O. 9, 1. 1 }

Formatting Lists

Let us consider the following list: In[5]:=

nPi = Table [N[i pi, j + 2i], {i, 3}, {j, 4}]

Ouq~=

{{3.14, 3.142, 3.1416, 3.14159}, {6.2832, 6.28319, 6.283185, 6.2831853}, {9.424778, 9.424778, 9.42477796, 9.424777961}}

With TableForm, it will be shown as a table. In[6]:=

TableForm [nP i)

Out[6}1lTableForm=

3.14 6.2832 9.424778

3.142 6.28319 9.424778

3.1416 6.283185 9.42477796

3.14159 6.2831853 9.424777961

Maybe all columns should have the same width. MatrixForm does that for us. In[7]:=

MatrixForm[%]

Out[7]IIMatrixForm=

3.14 6.2832 9.424778

3.142 6.28319 9.424778

3.1416 6.283185 9.42477796

3.14159 6.2831853 9.424777961

The result % (which actually contains a TableForm) can be used for further calculations, because the ... Form commands only act as a "wrappers", which affect the printing, but not the evaluation. One has to be careful with definitions, though (see ~ below).

TableForm and MatrixForm accept several options. With TableHeadings, for instance, the rows and/or columns can be labeled. In[8]:=

TableForm [nPi, TableHeadings -> {{" Pi:", 12Pi:", 13Pi:"}, None}]

Out[8}11TableForm=

pi: 2Pi: 3Pi:

3.14 6.2832 9.424778

3.142 6.28319 9.424778

3.1416 6.283185 9.42477796

3.14159 6.2831853 9.424777961

140

1. Basics

The following version centers the columns: In{9]:=

TableForm [nPi, TableHeadings -> {{" Pi:", "2pi:", "3pi:"}, None}, TableAlignments -> {Center, Center, Center}]

Ouf{9]I;TableForm=

pi:

2Pi: 3Pi: 1&

o

3.14 6.2832 9.424778

3.142 6.28319 9.424778

3.1416 6.283185 9.42477796

3.14159 6.2831853 9.424777961

The combination of definitions with TableForm or MatrixForm requires some care: We must enter the whole definition as the argument of TableForm or MatrixForm; otherwise, the special format of the result is assigned (see Subsection "A Possible Problem" on page 311).

Indexed Symbols

The function Array creates lists containing a symbol name and bracketized integers. Such objects can be used for indexed vectors, matrices, or tensors. By a convention in Mathematica, indices are put into single brackets. We pass the variable name as the first argument, the length of the list as the second, and, optionally, the number of the first element as the third argument. In{10]:=

Array [a, 5]

Ouf{10]= {a [1],

a [2],

a [3],

a [4],

a [5] }

The same list could also be created with the Table command: In{II]:=

Table [a [i], {i, 5}]

OUf{II]= {a [1],

a [2],

a [3],

a [4],

a [5] }

To start the indices with zero, we write: In{12]:=

Array[a, 5, 0]

Ouf{12]= {a [0],

or for a matrix:

a [1],

a [2],

a [3],

a [4] }

141

1.6 Lists In[13j:=

II MatrixForm

{3, 3}, 0]

Array [a,

Out[13jllMatrixForm= a[O, 0] a [1, 0] a[2, 0]

a [0, 1]

a [1, 1] a [2, 1]

a [0, a[l,

2] 2]

a [2, 2]

If we want to denote an indexed vector function of the parameter t, we usually write: In[14j:=

Table[a[i] [t],

Out[14j= {a[l] [t],

{i, 3}]

a[2] [t],

a[3] [t]}

In contrast to that, we might want to consider the indices as parameters. This would be denoted by: In[15j:=

Table[a[i, t],

Out[15j= {a [1,

o

t],

a [2,

{i, 3}] t],

a [3,

t]}

Summary Expression Table [expr,

Meaning range]

create a table; see Table 1-63 for the possible forms range

Table 1-62: Tables Range

Meaning

{imax}

i max copies

{i,

imax }

1, ... , i max

{i,

iminl i max }

i min , i min+l, ... , i max

{i,

iminf imaxf di}

i min , imin+di, ... , i max

{i,

iminl i max } ,

{j, Jmin' Jmax} , ...

multidimensional; the outermost list is associated with i; the above forms are possible for each dimension

Table 1-63: The different forms of ranges in Table, Sum, etc.

142

1. Basics

Expression

Meaning

Range [n]

{ 1, 2, ... , n}; an arithmetic sequence

Range [nl' n2]

{nl' nl+l, ... , n2}

Range [nl' n2, d n ]

{nl' nl+dn, ... , n2}

Array[j, n]

{j[ 1] , ... , f[ n] }; an indexed vector

Array[j, n, origin]

usef[origin] as the first element

Array[j,

{nl'

n2'

... }

]

the nested list with elements f[ iI' i2 , ... ]

Table 1-64: Special lists Expression

Meaning

TableForm [list]

show the elements of a list in the form of a table

MatrixForm [list]

show the elements of a list as a matrix, with cells of the same size

Table 1-65: Formatting of tables, lists and matrices Option

Default Value

Meaning

TableAlignments

{Left, Bottom, Left, ... }

the alignment of the entries of the different dimensions

TableDepth

Infinity

the maximum number of levels

TableDirections

{Column, Row, Column, ... }

the sequence of successive dimensions

TableHeadings

{None, None, ... }

the titles for the entries of the different dimensions

TableSpacing

{I,

... }

the number of spaces between the entries of the different dimensions

3,

0,

1,

Table 1-66: The options for TableForm and MatrixForm

o

Exercise

1. Create a 3x3x3 table, and display it in a clear manner.

143

1.6 Lists



1.6.2 Calculations with Lists, Pure Functions

We now learn how to calculate with lists. Most built-in functions with one argument directly apply themselves to the elements of a list. Otherwise, the best way is to use pure functions.

o

Operations on Lists

Algebraic functions automatically work on the elements of a list. In[1]:=

Exp[N[Range[O, 1,

Out[1]=

{l,

.2]]]

1.2214, 1.49182, 1.82212, 2.22554,

2.71828}

Note that we have done two operations here: First, the list Range [0, 1, .1] was converted to approximate numbers (with N), and then, the function Exp was evaluated for these numbers. The same applies for sums and products. We will talk about matrix products later, in Section 1.6.4. In[2]:=

c Array[a, 2] Array[b, 2]

Out[2]=

{c a [1]

b [1],

c a [ 2]

b [2] }

Technically speaking, such functions, which automatically evaluate for the elements of a list, have the attribute Listable (see Section 2.3.3).

But there are also functions which are not automatically mapped to lists, for instance Variables. It returns the variables of a polynomial. In[3]:=

Variables [x + y]

Out[3]=

{x,

y}

When applied to a list, it returns all variables appearing in the list. In[4]:=

v1 = {x + y,

In[5]:=

variables [v1]

Oulf~=

{x, y,

x,

z};

z}

If we want to see the variables of each element of the list, we have to use the function Map. It "maps" our function to all the elements.

144

1. Basics

In[6]:=

Map [Variables, vll

Out[6]=

{ {x,

y},

{ x},

{z} }

Because Map is often used in programs, we can also write it in a shorter operator form, with I @. In[7]:=

Variables /@ vl

Out[7]=

{ {x,

o

y},

{ x},

{z} }

Pure Functions

It often happens that we have to map a self-made function onto a list. [x_ 1

: = f [xl + g [xl

In[B]:=

h

In[9]:=

v2 = Array [a, 3 1

Out[9]=

{a [1],

In[10]:=

h /@ v2

a [ 2],

Out[10]= {f[a[l]]

a [ 3] }

+ g[a[l]],

f[a[2]]

+ g[a[211,

f[a[311

+ g[a[311}

It is rather tedious to define a new function, just to map it onto a list. Pure functions are a handy way of mapping something, without giving it a name and a separate definition.

The syntax of a pure function is Function [x, bodyJ. The first argument is the variable, or a list of several variables. Afterwards, in the body of the pure function, we define what shall be done with the variable(s). Our example thus simplifies to: In[11]:=

Function [x, f [xl + g [xl 1 /@ v2

Out[11]= {f[a[11]

+ g[a[l]L

f[a[2]]

+ g[a[21L

f[a[31]

+ g[a[3]1}

A short notation for pure functions uses # for the formal parameter (whose name is irrelevant), or #1, #2, ... for several parameters. In[12]:=

Function [f [#l + g [#]] /@ v2

Out[12]= {f[a[l]l

+ g[a[l]L

f[a[211

+ g[a[2]L

f[a[311

+ g[a[311}

An even shorter form only contains the body of the function, written in terms of the #, and closes the function definition with a &.

145

1.6 Lists In[13]:=

f[#]

+ g[#]&

Out[13]= {f [a [1]]

I@

v2

+ g [ a [1] ],

f [a [ 2 ]] + g [a [ 2] ],

f [a [ 3]] + g [a [ 3 ] ] }

All three notations are equivalent. The last two reduce the function completely to its contents; no irrelevant variable or function names are used. That is the reason for the term pure function. In Section 1.4.3, we have seen that the results of DSo1 ve and NDSol ve can be requested as rules for pure functions.

o

Example: The Equations of Motion of the Triple Pendulum

With these tools, we might derive the equations of motion of the triple pendulum (see Section 1.5.2) more elegantly. We first introduce the angles as an indexed list. In[14]:=

vars = Table[phi[i] [t], {i, 3}]

Out[14]= {phi[1] [t],

phi[2][t], phi[3][t]}

By using the functions Array and Through (see Table 1-68), the same list can be generated alternatively: In[15]:=

vars = Through [Array [phi, 3] [t]]

Out[15]= {phi [1] [t],

phi [2] [t], phi [3] [t] }

Our old Lagrange function is now written in terms of the new variables. In[16]:=

variableRule = {phil -> phi[l], phi2 -> phi[2], phi3 -> phi[3]};

In[17]:=

«triplePendulum.m;

In[1B]:=

lagNew

=

lag I. variableRule;

Notice that we replace phi 1, and not phi 1 [t] . The second would not replace the derivatives correctly, analogous to the solutions of DSol ve and NDSol ve (see Section 1.4.3).

The Euler-Lagrange equations can be calculated by mapping the operator D[D[lagNew, D[#, t]], t] - D[lagNew, #] == 0& onto the list of the variables. In[19]:=

D[D[lagNew, D[#, t]], t] Simplify;

- D[lagNew, #]

0& I@

vars

II

146

1. Basics

The result is suppressed, because it matches the one in Section 1.5.2. We make sure that the results are identical: Parts of equations can be extracted similarly to parts of lists (see Section 2.1.1). The next section will show that we get elements of nested lists by expressions of the fonn list [ [nI' n2, ... ]]. Therefore, the expressions % [ [i, 1]] (for i=l, 2, 3) are the left hand sides of the above equations, and lagEquations [ [i, 1]] the left hand sides of the old equations, where the angles also have to be replaced. Thus, the following table gives us the differences of the left hand sides: In[20}:=

Table [%[ [i, 1]] - lagEquations [[i, 1]] {i, 3}]

Out[20}= {O,

0,

/. variableRule,

0}

The right hand sides are zero for all equations, anyway.

o

Converting Lists into Parameters

We might use lists and list manipulations to arrange the arguments of functions. The function Apply uses the elements of the list as the arguments-and not the list itself: In[21]:=

Apply [f, v2]

Out[21}= f [a[l],

a[2], a[3]]

Evaluating f for the argument v2 would be something else, of course: In[22}:=

f [v2]

Out[22}= f [ {a [1],

a [ 2],

a [3 ] } ]

There exists a short operator notation for Apply, too: v2

In[23}:=

f

Oulf2~=

f[a[l],

@@

a[2],

a[3]]

Remember that a single @ stands for the prefix notation of a function operating on its argument, and is equivalent to In[22]:= (see Table 1-6 on page 23).

We can use Apply to calculate the sum or the product of the elements of a list. In[24}:=

Plus

Out[24}= a [ 1]

@@

v2

+ a [ 2]

+ a [3 ]

147

1.6 Lists In{25}:=

Times

Out{25}= a [ 1)

v2

@@

a [ 2) a [ 3 )

Of course, Mathematica also has built-in functions to do that. In{26}:=

Sum[a[i],

Out{26}= a [1) In{27}:=

+ a [3)

+ a[2)

{i, 3}]

Product[a[i],

Out{27}= a[l)

0

{i, 3}]

a[2) a [3)

Summary Short Form

Expression

Meaning

Function [x, body) Function [ {XI' x2'

a pure function with the formal parameter x

... },

a pure function with several formal parameters XI, x2' ...

body)

Function [body)

a pure function whose formal parameter is denoted by # (or #1, #2, ... )

body&

Table 1-67: Pure functions Expression

Short Form Meaning

Map [j, expr)

I

/@

expr

apply Ito the elements on the levellevelspec (see Table 2-4 on page 232)

Map [j, expr, levelspecl

I

MapAll [j, expr) MapAt [j, expr,

MapThread [j, {bl' b 2 ,

//@

expr apply Ito each subexpression of expr

n)

apply Ito the element at position n (n can be a list, to define a position in a nested expression)

{{ai' a2' ... },

... },

apply Ito each element of the top level of expr

{f[al' b l , ... ), j[ a2' b 2 , ... ), ... }

... } )

Apply[j, list)

I

@@

list

use the elements of list as the arguments

Apply[j, expr)

I

@@

expr

replace the head of expr by I

ofl

Table 1-68: Mapping and applying functions

148

1. Basics

Short Form Meaning

Expression Apply[j, expr, leve/spec]

replace the head of expr at the position leve/spec by I (see Chapter 2.1)

Thread [j[args]]

"thread" lover lists which appear in args

Operate [p, I[x, y]]

p

Through [p [II'

h]

[fl

[x, y]

P [jl [x],

[x]]

h

[x] ]

Table 1-68: Mapping and applying functions Expression

Meaning

Sum [expr, range]

a sum (the index ranges are analogous to Table, see Table 1-63 on page 141)

Product [expr, range]

a product (the index ranges are analogous to Table)

Table 1-69: Sums and products Expression

Meaning

Variables [poly]

show the variables appearing in a polynomial

Table 1-70: Variables of polynomials

o

Exercises

1. Generate a numerical table of the natural logarithms of the integers from 1 to 10. Find another way of doing the same. 2. Use a pure function to calculate the list of the derivatives of

with respect to x, y, and z. 3. Find at least three ways of calculating the sum of the squares of the integers from 1 to 10000. Compare the (CPU) timings of the different variants.



1.6.3 List Manipulation: The Cross Product

We now get to know many functions for the manipulation of lists. They will be important for our work with graphics objects in Chapter 1.7.

1.6 Lists

o

149

Parts of Lists

Let us consider the following list (we do not need to be bothered by the warning): In{1]:=

aList = Table [Exp[i], {i, 5}];

General::spelll: possible spelling error: new symbol name "aList" is similar to existing symbol "List".

As we have seen in Section 1.4.1, we can extract its second element by writing aList [ [2] ]. In Mathematica's full notation (see Chapter 2.1), this is written as: In[2}:=

Part [aList, 2]

Out[2}=

E2

We can also number the elements from the right-hand side In[3}:=

aList [[-3]]

Out[3}=

E3

or generate a sublist of successive elements: In[4}:=

aList[[Range[3]]]

ouq~=

{E, E2, E3}

An alternative would use Take. This function returns a sequence of elements. In[5}:=

Take [aList, 3]

Out[5}=

{E, E2, E3}

The fastest way of throwing away the first element is Res t. In[6}:=

Rest [aList]

Ouq~=

{E 2 , E 3 , E 4 , E5}

Drop drops elements, for instance the sequence from number 2 through 4:

150

1. Basics

In[7]:=

Drop [aList, {2, 4}]

Out[7)=

{E, E5}

Elements of nested lists are identified by giving their position on the different levels. In[B):=

Array [a, {2, 2}]

Out[B)=

{ {a [ 1, 1],

In[9):=

% [ [2, 1]]

Out[9)=

a [ 2, 1]

o

a [ 1,

2]},

{ a [2, 1], a [2, 2]}}

Changing Lists

The function Append (or Prepend) adds new elements at the end (or at the beginning) of a list. In[10):=

Append [aList, Exp[6]]

Ouq1~= {E, E2, E 3 , E4, E 5 , E6} In[11):=

Prepend [aLi s t , Exp [ 0] ]

Out[11)= {1,

2

3

4

5

E, E , E , E , E }

We can use Insert to add an element at a selected position within the list. In[12):=

Insert [aList, Exp[S/2], 3]

OutI'T'I 12J=

{

E, E 2 , E 5/2 , E 3 , E4,

E5 }

Delete, of course, deletes an element (or several elements, if several positions are given as a list). In[13):=

Delete [%, 3]

Ouq1~=

{E, E 2 , E 3 , E 4 , E5}

The function ReplacePart replaces elements. In[14):=

ReplacePart[aList, Exp[3.], 3]

Ouq1~=

2 4 5 {E, E , 20.0855, E , E }

151

1.6 Lists

o

Joining Lists

Two or more lists can be combined into a single list with Join. In{15}:=

Join[aList,

Out{15}= {E,

{a, b, e}]

E 2 , E 3 , E4, E 5 , a, b, c}

Join can serve as a nice example for the infix notation (see Table 1-6 on page 23). In{16}:=

{a, b, e} - Join - aList

Out{16}= {a,

b,

c, E, E 2 ,

The functions Union, Intersection, and Complement operate on lists by interpreting them as sets. In{17}:=

Union[{a, b, e},

Oulf1~=

{a, b, c, d}

In{18}:=

Interseetion[{a, b, e}, {b, e, d}]

Out{18}= {b, In{19}:=

c}

Complement [{a, b, e},

Out{19}= {a,

o

{b, e, d}]

{b}]

c}

Rearranging Lists

List can easily be sorted with the help of Sort. In{20}:=

Sort [ { f, b, g, e, 1, f}]

OUlf20= {l,

b,

e,

f,

f,

g}

We can use Union delete multiple occurrences of elements. In{21}:=

Union [%]

Out{21}= {1,

b, e , f,

g}

Reverse reverses the order of the elements. In{22}:=

Reverse [aList]

Oulf2~= {E 5 , E 4 , E 3 , E2, E}

152

1. Basics Finally, lists can be cyclically pennuted.

In{23]:=

RotateRight [aList]

Oulf2~= {E 5 , E, E2, E 3 , E4} In[24]:=

RotateLeft [aList, 3]

Oulf2~=

4 5 2 3 {E , E , E, E , E }

o

Example: The Cross Product

Let us now use our new knowledge to define a function cross, which calculates the cross product of two three-dimensional vectors. It does not concern us that such a function (Cross) already is implemented in the standard package LinearAlgebra' CrossProduct'; our version will be faster. A first version surely will use the well-known fonnula: In[25]:=

:=

crossNaive [u_, v_] {

u[[211 v[[3]] u[[311 v[[lll u[[lll v[[2]]

- u[[3]] v[[2]L - u[[lll v[[3]L - u[[211 v[[l]]

}

In[26]:=

u

In[27}:=

crossNaive [u, v]

{xl, yl,

OUlf2n= {-(y2 zl)

zl}; v

+ y1 z2,

{x2, y2,

z2};

x2 zl - xl z2, -(x2 y1) + xl y2}

What happens if we apply it to something other than a three-dimensional vector? In[28}:=

crossNaive [a, b] Part: : partd: Part specification a[[2]] is longer than depth of object. Part: : partd : Part specification b[[3]] is longer than depth of object. Part: : partd : Part specification a[[3]] is longer than depth of object.

153

1.6 Lists General: :stop: Further output of Part::partd will be suppressed during this calculation. Out[28}= {- (a [ [3 ]]

b [ [2] ]) + a [ [2 ]] b [ [3 ] ] ,

a[[3]] b[[l]] - a[[l]] b[[3]], -(a[[2]] b[[l]]) + a[[l]] b[[2]]}

Such error messages do not make sense for a user who has not written the function himself or herself. Therefore, we have to assure that the function does not evaluate for incorrect input. This can be achieved by adding a I; and a condition, in the form of a logical expression, to the definition. Then, the definition only transforms expressions for which the condition returns True. As a starting point for the condition, we use VectorQ. It returns True for vectors, and otherwise False. In[29}:=

VectorQ [Sin [x] ]

Out[29}= False In[30}:=

VectorQ [{a, b}]

Out[30}= True

The second part of the condition shall assure the length of three. This can be written as an equation. With these conditions, the vector product looks like this: In[31}=

crossFormula [u_, v _] : = {u[[2]] v[[3]] - u[[3]] v[[2]], u[[3]] v[[l]] - u[[l]] v[[3]]' u[[l]] v[[2]] - u[[2]] v[[l]]} I; VectorQ[u] && VectorQ[v] && Length[u] 3 && Length[v] 3

==

==

It now handles incorrect input by doing nothing. In[32}:=

crossFormula [a, b]

Oulf3~=

crossFormula[a, b]

The cross product contains cyclical permutations: The first term of each component consists of the product of a component of the first vector with the (cyclically) next component of the second vector. Such "shifts" are implemented very efficiently in the functions RotateRight and RotateLeft. The following combination of rotations does exactly what we need:

154

1. Basics

In{33}:=

RotateLeft [u RotateLeft [v] - RotateLeft [u] v]

Ouq3~=

{-(y2 zl) + y1 z2, x2 zl - xl z2, -(x2 y1) + xl y2}

Let us therefore define: In{34}:=

cross [u_ I v _] .RotateLeft[u RotateLeft[v] - RotateLeft[u] v] I; VectorQ[u] && VectorQ[v] && Length[u] == 3 && Length[v] == 3

This slightly speeds up the calculation. {20}]; II Timing

In{35}:=

Table [crossFormula[u , v],

Ouq3~=

{O.25 Second, Null}

In{36]:=

Table[cross[u , v], {20}]; II Timing

Ouq3~=

{O.2 Second, Null}

It is remarkable that the function Cross from the package LinearAlgebra' CrossProduct' is clearly slower than both of our versions. In{37}:=

«LinearAlgebra' CrossProduct'

In{38]:=

Table [Cross [u , v]

Ouq3~=

{O.516667 Second, Null}

I

{20}]; I I Timing

An even faster implementation has been pointed out to me by Leszek Sczaniecki from Wolfram Research. It does not use any list manipulation, but identifies the terms by appropriate list patterns (see Chapter 2.2): In[39}:=

crossFast [{ul_ I u2_ I u3_} ?VectorQ, {vi_I v2_1 v3_}?VectorQ] := {u2 v3 - u3 v2, u3 vi - ul v3 , ul v2 - u2 vi}

In[40}:=

crossFast [u , v]

OUlf40= {-(y2 zl) In[41}:=

+ y1 z2,

x2 zl - xl z2, -(x2 y1) + xl y2}

Table [crossFast [u , v]

Out{41}= {O.116667 Second,

I

Null}

{20}]; I I Timing

155

1.6 Lists

o

Efficiency of List Manipulations

It is a good habit to create lists all at once, wherever possible. This can be drastically faster then appending or prepending elements. For example, we use Table [a, {50 O}] to create a list containing 500 equal elements a. Let us look at the timing only. {SOO}]; II Timing

In[421:=

direct = Table[a,

Ou~4~=

{O.0166667 Second, Null}

The same list could also be produced by starting with an empty list and appending the elements. We use a Do loop (see Section 2.4.3) in the following way: In[431:=

appended = {};

In[441:=

Do [appended = Append [appended, a],

{SOO}]; II Timing

Out[441= {2.16667 Second, Null}

The resulting lists are the same: In[451:=

Shallow [ {appended, direct}]

Out[4511lShallow=

{{a, a, a, a, a, a, a, a, a, a, «490»}, {a, a, a, a, a, a, a, a, a, a, «490»}}

The difference in the timings results from the (internal) need to manipulate the data structure of the list for each new element.

o

Summary

• Append, Prepend, etc. should only be used when necessary. It is more effi-

cient to create a list with full length in one step. Expression

Meaning

exprl I; expr2

only evaluate exprl if expr2 returns True

Table 1-71: Conditions for the evaluation Expression

Meaning

First [list]

the first element of list

Last [list]

the last element

Table 1-72: Working with lists

156

1. Basics

Expression

Meaning

Part [list, n) or list [ [n) )

the nth element

Part [list, -n) or list [ [ -n) )

the nth element from the right

Part [list, {n! ' n2' ... }) or list[[{n!, n2' ... }))

a list of the selected elements, e.g., list[ [ Range [n, m) ))

Part [list, n! ' n2' list [ [n!, n2' ... ) )

... ) or

Take [list, n)

an element in a nested list the list of the first n elements

Take [list,

-n)

the list of the last n elements

Take [list,

{m, n})

the elements m through n

Rest [list)

drop the first element

Drop [list, n)

drop the first n elements

Drop [list,

-n)

drop the last n elements

Drop [list,

{m, n})

drop the elements m through n

Append [list, element)

append an element (at the end of the list)

Prep end [list, element)

prepend an element (at the beginning of the list)

Insert [list, element, n)

insert an element at the position n

Insert [list, element,

-n)

insert an element at the position n (from the right)

Delete [list, n) etc.

delete the element at position n

ReplacePart [list, new, n)

replace the nth element by new

ReplacePart [list, new, {n! ' n2, ... } )

replace the element at the position {n!, n2' ... } of a nested list

Join [list!, list2)

join two (or more) lists

Union [list!, list2)

give the sorted list of all distinct elements of the given lists

Intersection [list!, list2)

give the sorted list of all elements common to the given lists

Complement [universal,

give the elements of universal, which do not appear in the given lists; the result is sorted

Sort [list)

put a list into standard order

list! ' ... )

Table 1-72: Working with lists

1.6 Lists

157

Expression

Meaning

Sort [list, sortfct]

sort according to a given sort function sortfct (it must have two arguments and give True, if the arguments are sorted; default: OrderedQ [ {#1, #2}] &)

Reverse [list]

reverse the order of the elements

RotateRight [list]

cycle a list by one position to the right

RotateRight [list, n]

cycle a list by n positions to the right

RotateLeft [list]

cycle a list by one position to the left

RotateLeft [list, n]

cycle a list by n positions to the left

Length [expr]

the number of elements of expr

Flatten [list]

flatten a nested list, i.e., remove the inner braces

Flatten [list, n]

flatten to level n

Parti tion [list, n]

partition a list into non-overlapping sublists of length n

Parti tion [list, n, d]

generate sublists with offset d

Table 1-72: Working with lists Expression

Meaning

VectorQ [expr]

return True if expr is a vector, and otherwise False

Table 1-73: A test for vectors

o

Exercises

1. Use t = Table[i+j, {i, lO},

{j, Random [Integer,

{l,

lOll}];

to create a nested list with sublists of different length. Find an elegant way to construct a list containing the different lengths of the sublists. 2. Cycle each of the elements of t (see Exercise 1) by two positions to the right. We are looking for an elegant solution with a pure function. 3. Consider the mapping f:Rn ~ Rm. It shall be given by the coordinate functions fi (Xl' ... , Xn) , i = 1, ... , m. Define a Mathematica function which calculates the Jacobian off,

158

1. Basics

[~~;J ~ (i

1, "" m; j

~

1, "'. n)

at a given point. Assure that only correct input is accepted. After having developed your own solution, compare it to the version shown in the next chapter.



1.6.4 Vectors, Matrices, Tensors: The Jacobian

In mathematical applications, lists are used to define vectors, matrices, and tensors. We now learn how problems of linear algebra can be solved in this way.

o

Predefined Matrices and Matrix-Functions

Identity matrices and diagonal matrices are easy to produce: In{1]:=

id = IdentityMatrix[3]

Out[1]=

{ {1,

In[2]:=

diag = DiagonalMatrix [{a, b, c}]

Out[2]=

{ {a,

0,

O},

0,

O},

{O,

1,

{ 0, b ,

O},

0 },

{O,

{ 0,

0,

0,

1}}

c} }

Of course, the usual matrix functions (determinant, transpositIOn, inversion, matrix power, and matrix exponential) are built-in, as well. In[3]:=

m = {{a, b}'

{c, d} }

Out[3]=

{ {a, b}'

d} }

In[4]:=

Det[m]

Out[4]=

-(b

In[5]:=

Transpose[m]

Out[5]=

{ {a, c} , {b, d} }

In[6]:=

Inverse[m]

Out[6]=

{{=(S-c)-+-a-a' -(=(S-c)-+-a-a)}'

c)

{c,

+ a d

d

{-(-----~------)

b

-----~------}}

-(b c) + a d ' -(b c) + a d

159

1.6 Lists In[?]:=

MatrixPower [m, 2]

Out[?]=

{{a 2 + b c, a b + b d},

In[S]:=

MatrixExp[{{a, b}, {b, a}}]

Out[S]=

{{--2---

Ea - b

+

_Ea - b

{---2---

o

Ea + b

--2---

+

Ea + b

--2---

{a c + c

_Ea - b

---2---

+

Ea - b

--2---

+

Example: Scaled Plots of Data

The function Transpose is very useful for general list manipulations, as well. Sooner or later, the reader will need to convert two lists of equal length into a list of pairs of corresponding elements. For instance, this problem arises when we have a single list of experimental data, and we want to create a plot which has a correct scale on the horizontal axis-see Section 1.5.5. Let us illustrate this by reading our data points and creating a list of the corresponding "time values". In[9]:=

(expData = ReadList["raw-data-file.m", Real]) II Short

Out[9]//Short=

{0.0796992079824443964, «59», In[10]:=

(timeValues = Range[O, 6,

-0.23067«10»5809}

.1]) II Short

Out[10]//Short=

{O,

0.1,

0.2,

0.3,

0.4,

0.5, «52», 5.8, 5.9, 6.}

We now have two lists of equal length. For a plot with ListPlot, we have to calculate a list of pairs of corresponding "time" and data values. The solution is very simple: We combine the two lists into a nested list (which is a 2xn matrix) and transpose it (to get the nx2 matrix). In[11]:=

Transpose [{timeValues, expData}] I I Short

Out[11 ]//Short {{a,

0.0796992079824443964}, «59»,

{6., -0«19»9}}

With this list, ListPlot gives the correct scaling on the "time" axis (compare to Out[6]= on page 132).

160

1. Basics

In[12]:=

ListPlot [%]

..

1

.. ... .. .. ..

0.5

1

.. .. 3 •

2

5

4

6

'.

-0.5

... ... .' .. .. .'

-1

Out[12]= -Graphics-

o

Products: The Jacobian

We have already seen that the multiplication of a list (representing a vector or matrix) with a scalar is done automatically. In[13]:=

a Array[x, 3]

Oulf1~=

{a x[l],

a x[2],

a x[3]}

The product of two lists is evaluated by multiplying the corresponding elements. If we want the matrix product, we have to use the . operator. In[14]:=

diag . Array [x,

{3, 3}]

Out[14]= {{a x[l,

1], a x[l, 2], a x[l, 3] L {b x[2, 1], b x[2, 2], b x[2, 3]L {c x[3, 1], c x[3, 2], c x[3, 3]}}

Mathematica sums the last index of the first argument with the first index of the second. There is no need to differentiate between column vectors and row vectors. Thus, the scalar product of two vectors can be written as the matrix product of the two lists. In[15]:=

Array [x,

Oulf1~=

x[l] y[l]

3]

. Array [y I

+ x[2] y[2]

3] + x[3] y[3]

The function Outer defines an outer product. For instance, it creates the matrix--or tensor--of all products of the elements of two vectors.

161

1.6 Lists In[16}:=

Outer [Times, Array [x, 2], Array [y, 2]]

Out[16}IIMatrixForm= x[l] y[l] x[2] y[l]

x[l] x[2]

I I MatrixForm

y[2] y[2]

It is an interesting feature of Ou ter that generalized products can be used instead of Times. In[17}:=

Outer[f, Array [x, 2], Array[y, 2]]

Out[17}IIMatrixForm= f[x[l], y[l]] f[x[21, y[l]]

f[x[l1, f[x[2],

II MatrixForm

y[2]] y[2]]

We use this to calculate the Jacobian of a mappipg (see Exercise 3 on page 157). A complicated implementation might look like this: In[18}:=

In[19}:=

jaci[f_, var_, point_] := (Table[D[f[ [i]], var[ [j]]], {i, Length[f]}, {j, Length [var] }] I. Table[var[[k]] -> point[[k]], {k, Length[var]}]) Length [var] == Length [point] jaci[{x y, x + y},

Out[19}= {{ 2,

l},

{1,

{x, y},

{l,

I;

2}]

l}}

By mapping a suitable pure function (with Map or /@, see Table 1-68), we get a simpler version: In[20}:=

In[21}:=

j ac2 [f_, var_, point_] : = (D[f, #]& /@ var /. Table[var[[k]] -> point[[k]], Length [var] == Length [point] jac2[{x y, x + y},

Out[21}= {{ 2,

l},

{l,

{x, y},

{k, Length[var]}])

/;

{i, 2}]

l}}

The table can be constructed even more elegantly, by taking the outer product of the functions with the variables, and by using the differential operator D as the "product" .

162

1. Basics

In[22]:=

In[23]:=

j ae3 [C, var_, point_] : = (Outer[D, f, var] /. Table [var [[k]] -> point [ [k] ], Length [var] == Length[point] jae3[{x y, x + y},

Out[23]= {{ 2,

1L

{x, y},

{k, Length [var] }]) /;

{l, 2}]

{ 1, 1 } }

Let us simplify the table of the rules as well. Unfortunately, it cannot be written in the form var -> point. In[24]:=

jae4[C, var_, point_] .(Outer[D, f, var] /. var -> point) /; Length [var] == Length[point]

In[25]:=

jae4[{x y, x + y},

Out[25]= {{ y,

x},

{1,

{x, y},

{l, 2}]

1}}

No rules were used here, because, according to the syntax of rules, pairs {x, y} would have to be replaced. But this pair does not appear in the result of the outer product. How can we convert a rule for lists into a list of rules? This is done by the function Thread, which "threads" functions over lists in the arguments in the following way: In[26]:=

Thread[f[{a, b},

{e, d}]]

Oulf2~=

{f[a, c], f[b, d]}

In our case, f corresponds to the function Rule (in its full notation, see Table 2-13 on page 254). Thus, Thread does exactly what we need. In[27]:=

Thread [{x, y} - > {l, 2}]

Oulf2~=

{x -> 1, y -> 2}

With this, the function for the Jacobian can finally be defined as: In[28]:=

In[29]:=

j ae [f_, var_, point_] : = (Outer[D, f, var] /. Thread[var -> point]) Length [var] == Length[point] jae[{x y, x + y},

Out[29]= {{ 2,

1L

{ 1, 1}}

{x, y},

{l,

2}]

/;

163

1.6 Lists

This example shows the extraordinary compactness and elegance possible in Mathematica programs.

o

Summary Expression

Meaning

c m c * m

the (element-wise) multiplication, e.g., with a scalar

a

b

the matrix product

Outer [I, t1 ' t2' ... ]

the generalized outer product of tensors, with "multiplication" i

Inner [j, tl ' f2' g]

the generalized inner product, with "multiplication" i and "addition" g

Table 1-74: Products Expression

Meaning

IdentityMatrix[n]

the identity matrix of dimension n

DiagonalMa tr ix [list]

the diagonal matrix with the given diagonal elements list

Inverse[m]

the inverse matrix

MatrixPower[m, n]

the nth power of a matrix m

MatrixExp[m]

the exponential function of a matrix: =

mi

Ll 0

i =

l.

Det[m]

the determinant of a matrix

Transpose[m]

the transposed matrix

Transpose [list,

{nl'

n2,

... } ]

transposition, such that the kth level of list becomes the nkth level of the result

Table 1-75: Matrix operations Expression

Meaning

Thread[j[args]]

"thread" i over lists which appear in args

Thread [j[args] , h]

thread i over objects with head h, which appear in args

Table 1-76: Threading functions over lists

164

o

1. Basics

Exercises

1. Calculate the inverse of a general (indexed) matrix of dimensions 4x4. 2. Define a function which linearizes mappings from R n in R m .



1.6.5 Eigenvectors and Eigenvalues: An Oscillator

Eigenvalue problems can be solved directly with the built-in functions Eigenvalues and Eigenvectors, or Eigensystem.

Figure 1-12: An oscillator conSisting of three connected masses

Let us look at an example: Figure 1-12 shows an oscillator with three masses, which are bound to a horizontal plane. The masses mI' m2, and m3 are connected with (massless) springs, such that they form an equilateral triangle at rest. A fixed frame holds the other ends of the springs. To make things a little easier, we assume that all springs have the same spring constantJ(force =J* elongation of the spring). We want to find the normal modes of this system.

165

1.6 Lists

To solve this problem, we have to derive the linearized equations of motion (around the equilibrium position). This is quite simple, if we already linearize during the derivation of the equations (i.e., set sine and tangent functions of small angles equal to the angle and cosine functions equal to one). We denote the horizontal and the vertical displacements of the mass m i by xi and Yi (see Figure 1-13). For the mass m 1 ' we get the x-component of the equation of motion as

The right-hand side of this equation can be constructed as follows: Imagine each mass is displaced in the x- and the y-direction separately, and independently of the other masses-linearization makes this assumption correct. This changes the lengths of the springs and results in a force on the first mass. We must calculated the x-component of this force.

Figure 1-13: The choice of coordinates

If, for instance, the mass m3 is displaced by x3, then the spring between ml and m3 is shortened by x3

x cos60° = 3 2

166

1. Basics

(plus corrections of higher order). This gives a force

in the direction of the spring. The projection of the force onto the x-direction becomes

Because of our linearization, all such terms can be added. This yields the result (1.9).

Equation (1.9) can be simplified to mIx I

= f(-~XI+~(X2+X3)

+J}(-Y2+ Y3))'

(1.10)

By an analogous calculation, the y-component turns out to be

thus (1.11) Similarly, we get the equations of motion for the other masses: (1.12)

(1.13) (1.14) (1.15) We now combine the coordinates into a single vector.

167

1.6 Lists

Xl YI Z

X2

=

Y2 X3 Y3

This allows us to write the equations (1.10) through (1.15) in matrix form:

mZ·+ cZ =

o.

(1.16)

The symbol m in Equation (1.16) stands for the mass matrix ml 0

m=

and c for the stiffness matrix

0

0

0

0

0 ml 0

0

0

0

0

0 m2 0

0

0

0

0

0 m2 0

0

0

0

0

0 m3 0

0

0

0

0

o

m3

168

1. Basics

c

=f

1 4

J3

1 4

J3

5 2

J3

3 4

J3

3 4

1 4

J3

94

J3

-1

0

J3

3 4

J3 4

7 4

0

0

1 4

J3

-1

0

9 4

J3

J3

3 4

0

0

J3

7 4

1 2

0

0 --

4

4

4

4

4

4

4

4

4

4

4

A normal mode of the system is a solution of the equations of motion (1.16), for which all masses oscillate with the same frequency. We find the normal modes with an "ansatz" Z

(t)

=

(sin cot) z.

(1.17)

The frequencies co and the eigenvectors z result from substituting Equation (1.17) into Equation (1.16). This gives the matrix equation

( -co 2 m + c) z

=0

or (1.18) The symbol 1 denotes the identity matrix.

Therefore, we have to solve the eigenvalue problem for the matrix m-1c. That means, we have to solve Equation (1.18) for co2 and z. The eigenvalues co2 are the squares of the frequencies. In Mathematica, the problem can be solved as follows: In[1}:=

m

DiagonalMatrix [{m1, m1, m2, m2, m3, m3}];

In[2]:=

c = f* {1/2, 0, -1/4, Sqrt[3]/4, -1/4, -Sqrt[3]/4}, {O, 5/2, Sqrt [3] 14, -3/4, -Sqrt [3] 14, -3/4}, {-1/4, Sqrt[3]/4, 9/4, -Sqrt[3]/4, -1, O}, {Sqrt [3] 14 , - 3 14, - Sqrt [3 ] 14 , 7/4, 0, O},

169

1.6 Lists { -1 I 4, - Sqrt [3] 14, -1, 0, 9 14, Sqrt [3] 14} , { - Sqrt [3 ] 14 , - 3 14 , 0 , 0 , Sqrt [ 3 ] 14, 7 14 } } ;

The matrix c should be symmetric. Let us check for typing errors: In[3}:=

II MatrixForm

c - Transpose[c]

Out[3}IIMatrixForm=

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

We now try to calculate the eigenvalues. In[4}:=

Eigenvalues [Inverse [m] . c] ;

Eigenvalues::eival: Unable to find all roots of the characteristic polynomial. We cannot solve this eigenvalue problem in terms of radicals, because the roots of a polynomial of degree six have to be calculated. In[5}:= Out[5}=

Det[Inverse[m].c -

~

IdentityMatrix[6]]

(80 f6 - 364 ~ f5 m1 + 176 ~2 f4 m1 2 - 124 ~ f5 m2 + 480 ~2 f4 m1 m2 - 212 ~3 f3 m1 2 m2 + 47 ~2 f4 m2 2 _ 152 /13 f3 m1 m2 2 + 60 /1 4 f2 m1 2 m22 - 124 /1 f5 m3 + 480 ~2 f4 m1 m3 - 212 ~3 f3 m1 2 m3 + 182 ~2 f4 m2 m3 - 596 /13 f3 m1 m2 m3 + 240 ~4 f2 m1 2 m2 m3 - 64 /13 f3 m2 2 m3 + 176 ~4 f2 m1 m2 2 m3 - 64 ~5 f m12 m2 2 m3 + 47 /1 2 f4 m3 2 _ 152 ~3 f3 m1 m3 2 + 60 ~4 f2 m12 m3 2 - 64 ~3 f3 m2 m3 2 + 176 ~4 f2 m1 m2 m3 2 - 64 ~5 f m1 2 m2 m3 2 + 20 ~4 f2 m2 2 m3 2 _ 48 ~5 f m1 m2 2 m3 2 + 16 ~6 m1 2 m2 2 m3 2 ) /

(16 m1 2 m2 2 m3 2 )

Therefore, we use numerical values for the parameters, for instance the following:

170

1. Basics

In[61:=

numerical Values = {f -> 1., m1 -> 1., m2 -> 1.5, m3 -> 2.};

We now get the eigenvalues and the eigenvectors very quickly. In[71:=

Eigenvalues [Inverse [m].c /. numericalValues]

Oulfn=

{3.10492, 1.6949, 1.44863, 0.669099, 0.551711, 0.197413}

In[B}:=

Eigenvectors [Inverse [m] . c /. numerical Values]

Oulf~=

{{0.0283427, -0.882828, -0.288206, 0.274883, 0.185433, 0.163715}' {0.146934, 0.488161, -0.753235, 0.0298654, 0.38192, -0.161221}, {0.570044, 0.0197214, -0.0559514, 0.605934, -0.40066, -0.37927}, {0.126225, -0.457007, -0.249373, -0.677152, -0.247037, -0.439843}, {-0.046118, 0.164528, -0.514462, -0.08608, -0.611743, 0.569643}, {-0.919173, -0.00894456, -0.136953, 0.228356, -0.140551, -0.25374}}

The result can be printed more clearly by using less digits. In[9}:=

N [%, 2] / / MatrixForm

Out[911IMatrixForm=

0.028 0.15 0.57 0.13 -0.046 -0.92

-0.88 0.49 0.02 -0.46 0.16 -0.0089

-0.29 -0.75 -0.056 -0.25 -0.51 -0.14

0.27 0.03 0.61 -0.68 -0.086 0.23

0.19 0.38 -0.4 -0.25 -0.61 -0.14

0.16 -0.16 -0.38 -0.44 0.57 -0.25

The system oscillates "in time", if the initial conditions are chosen as a multiple of these six displacement (row) vectors. The corresponding frequency is the corresponding eigenvalue. Each general small oscillation is a superposition of these normal modes. Unfortunately, these lists of numbers do not give a good impression of how the modes look like. This motivates us to learn more about Mathematica graphics, such that we can visualize the movement of the system with an animation. To finish, we save the two matrices and the chosen values of the parameters for later use. In[10}:=

Save["oscillator.m", m, c, numericalValues]

171

1.6 Lists

o

Summary Expression

Meaning

Eigenvalues[m]

the eigenvalues of a matrix

Eigenvalues[N[m]]

the numerical values of the eigenvalues

Eigenvectors[m]

the eigenvectors of a matrix

Eigenvectors[N[m]]

the numerical values of the eigenvectors

Eigensystern[m]

the eigenvalues and the corresponding eigenvectors, combined as lists

Table 1-77: Eigenvalues and eigenvectors

o

Exercises

1. Calculate the eigenvalues and the eigenvectors of the above oscillator in one step, with different choices of masses. 2. Calculate the normal modes of the linearized triple pendulum from Section 1.5.2. Compare the solutions of the linearized and the nonlinear system for initial conditions corresponding to the normal modes; choose initial vectors with "large" and "small" magnitudes.

172

1. Basics

• 1.7 Graphics Programming We now talk about Mathematica as a programming language for graphics. This means that we can use our tool not only for plots of functions or data, but also for general graphics, consisting of lines, circles, etc. As examples, we will visualize the movements of the triple pendulum (from Section 1.5.2) and of the oscillator (from Section 1.6.5). These features can also be used to add text and pictures to function plots in a flexible way, wherever the basic options do not suffice .



1.7.1 The Structure of Graphics

Let us have a quick look "inside" Mathematica, to see how graphics objects are represented. We consider the following simple picture: In[1]:=

ListPlot[{{O,

A},

{.S,

.S}'

{l,

l}}]

1

0.8 0.6

0.4 0.2

0.2

Out[1]=

0.4

0.6

0.8

1

-Graphics-

With the command InputForm, we get the explicit representation of the graphics. This works for any other M athematica output, as well. In[2]:=

Short [InputForm [%],

4]

Out[2}1IShort=

Graphics[{Point[{O, O}], Point[{O.5, O.5}], Point[{l, 1}]}, {PlotRange -> Automatic, AspectRatio -> GoldenRatio A (-l) , «19», PlotRegion -> Automatic}]

1.7 Graphics Programming

173

We see that the plots consists of a Graphics object, with a list of three points and a list of options as parameters. All graphics objects are built the same way: They consist of a head, which describes the type of the graphics (Graphics, Graphics3D, etc.), a list of graphics primitives and graphics directives, and options. The primitives are the basic elements (points, lines, etc.), the directives define properties (color, thickness, etc.). The possible graphics primitives in two dimensions are: Point, Line, Rectangle, Polygon, Circle, Disk, Raster, and Text; in three dimensions: Point, Line, Polygon, Cuboid, and Text (see Tables 1-80 and 1-81). Such a graphics object can be displayed with the Show command. The following expression defines and displays a hyper cube-the unfolding of a four-dimensional cube in three dimensions: In[3]:=

Show [Graphics3D[ Cuboid /@ {{O,O,O},{-l,O,O},{l,O,O},{2,O,O}, {O,l,O},{O,-l,O},{O,O,l},{O,O,-l}}]]

ouq~=

-Graphics3D-

Notice how the primitive Cuboid can elegantly be mapped (with Map or /@) onto the list of points (see Section 1.6.2).

The graphics primitives can be supplemented with graphics directives, wherever necessary (see Table 1-83). These directives must be written before the elements to which they should be applied. Groups of directives and primitives can be

174

1. Basics

combined into nested lists. In this case, each directive only applies to the succeeding elements and subsublists of the sublist in which the directive stands. In this way, we can construct the following picture: In[4]:=

Show [Graphics [ {

Line [ { { 0 , O}' {O, 1}, {1, 1}, {1, O} , {O, O} } ] , {GrayLevel[.4], Rectangle[{O, O}, {.2,

.2}]},

{

Dashing [ { . 1, • OS} ] , Circle[{.5,.5}, .3, {Pi/2,3Pi/2}], Thickness [ .02], Line [ { { .1, .9}, { .9, .1} } ] },

{PointSize [.1], Point [{. 5, . 5}] }, Text [ "large dot", {. 7 , • 5} ] , Text [FontForm[ "rectangle (\"Courier\",14)", {"Courier",14}], {.6,.05}] }]

, X

(

, -- ,

~l.rge e

Oulf~=

dor

( "Courier ", 14)

-Graphics-

Notice that, for instance, the Dashing directive applies to the half circle as well as to the line, whereas Thickness only applies to the line. The texts are centered at the given points. The \ in FontForm are necessary to create quotes within a string (see Section 2.6.7).

All such graphics can be supplemented with the options we know from Chapter 1.5. They change the appearance of the picture on the whole.

175

1.7 Graphics Programming In[5]:=

Show [%, AspectRatio -> 1, Axes -> True, Background -> GrayLevel[.9]

, V-

lr-------------------------------, 0.8

I' \ ~... ""

0.6

" ,,

0.4

rectangle ( " Courier ", 14) 0 .4 ouq~=

o

0.6

0.8

1

-Graphics-

Summary Expression

Meaning

InputForm [expr]

convert an expression into standard input form

FullGraphics [g]

a graphics object, where the options are replaced by their explicit representations

Table 1-78: Explicit representations of expressions and graphics Object

Meaning

Graphics [list]

general two-dimensional graphics

Graphics3D [list]

general three-dimensional graphics

DensityGraphics [list]

density graphics

ContourGraphics [list]

contour graphics

Table 1-79: Graphics objects

176

1. Basics

Object

Meaning

SurfaceGraphics [list]

simple three-dimensional surfaces

GraphicsArray [list]

an array of graphics

Table 1-79: Graphics objects Graphics Primitive

Meaning

Point [{x, y}]

a point

Line [{ {xl' Yl },

{x2'

... } ]

Y2},

a line through the given points

Rectangle [ {xmin' Ymin} , {xmax ' Ymax} ] Polygon [ { {Xl' Yl },

{x2'

Y2}, ... } ]

a filled polygon through the given points a circle with center at {x, y} and radius r

Circle [{x, y}, r] Circle [{x, y}, r,

{theta 1 ,

a circular arc

theta2} ]

Circle [{x, y}, {theta 1 ,

an elliptical arc

{rx ' ry} , theta2} ] , etc.

Disk[{x, y}, r] , etc.

a filled disk (analogous to Circle)

... }, ... }, ... } ]

an array of gray levels aU (between 0 and 1)

Raster [ { {all' a12' {a2l'

a22'

RasterArray [ { {gll' gl2 ' {g21'

g22'

Text [expr,

... }, ... } ]

{x,

a filled rectangle

... },

an array of cells colored according to the graphics directives gij

y}]

text, centered at the given point

Table 1-80: Graphics primitives in two dimensions Graphics Primitive

Meaning

Point [{x, Y, z}]

a point

Line [{ {xl' Yl' zl },

{x2'

Polygon [ { {xl' Yl' zl },

Y2' {x2'

Z2}, Y2'

... } ] z2},

a line

... } ]

a filled unit cube

Cuboid [ {xmin' Ymin' Zmin} ] Cuboid [ {xmin' Ymin' Zmin} , Text [expr,

{x,

Y,

z} ]

a filled polygon

{xmax '

Ymax '

Zmax} ]

a filled cuboid text, centered

Table 1-81: Graphics primitives in three dimensions

177

1.7 Graphics Programming

Expression

Meaning

FontForm[ "text", font]

formatted text;font is a list, consisting of a font and a size

Scaled [ {sx' Scaled [ {sX'

scaled coordinates (0 through 1 in all dimensions of the graphics); this is useful to give "absolute" positions

Sy} ]

sz} ]

Sy'

Table 1-82: More functions which are useful for graphics Graphics Directive

Meaning

Hue [h]

parameters between 0 and 1 are mapped onto the color spectrum-from red over yellow, green, blue, and back to red; other parameter values are treated cyclically

Hue [h, s, b]

colors in the hue-saturation-brightness model (Hue [h] corresponds to Hue [h, 1, 1])

RGBColor[ red, green, blue]

colors in the red-green-blue model; parameters outside the interval [0, 1] are truncated

GrayLevel [level]

gray-levels; values must be between 0 (black) and 1 (white)

PointSize[h]

the size of points, given as a fraction of the total width of the graph

AbsolutePointSize[h]

the absolute point size (in printer's points,

Thickness [h]

the line thickness, as a fraction of the total width of the graph

AbsoluteThickness[h]

the absolute line thickness (in printer's points)

Dashing [ {r\, r2,

... } ]

-:h. of an inch)

the lines are dashed, with successive segments of lengths r\, r2, ... (cyclically)

AbsoluteDashing[ {r\ ' r2, ... } ]

a dashed line with successive segments of absolute lengths

EdgeForm[ ]

do not draw the edges of polygons (three-dimensional)

EdgeForm[g]

the edges of polygons are drawn according to the graphics directive g (three-dimensional)

FaceForm [gfront, gback]

the front faces of (three-dimensional) polygons are drawn according to the graphics directive gfront, the back faces according to gback (the comers are specified counterclockwise, when viewed from the front face)

rl, r2, ...

Table 1-83: Graphics directives

178

1. Basics

o Exercises 1. Study the objects in the standard package Graphics' Polyhedra' . 2. Draw a dodecahedron with one face removed from it. 3. Draw the edges of the above dodecahedron red and thicker. 4. Create a three-dimensional picture of 100 points, which are randomly placed in a unit cube.



1.7.2 Example: Animation of the Triple Pendulum

It is now an almost trivial task to draw and animate the motion of the triple pendulum from Section 1.5.2. Let us assume, as a first step, that the positions of the pendulum are given by a list of the three angles. In[1]:=

angles = {.l, .2,

.25};

We will visualize the pendulum rods by three lines. Their end points can be calculated as follows (compare with Figure 1-7): In{2]:=

xl

Sin[angles[[l]]];

In{3]:=

yl

-

In{4]:=

x2

xl + Sin[angles[[2]]];

In{S]:=

y2

yl

In{6]:=

x3

x2 + Sin[angles[[3]]];

In{7]:=

y3

y2 - Cos[angles[[3]]];

Cos[angles[[l]]];

-

Cos[angles[[2]]];

We start the first line at the origin (the support of the topmost rod) and continue with the other two. The range of the graphics should be chosen such that all possible configurations, even the "standing" one, can be drawn. (The empty top part of the graphics is clipped in the print though, to save paper.)

1.7 Graphics Programming In[B]:=

Show [Graphics [Line [ {{O, OJ, {xl, y1}, {x2, y2}, {x3, y3}}]], AspectRatio -> Automatic, PlotRange -> {{-3, 3},{-3, 3}}]

Ouq~=

-Graphics-

179

Is is easier to differentiate between the rods, if we draw the lines in color and a little thicker. Most common colors are predefined in the package Graphics' Colors' . In[9]:=

«Graphics' Colors'

In[10]:=

Show [Graphics [ {

Thickness [.01] , {

{Red, Line[{{O, O}' {xl, y1}}]}, {Green, Line[{{x1, y1}, {x2, y2}}]}, {Blue, Line[{{x2, y2}, {x3, y3}}]} } },

AspectRatio -> Automatic, PlotRange -> {{-3, 3},{-3, 3}}]

Ouq10= -Graphics-

180

1. Basics

Let us now put together a function, which creates a Graphics object with these lines, for given angles. The calculation of sines and cosines takes time. It therefore makes sense to avoid multiple evaluations of such functions, and to calculate the end points in advance. All this can be combined in a single function by writing the necessary calculations in round parentheses. In[11]:=

pendulumLines [angles_]

:=

(

xl Sin[angles[[l]]]; y1 - Cos [angles [ [1.] ] ] ; x2 xl + Sin[angles[[2]]]; y2 y1 - Cos[angles[[2]]]; x3 x2 + Sin[angles[[3]]]; y3 y2 - Cos[angles[[3]]]; Graphics [

=

{

Thickness[.Ol], {

{Red, Line[{{O, A}, {xl, y1}}]}, {Green, Line[{{x1, y1}, {x2, y2}}]}, {Blue, Line [{{x2, y2}' {x3, y3}}]} } },

AspectRatio -> Automatic, PlotRange -> {{-3, 3},{-3, 3}}

We now clear the values of Xi and Yi' and test the function. In[12]:=

Clear [xl, y1, x2, y2, x3, y3]

In[13]:=

Show [pendulumLines [angles]]

Oulf1~=

-Graphics-

181

1.7 Graphics Programming

The drawing is done correctly. But our function has the inconvenient property of assigning values to the global symbols Xi and Yi: In[14]:=

xl

Out[14]= 0.0998334

This can be dangerous. It is best that we localize the variables with the Mathematica function Module. In[15]:=

pendulumLines [angles_] : = Module [ {xl, yl, x2, y2, x3, y3}, xl = Sin[angles[[l]]]; y1 - Cos[angles[[l]]]; x2 xl + Sin[angles[[2]]]; y2 y1 - Cos[angles[[2]]]; x3 x2 + Sin[angles[[3]]]; y3 y2 - Cos[angles[[3]]]; Graphics [ {

Thickness [.01] , {

{Red, Line[{{O, O}, {xl, y1}}]}, {Green, Line [{ {xl, y1}, {x2, y2}}]}, {Blue, Line[{{x2, y2}, {x3, y3}}]} } },

AspectRatio -> Automatic, PlotRange -> {{-3,3},{-3,3}} /; VectorQ[angles] && Length[angles]

==

3

The local variables have to be written as a list, which is passed as the first argument. The second argument, the body, is a sequence of expressions with the actual calculations. Note that the two arguments of Module are separated by a comma, whereas the second argument, the body, may contain several expressions, which are separated by semicolons. The result of the last expression of the body is returned as the result of the Module function (in our case, the Graphics object). The round parentheses (see In[11]:=) are not necessary in Module, because the expressions are already grouped-being the second argument.

182

1. Basics

This new version of pendul umLines no longer changes the values of the and the Yi' In[16j:=

Clear [xl, y1, x2, y2, x3, y3]

In[17j:=

pendulumLines [angles] ;

In[1Bj:=

xl

xi

Out[1Bj= xl

We now evaluate a more spectacular solution of the triple pendulum than the one from Section 1.5.2. We read the saved data from the file t rip 1 e Pen d u 1 urn. rn and integrate, for new initial conditions, over a range of lO time units. In[19j:=

«triplePendulum.m;

In[20j:=

initials = {phil [0] phil' [0]

In[21j:=

valueRule = {m -> 1, 1 -> 1, g -> 1};

In[22j:=

lagSolRule = NDSolve [Evaluate [ Flatten[{lagEquations, initials}] /. valueRule], angles, {t, 0, 10}];

==

3, phi2 [0] == 0, phi3 [0] == 0, 0, phi2' [0] == 0, phi3' [0] O};

The function pendulumLines is now used to generate the corresponding Graphics objects, in steps of .1 seconds. If only little memory is available, the reader should draw less pictures. In[23j:=

animationGraphics = Table[penduiumLines[angles /. lagSolRule[[l]]], {t, 0, 10, 11l0}];

These graphics can be animated with the command ShowAnimation from the standard package Graphics' Animation' or with Show /@ animationGraphics and the animation command Animate Selected Graphics ... of the notebook front end. In[24j:=

«Graphics' Animation'

In[25]:=

ShowAnimation [animationGraphics]

183

1.7 Graphics Programming

We do not print all the single pictures here, but for readers who cannot follow the calculations on their computer, 48 pictures (every second one), are printed as a GraphicsArray. In[26]:=

Show [GraphicsArray [Partition[ animationGraphics[[Range[l, 97, 2]]], 6]]]

The pictures are shown as Color Plate 3 on page II. Oulf2~=

-GraphicsArray-

Parti tion partitions the list into sublists, each containing the six elements of a row (see Table 1-72 on page 155).

o

Summary Expression

Short Form

CompoundExpression [exprj, expr2' ••• J

(exprj;

expr2;

Meaning

... ) a sequence of expressions

Table 1-84: Several expressions, grouped as a single expression Expression

Meaning

Module [{x, y, ... } , exprJ

a module with local variables x, y, ...

Module [{x = xO' Y = YO' ... } , exprJ

the local variables are initialized

Table 1-85: The localization of variables Package

Examples

Contents

Graphics'Colors'

Red, Green, Blue, Yellow, ...

color definitions

Table 1-86: A package with color definitions

o

Exercises

1. Animate the solutions of Exercise 3 on page 106. 2. Calculate and animate the motion of the triple pendulum for different initial conditions.

184



1. Basics

1.7.3 Example: The Oscillator

The normal modes of the oscillator from Section 1.6.5 (Figure 1-12) ask for a visualization, as well. Let us read the definitions for m, c, and numerical Values, and define a list for the values of the masses. In[1]:=

«oscillator.m

Out[1]=

{f -> 1., ml -> 1., m2

In[2]:=

masses: = {ml, m2, m3} /. numerical Values

-> 1. 5, m3 -> 2.}

We build our Graphics object in several steps. The masses shall be drawn as disks (filled circles). We will need them in the equilibrium position, as well as in the displaced positions. It therefore makes sense to define a function which takes the list of the positions of the masses (i.e., a list of the three points) as parameter. In[3]:=

massDisks [points_] : = Thread [Disk [points, .05 Sqrt[masses]]]

Note that the function Thread (see Table 1-76 on page 163) converts the list of points and the list of masses in the arguments of Disk into three Disk objects, each with a point and the scaled mass in its argument. We choose the area of the disk proportional to the mass. For the equilibrium position In[4]:=

equiPts

=

{{1/2, Sqrt[3]/2}, {l, O}, {O, O}};

we get the following picture:

185

1.7 Graphics Programming In[5]:=

Show [Graphics [massDisks [equiPts]], AspectRatio -> Automatic]

Oulf~=

-Graphics-





The rectangular frame is at rest; we can define a fixed expression for it. In[6]:=

box

=

Line[{ {-1, -1}, {2, -1}, {2, Sqrt[3]/2 + 1}, { -1 , Sqrt [3 ] 12 + 1}, { -1 , -1 } }];

The springs also have to be drawn. As a simplification, we represent them by straight lines. We have to implement this as a function, because the end points will be moving. In{7]:=

springLines [points_]

.-

{

Line[{{1/2, Sqrt[3]/2 + 1}, points[[l]]}], Line[{{1, -1}, points[[2]], {2, O}}]' Line[{{-l, O}, points[[3]], {O, -1}}], Line [Append [points, points[[l]]]]

For the equilibrium, we now have: In[8]:=

Show [Graphics [ {

box, massDisks[equiPts], springLines[equiPts]

186

1. Basics },

AspectRatio -> Automatic]

/\ Oulf~=

-Graphics-

Let us use colors, draw the springs dashed for the equilibrium position, and draw the frame thicker. Again, we use the definition from Graphics' Colors' . In{9]:=

Needs ["Graphics' Colors' "]

In{10]:=

Show [Graphics [ {

{Red, Thickness[.02], box}, {

Magenta, massDisks[equipts], {Dashing[{.OS, .OS}], springLines[equiPts]} },

AspectRatio -> Automatic]

187

1.7 Graphics Programming

I

I I

/ /

"

\

r---'I

I

Out[10]= -Graphics-

This is a nice picture for the equilibrium. We now have to recalculate the eigenvectors. In[11]:=

ev = Eigenvectors [Inverse [m].c /. numericalValues];

Each row (eigenvector) contains the x and y coordinates of the corresponding mode. We get the displaced positions for a mode by adding a scaled multiple of the eigenvector to the equilibrium position. Let us use the number of the mode and the scaling factor as parameters of our function: In[12]:=

oscPts [mode_, scale_] : = equiPts + scale Partition[ev[[mode]], 2]

We can now draw the displaced position for the first mode and a scaling of . 2. In[13]:=

dispPts = oscPts [1, .2];

In[14]:=

Show [Graphics [ {

{Red, Thickness[.02], box}, {

},

Magenta, massDisks[equiPts], {Dashing[{.OS, .OS}], springLines[equiPts]}

188

1. Basics {

Blue, massDisks[dispPts], springLines[dispPts] }

,

}

AspectRatio -> Automatic]

!

j ~

I

Ouq1~=

J.~~ \ ... I

-Graphics-

Everything is now combined into a function, which generates the desired Graphics object. In[15]:=

generateGraphics [mode_, scale_] : = Module[{dispPts = oscPts[mode, scale]}, Graphics [ {

{ Red, Thickness[.02], box }, {

Magenta, massDisks[equiPts], {Dashing[{.OS, .OS}], springLines[equiPts]} }, {

Blue, massDisks[dispPts], springLines[dispPts]

1.7 Graphics Programming

189

},

AspectRatio -> Automatic

By varying the scale with a sine function, we get the pictures for an animation. In[16}:=

animationGraphics [mode_] : = Table [generateGraphics [mode, 0.2 Sin[t]], {t, 0, 2pi - pilla, Pi/10}]

The first mode gives us the following pictures: In[17}:=

picts = animationGraphics [1] ;

Again, they can be animated with ShowAnimation. In[1B}:=

Needs ["Graphics' Animation' "]

In[19}:=

ShowAnimation [picts]

Books still have no built-in movie projector, but a GraphicsArray can give an idea of what happens. In[20}:=

Show[GraphicsArray[Partition[picts, 4]]]

The pictures are shown as Color Plate 4 on page III. OUlf20= -GraphicsArray-

o

Exercise

1. Animate the other normal modes of the oscillator.

190

1. Basics

• 1.8 More Selected Tools This chapter contains a compact overview of additional helpful tools in Mathematica. Some of the functions are built into the kernel, others are defined in standard packages. Since these packages contain hundreds of additional objects, we can cover only a small fraction of them. The choice has to be arbitrary. A more systematic documentation can be found in the "Guide to Standard Mathematica Packages" [BKM92]. The standard packages are organized by topics and located in different directories. Each of the directories contains a master file (e.g., Calculus' Master'). After loading this master (e.g., «Calculus'Master'), we can use all functions defined in the packages within the corresponding directory.



1.8.1 Graphics and Sound

o

Vector Fields

Vector fields corresponding to differential equations in two or three dimensions can give a good qualitative impression of the properties of the solutions. The packages Graphics' PlotField' and Graphics' PlotField3D' contain Mathematica functions which draw such vector fields. In[1]:=

«Graphics' PlotField'

In[2]:=

?Graphics' PlotField' *

ListPlotVectorField MaxArrowLength PlotGradientField PlotHamiltonianField In[3]:=

PlotPolyaField PlotVectorField ScaleFactor ScaleFunction

?PlotVectorField

PlotVectorField[f, {x, xO, xl, (xu)}, {y, yO, yl, (yu)}, (options)] produces a vector field plot of the two-dimensional vector function f.

We look at an example: In[4]:=

vf = PlotVectorField [ {-y + x A 2, x + Sin[y]}, {x, -2, 2},

{y, -2, 2}]

191

1.8 More Selected Tools

,

,

...

.

....

. .

......

... .

,

~

--, . ..

~

. .

, ....

, , , , " ,

,

... ...

,

........................

..... .... .... ... ......,.. ............................. ,

Out[4]=

,

,

I I /

I

/

.I /' /'

/'

,

... ...

........ ....... ..... ..... ... ... ... , ....,.. .............................. ..

....,.. ....... .......

,

1

..........

........ ....... ..... ....

, , , ,

.. ..

....

- - - .... - --

~ ~

-------""~

-Graphics-

Let us now derive a solution of the corresponding differential equation, and plot it. In[5]:=

NDSo1 ve [ {x' [t] == -y[t] + x[t] A2, y' [t] == x[t] + Sin[y[t]], x[O] == -1.5, y[O] == a}, {x, y}, {t, 0, 2}];

In[6]:=

sol = ParametricP10t[Eva1uate[{x[t], y[t]} /. %], {t, 0, 2}, P10tRange -> {{-2, 2}, {-2, 2}}] 2

1.5 1

0.5

-2

-1.

1

-2 Oulf~=

-Graphics-

The solution curve nicely fits the vector field, as it has to:

1.5

2

1. Basics

192 In[7]:=

Show [ {sol, vf}, AspectRatio -> Automatic]

...

...

..

, ,

--

......

...

....

.... ...

...

...

, .....

.......... , ........... "

......

,

, , '1:-5"" , , ...

....1

,

• 0."5

, I

,

\

'

-0.5

...... "

........... ,

, 0.5

, ,

.....

,

'"

I

I I I /'

, " /' " " /'

/'

/'

.,.. .,.. ,. 1.5

-------...

2

- - - .-

...

........................

o

... ,

...

-2

Oulf~=

....

,

.................

..... ....

2

...

,

............. -2

-Graphics-

Graphics Tools

The package Graphics' Graphics' contains definitions for logarithmic plots, bar charts, pie charts, plots with error bars, tools for custom labelling, and much more. In[B]:=

«Graphics' Graphics'

In[9]:=

?Graphics' Graphics'

*

BarChart BarEdges BarEdgeStyle BarGroupSpacing BarLabels Barorientation BarSpacing BarStyle BarValues DisplayTogether DisplayTogetherArray ErrorListPlot GeneralizedBarChart LabeledListPlot

LogListPlot LogLogListPlot LogLogPlot LogPlot LogScale PercentileBarChart PieChart PieExploded PieLabels PieLineStyle PieStyle PiScale PolarListPlot PolarPlot

193

1.8 More Selected Tools LinearLogListPlot LinearLogPlot LinearScale ListAndCurvePlot LogGridMajor LogGridMinor LogLinearListPlot LogLinearPlot In[10}:=

Scale ScaledListPlot ScaledPlot SkewGraphics StackedBarChart TextListPlot TransformGraphics UnitScale

Plot [BesselJ[3, x], {x, 0, 6Pi}, Ticks -> {piScale, Automatic}] 0.4

0.3 0.2

0.1

-0.1 -0.2

-0.3

OUlf10= -GraphicsIn[11}:=

BarChart [Sin [Range [10]] "2]

Out[11}= -Graphics-

194

o

1. Basics

Sound

Mathematica can not only draw, but also play sound. The command Play does it for us. It works in an analogous manner to Plot. Of course, we need a computer with the necessary sound equipment for that. In[12]:=

Play[Sin[2Pi 440t],

{t, 0, 2}]

Out[12]= -SoundIn[13]:=

Play[AiryAi[t] Sin[2Pi 440t],

{t, 0, 2}]

Out[13]= -Sound-

o

Summary Expression Play[j,

{t,

Meaning tmin'

t max } 1

generate sound with the amplitude function!

Table 1-87: Sound

195

1.8 More Selected Tools

Package

Contents

Graphics'PlotField'

vector fields in two dimensions

Graphics'PlotField3D'

vector fields in three dimensions

Graphics'Graphics'

many useful tools for two-dimensional graphics

Table 1-88: Some packages for graphics

o

Exercises

1. Draw the vector field corresponding to the system of differential equations

= -z,

i

y = siny, i

= x.

Where is a good point of view? 2. Draw a logarithmic plot of BesselK [1, xl in the range between 0 and 5. 3. Listen to the superposition of the concert pitch (440 Hz) with a sound that is detuned by I Hz.



1.8.2 Complex Numbers

The built-in functions Re, Im, Abs, Arg, and Conjugate only evaluate for numbers. In{1]:=

Re [a + I b]

Out[1}=

Re [a + I

b]

This is because the symbols a and b can stand for anything-real or complex numbers, or other Mathematica objects. The function ComplexExpand is a great help if we want to work with real and complex symbols. If ComplexExpand is given one argument only, it assumes all parameters to be real. In{2]:=

ComplexExpand [Re [a + I bll

Out[2}=

a

196

1. Basics

If certain parameters are not real, and we want them to be split into their real and imaginary part, we can pass these parameters (as a list) in the second argument. In[3]:=

ComplexExpand [Re [a + I b],

Out[3]=

-Im[b]

{a, b}]

+ Re [a]

The option TargetFunctions controls the functions which are used for the result. In[4]:=

ComplexExpand [Re [a + I b], {a, b}, TargetFunctions -> {Abs, Arg}]

Out[4]=

Abs [a]

Cos [Arg [a]]

- Abs [b] Sin [Arg [b]]

Another application of ComplexExpand is the transformation of trigonometric functions with complex arguments. In[5]:=

ComplexExpand[Sin[a + I b]]

Oulf~=

Cosh[b] Sin[a]

+ I Cos [a]

Sinh[b]

The package Algebra' ReIm' does complex calculations by another method. In[6]:=

< {Re, {Abs[(a + I b)"3], Arg[(a + I b)"3]}

Im}]& /@

Oulf1~= {(a 2

+ b 2 )3/2, ArcTan[Cos[3 ArcTan[a, bll, Sin[3 ArcTan[a, blll}

o

Summary Expression

Meaning

Re [xl

the real part of a complex number

Im[xl

the imaginary part of a complex number

Conjugate [xl

the complex conjugate of a complex number

Abs [xl

the absolute value of a complex number

Arg [xl

the argument of a complex number

Table 1-89: Functions for complex numbers Expression

Meaning

ComplexExpand [exprl

expand by assuming that all symbols are real

Table 1-90: The manipulation of complex symbols

198

1. Basics

Meaning

Expression ComplexExpand [expr,

{Xl'

X2'

... } 1 expand and assume that all symbols, except xl' X2, ... ,

ComplexExpand [expr, {Xl' X2' TargetFunctions -> {if} 1

... },

are real

try to write the result in terms of the functions if, which are taken from {Re, 1m, Abs, Arg, Conjugate, Sign}

Table 1-90: The manipulation of complex symbols Package

Contents

Algebra'Relm

,

extensions ofRe, 1m, and Conjugate to symbols

Table 1-91: A package for complex symbols Expression

f /:

lhs

=

Meaning rhs the definition is associated to f

Table 1-92: Associated definitions

o

Exercise

1. Calculate the real and the imaginary part of 1 (a+ib)3'

where a and b are real.



1.8.3 Sums, Products, Series

o

Symbolic Sums, Products, and Series

We have seen in Section 1.6.2 that the functions Sum and Produc t do what their names say. In[1]:=

Sum [k A 3 ,

Out[1}=

3025

{ k , 10 } ]

199

1.8 More Selected Tools

If, for instance, the upper bound is a symbol, these functions do not evaluate anymore. In[2]:=

Sum[k"3,

Out[2]=

3 Sum [k ,

In[3]:=

Product[l - 1/(2k),

Out[3]=

1 Product[l - 2-j('

In[4]:=

Sum[(n - l)/(n + 1)"5, {n, Infinity}]

Out[4]=

-1 + n Sum [--------, (1 + n) 5

{k, n}] {k,

n}]

{n,

{k, 1, n}]

{k, 1, n}]

Infinity}]

The last case can be approximated by a numerical sum with NSum. In[5]:=

NSum[(n - l)/(n + 1)"5, {n, Infinity}]

Oulf~=

0.00846772

The analogous function NProduc t returns numerical approximations of products. In Section 3.3.3, we will see how the precision of such numerical calculations can be controlled.

If we want symbolic results, it is necessary to load the package Algebra' SymbolicSum'. It extends Sum and Product to a large class of symbolic sums and products. In[6]:=

«Algebra' SymbolicSum'

In[7]:=

Sum[k"3,

Oulf~=

In[8]:= Out[8]= In[9]:=

n 2 (1 + n)2

-----4-----

Product[l - 1/(2k),

{k, 1, n}]

(2 n)!

4-n--~2 n. Sum[(n - l)/(n + 1)"5,

Oulf~= ~Q-§o~~~

o

{k, n}]

+

{n, Infinity}]

~~1YQ~~1~L_~1

Taylor Expansions

The function Series returns a Taylor expansion.

200

1. Basics

In[10]:=

Series[Sin[xl Exp[x"2l, {x, 0, 8}l

Out[10]=

x +

5 x3

-6--

+

41 x 5

-120-

+

461 x 7

-5040-

+ O[x]

9

Functions, which are approximated by such series, can be inverted with InverseSeries. In[11]:=

InverseSeries [%, xl

Out[11]=

x -

~6~:

+

~~~o~~ - n~~h~~

+ 0 [x]9

Indeed, if this series is substituted for x into the original series, we get the identity (up to the desired order). In[12]:=

%% /. x -> %

Out[12]=

x + 0 [x]9

Such series objects (containing an 0 [ ... ] ) can be converted back into normal expressions with Normal. This truncates the terms of "higher order".

o

In[13]:=

Normal [%l

Out[13]=

x

Summary

Expression

Meaning

Sum[j, range]

the sum over /; the range is analogous to Table 1-63 on page 141

Product [I, range]

the product

NSum[j, range]

the numerical approximation of a sum

NProduct [I, range]

the numerical approximation of a product

Series [j,

{x, xO' n}]

the Taylor series of/in x = xo, up to the order (x - xo)n

InverseSeries [s, x]

the series expansion of the inverse function, where s has been produced by Series

Normal [s]

return a normal expression for a series s, by truncating the terms of "higher order"

Table 1-93: Sums, products, series

201

1.8 More Selected Tools

Contents

Package Algebra'SymbolicSum

,

extensions of Sum and Product to symbolic sums, products, and series

Table 1-94: A package for symbolic sums and products

o

Exercise

1. Calculate

n 00

k= 1

4k(k+ 1). (l + 2k) 2

2. Find and compare two series expansions of the arcsine function, by a direct expansion, and by inverting the expansion of the sine function.



1.8.4 Data Analysis, Interpolation

o

Reading and Plotting External Data

We have seen in Section 1.5.5 that external data can be imported with ReadList. The functions ListPlot, ListPlot3D, ListContourPlot, and ListDensi tyPlot plot discrete data. If three-dimensional data points are not lying on an equidistant grid, we can use the functions ScatterPlot3D and ListSurfacePlot3D from the package Graphics' Graphics3D' .

o

Approximations, Interpolations

Let us now look at the following data: In{1]:=

data = Table[N[x! Exp[-2xll,

{x,

lOll;

202

1. Basics

In[2]:=

dataPlot

ListPlot[data, AxesOrigin -> {a, O}]

0.12 0.1 0.08 0.06 0.04 0.02 2

Oulf~=

8

6

4

10

-Graphics-

With Fi t, the points can be approximated by linear combination of some given functions. It returns a least-squares fit. Of course, the quality of the fit highly depends on the chosen functions. A first approximation might use a quadratic polynomial.

=

In[3]:=

fitl

Fit [data,

{l, x, x"2}, x]

Oulf~=

0.140872 - 0.0439157 x + 0.00320296 x 2

We can expect a better approximation by adding a suitable exponential function (see Outfl)= below). In[4]:=

fit2 = Fit[data, {l, x"2, Exp[-x]}, x]

Oulf~=

-0.00352578 + Q~~§1~1 + 0.000124671 x 2 EX

The following fit returns an approximation by a function of the form

In[S]:=

fit3 = Exp[Fit[Log[data],

Oulf~=

E-0.959735 - 1.3141 x + 0.0933464 x 2

{l,

x, x"2}, x]]

How good are these fits? Let us use the option PlotStyle (see Table 1-97) to get different dashings for the plots. We suppress displaying the graphics in a first step (see Section 1.5.2).

203

1.8 More Selected Tools In[6]:=

Oulf~=

fitPlot = Plot[{fit1, fit2, fit3}, {x, 1, 10}' PlotStyle -> {Dashing[{1, O}], Dashing[{.09, Dashing[{.06, .02}]}, DisplayFunction -> Identity]

.02}],

-Graphics-

By setting DisplayFunction -> $DisplayFunction, the above plots can be displayed, together with the data points. In£7]:=

Show[fitPlot, dataPlot, DisplayFunction -> $DisplayFunction] 0.05 0.04 0.03 0.02 0.01

-0.01

Oulfn= -GraphicsObviously, the third fit gives the best result. We can also find an interpolating polynomial, which goes exactly through the data points.

=

In[B]:=

iPoly

InterpolatingPolynomial [data, x]

Oulf~=

0.135335 + (-0.098704 + (0.0384726 + (-0.0103346 + (0.00213703 + (-0.000360076 + (0.0000513625 + (-6.35489 10- 6 + (6.95711 10- 7 6.82455 10- 8 (-9 + x))

(-8 + x)) (-7 + x)) (-6 + x)) (-5 + x)) (-4 + x)) (-3 + x)) (-2 + x)) (-1 + x) In[9]:= Oulf~=

iPolyPlot = Plot [iPoly, {x, 1, 10}, DisplayFunction -> Identity]

-Graphics-

204 In{10}:=

1. Basics Show [ipolyPlot, dataPlot, DisplayFunction -> $DisplayFunction, PlotRange -> {O, .04}] 0.04 0.035 0.03 0.025 0.02 0.015 0.01 0.005

o

2

4

6

8

10

OUlf10= -Graphics-

The interpolating polynomials become very complicated for large sets of data. In such cases, it is better to use suitable interpolations of successive data points (splines). This is done by Interpolation. The result is a pure function (see Section 1.6.2) of type InterpolatingFunction. We have met such objects as the results of NDSol ve. The degree of the interpolation polynomial is normally 3; if desired, it can be changed with the option InterpolationOrder. If desired, we can add the values of derivatives to the data as well. In[11}:=

iFunct = Interpolation [data]

Out{11}= InterpolatingFunction [{ L In{12]:=

10 L

1

iFunctPlot = Plot [iFunct [x], {x, 1, 10}, DisplayFunction -> Identity]

Out{12}= -GraphicsIn{13}:=

Show [iFunctPlot, dataPlot, DisplayFunction -> $DisplayFunction, PlotRange -> {O, .04}]

205

1.8 More Selected Tools

0.04 0.035 0.03 0.025 0.02 0.015 0.01 0.005 0 Out[13}=

2

4

6

8

10

-Graphics-

This curve is not as smooth as the interpolating polynomial, but its second derivative is still continuous. We might compare the errors of both versions, if compared to the original function (see Exercises 1 and 2).

o

Statistical Analysis, Nonlinear Fits

The directory S tat i s tic s contains many standard packages for statistical analysis, as well as tools for nonlinear fits. After executing the command In[14}:=

Needs [IIStatistics'Master' II]

we can freely use all these functions; the necessary packages are then loaded automatically.

o

Summary

Expression

Meaning

Fit [data, funs, varsl

the approximation of data by a least-square fit with the functions funs, in the variables vars

InterpolatingPolynomial[

the interpolation of data points by a polynomial inx

ifl' ... , fn}' xl InterpolatingPolynomial[ {xI'

II},

.0. ,

{xn' fn}}' xl

a polynomial in x, which goes through the points {xi,fil

Table 1-95: Interpolations of data

1. Basics

206

Expression

Meaning

InterpolatingPolynornial[ {xl' {iI' dft ' ddft, ... L ... } , xl

a polynomial which interpolates data (given by values and derivatives)

Interpolation [datal

the interpolation of data by an InterpolatingFunction object; see Table 1-96 for the forms of data

Table 1-95: Interpolations of data Data without Derivatives {iI'

Data with Derivatives

... , In}

{ {xl'

ftL .. ,'

{ {Xl'

Yl'

{x n , In}}

... , ftL ... }

{ {xl'

{iI' dft ' ddft,

... } L ... }

replace jj by {jj, {dxfi, dyjj, ... } }

Table 1-96: The different forms of data in Interpolation Option

Meaning

Interpola tionOrder the degree of the polynomial curves (default: 3)

Table 1-97: An option for Interpolation Option

Values

PlotStyle

style

Meaning

{ {stylel} ,

{style2} }

• the style for points and lines (Dashing, etc.) • the styles of successive lines (treated cyclically)

Table 1-98: An option for Plot and ListPlot Directory

Contents

S tat i s tic s

several packages for statistical analysis

Table 1-99: Packages for statistics

o

Exercises

1. Compare the absolute values of the approximations by an interpolating function (spline) and by an interpolating polynomial, for the above data of x!e-2x .

207

1.8 More Selected Tools

2. Do the same as in Exercise 1, but for data points of the sine function, in the interval [0, 2It].



1.8.5 Transformations

o

Discrete Fourier Transforms

The built-in functions Fourier and InverseFourier use a fast "FFT" algorithm to calculate the discrete Fourier transform of a list of complex numbers and the inverse. The length of the data does not need to be a power of 2. Let us consider the data from a decreasing exponential function, completed with the value 0.5 at the left side (see [Bri74]). In[1]:=

expData = Join [ { .5}, Table [Exp [-t] {t, .25, 7.75, .25}]];

In[2}:=

ListPlot [expData, PlotRange -> {a, 1}, PlotLabel -> "Data"]

/ / N,

Data

1

0.8 0.6

0.4 0.2

o Oulf2}=

... 5

10

15

20

25

30

-Graphics-

We now calculate the discrete Fourier transform. In[3}:=

fData = Fourier [expData] ;

To compare with the continuous transform, we scale as follows: In[4}:=

fData = fData .25 Sqrt [Length [expData] ] / / N;

208

1. Basics

The corresponding physical frequencies run over a range of length 3.875. The following command produces a plot of the real part of the discrete Fourier transform: In[5]:=

diseRe = ListPlot [ Transpose[{Table[t, {t, 0, 3.875, .125}], Re[fData]}], PlotRange -> All, PlotLabel -> IRe[DFT]"] Re[DFT] 1

0.8 0.6 0.4

0.2

. . . . . . . . .. . ........ . 1

Oulf~=

2

3

-Graphics-

The origin corresponds to the frequency 0, the right half of the plot to the negative frequencies. It is possible to move the latter to the left, but the chosen representation is more common. The continuous Fourier transform of the original function (see In[1]:=) (t 2:: 0)

(t < 0)

can be calculated by hand. In[6]:= Out[6]=

eft

= Integrate[Exp[-t]

Exp[2Pi I f t], {t, 0, Infinity}]

1 + 2 I Sqrt[f 2 Pi 2 ]

----1-~-4-f2-~i2----

For its real part, we get: In[?]:=

eftRe = ComplexExpand[Re[eft]]

Out[?]=

1 ;:-~-4-f2-~i2

209

1.8 More Selected Tools In[8]:=

= Plot[cftRe, {f, 0, 3.875}, PlotLabel -> "Re[CFT]"]

c~ntRe

Re [CFT]

1 0.8 0.6 0.4 0.2

1

Dut[8]=

2

3

-Graphics-

The following plot compares the two transforms for positive frequencies: In[9]:=

Show [discRe, contRe, PlotLabel -> "Re[DFT], Re[CFT]", PlotRange -> {{O, 3.875/2}, All}] Re[DFT], Re[CFT] 1

0.25 Duq~=

0.5

0.75

1

1.25

1.5

1.75

-Graphics-

The agreement is good.

o

Symbolic Fourier Transforms

The standard package Calculus' FourierTransform' contains tools for the symbolic calculation of continuous Fourier transforms and Fourier series:

1. Basics

210 In[10]:=

«Calculus' FourierTransform'

In[11]:=

?Calculus' FourierTransform'

*

FourierCosSeriesCoefficient FourierCosTransform FourierExpSeries FourierExpSeriesCoefficient $FourierFrequencyConstant FourierFrequencyConstant $FourierOverallConstant FourierOverallConstant FourierSample FourierSinSeriesCoefficient FourierSinTransform FourierTransform FourierTrigSeries InverseFourierCosTransform InverseFourierSinTransform InverseFourierTransform NFourierCosSeriesCoefficient NFourierExpSeries NFourierExpSeriesCoefficient NFourierSinSeriesCoefficient NFourierTransform NFourierTrigSeries In[12]:= Out[12]=

In[13]:= Out[13]=

FourierTransform[Exp[-a t"'2] fb, t, f]

_____ ~g~~l~~l _____ _ Sqrt[al b E f2 /(4 a)

InverseFourierTransform [%, f,

t]

1

------2

b Ea t

The package also defines the Dirac function: In[14]:=

FourierTransform[l, t, f]

Oulf1~=

2 pi DiracDelta[fl

FourierTrigSeries [expr, {x, xmin' x max }' n] returns the Fourier series of expr, up to the order n. The function in x is treated as periodic, with a period from xmin to xmax .

211

1.8 More Selected Tools In[15]:=

fs = FourierTrigSeries[x A2, {x, 0, 1}, 3]

Out[15]=

~

+ ~~§l~_E~_~l + ~~§l~_E~_~l + ~~§l§_E~_~l +

pi 2

2

(_:1 __

4 pi 3

4 pi 2

+

1_:_~_E~~) 4 pi 3

1_:_~_E~~)

2 ( __ :1 __ + 32 Pi 3 2 (-1

108-~i3

32 Pi 3

+

9 pi 2

Sin[2 pi xl + Sin[4 pi xl +

1_:_1~_~~:) 108 Pi 3

Sin[6 pi xl

We can compare the original function with its approximation by a Fourier series: In[16]:=

Plot[{fs,

(x - Floor[x])A2), {x, 0, 4}]

1

Ouq1~=

o

-Graphics-

Symbolic Laplace Transforms

The package Calculus'LaplaceTransform' contains the functions LaplaceTransform and InverseLaplaceTransform for the calculation of Laplace transforms. In[17]:=

«Calculus' LaplaceTransform'

In[18]:=

?Calculus' LaplaceTransform' *

Definitelntegral LaplaceTransform InverseLaplaceTransform ZeroLimit In[19]:=

LaplaceTransform[Exp [t], t, s]

Out[19]=

:1-:;:-8

1

212

1. Basics

In{20]:=

InverseLaplaceTransform[Exp [a/s + bl, s, tl

OUlf20= Eb

(Sqrt[E1 BesselI[l, 2 Sqrt[a t11 + DiracDelta[t1)

The most important rules are already built-in: In{21]:=

LaplaceTransform[g' [t] + t g[t], t, s]

Out{21]=

-g [0 1 + s LaplaceTrans form [g [t 1, t, s 1 LaplaceTransform(O,O,l) [g[t1, t, sl

o

Summary Expression

Meaning

Fourier [list1

the discrete Fourier transfonn of a list list= {aI' ... , an} , according to b = s

InverseFourier [list1

n

L a r e 21ti (r-l) (s-I)/n In

J...

r

=I

the discrete inverse Fourier transfonn of a list list= {b l , ... , b n } , according to a

r =

J...

n

L b e-21ti (r-l) (s-I)/n

Jns=1

S

Table 1-100: Discrete Fourier transforms Package

Contents

Calculus'FourierTransform'

symbolic Fourier transfonns and series

Calculus'LaplaceTransform'

symbolic Laplace transfonns

Table 1-101: Packages for symbolic transformations

o

Exercises

1. Consider the Bessel function Bes s e 1 J [ 1, t 1 in the interval of its first (double-sided) "oscillation". Continue the function periodically and approximate it by a Fourier series. Compare the series to the original function. 2.

Construct another example for the comparison of a discrete with a continuous Fourier transfonn.

1.8 More Selected Tools



213

1.8.6 Mathematical Functions

The Mathematica kernel contains many more mathematical constants and functions. Among them are:

Abs, AiryAi, AiryAiPrime, AiryBi, AiryBiPrime, ArcCos, ArcCosh, ArcCot, ArcCoth,ArcCsc, ArcCsch,ArcSec, ArcSech,ArcSin,ArcSinh,ArcTan, ArcTanh,Arg,ArithmeticGeometricMean, BernoulliB,BesselI, BesselJ,BesselK,Bessel~Beta, Binomial, Catalan, Ceiling, ChebyshevT, ChebyshevU, ClebschGordan, Conjugate,Cos,Cosh,CosIntegral,Cot,Coth,Csc,Csch,Degree, Divisors, DivisorSigma, E,EllipticE,EllipticExp, EllipticF, EllipticK,EllipticLog, EllipticPi,EllipticTheta, Erf,Erf c, EulerE, EulerGamma, EulerPhi, Exp, ExpIntegralE, ExpIntegralEi, ExtendedGCD, Factorial, FactorInteger, Floor, Gamma, GaussianIntegers, GCD, GegenbauerC, GoldenRatio, HermiteH, HypergeometricOF1, HypergeometriclFl, Hypergeometric2Fl, HypergeometricU, I, 1m, Infinity, IntegerDigits, InverseJacobiSN,JacobiAmplitude,Jacobi~JacobiSN,JacobiSymbol,Ja­

cobizeta, LaguerreL, LCM, Legendre~ LerchPhi, Log, LogIntegral, Max, Min, Mod, MoebiusMu, Multinomial, Partitions, Parti tionsQ, pi, Pochhammer, PolyGamma, PolyLog, PowerMod, Prime, PrimePi, PrimeQ, Quotient, Random, Re, RiemannSiegelTheta,RiemannSiegelZ,Round,Sec, Sech,SeedRandom, Sign, si gnature,Sin, Sinh, SinIntegral,SixJSymbol, SphericalHarmonicY, StirlingSl, StirlingS2, Tan, Tanh, ThreeJSymbol and Zeta. The mathematical properties and definitions of the special functions should be looked up in a handbook (e.g., [AS65]). We get a short explanation from Mathematica's help tools (see Chapter 1.2). More details are given in the Mathematica book [WoI91]. In{1]:=

?RiemannSiegel Theta

RiemannSiegelTheta[t] gives the analytic function theta(t) which satisfies RiemannSiegelZ[t] == Exp[I RiemannSiegelTheta[t]] Zeta[1/2 + I t]. The argument t need not be real, but if it is, then RiemannSiegelTheta[t]] == Im[LogGamma[1/4 + I t/2]] - t Log [Pi] /2.

214

1. Basics

Let us verify that the Bessel function really solves the corresponding differential equation, and that the cosine integral and the error functions are defined properly: In[2}:=

DSolve[t A2 X[t],



X"

[t] + t x' [t] + (t A2 - n A2)x[t]

0,

t]

Oulf~=

{{x[t] -> BesselJ[Sqrt[n 2 ], t] C[l] + BeSselY[Sqrt[n 2 ], t] C[2]}}

In[3}:=

Integrate [Cos [t] It, t]

Oulf~=

Coslntegral[t]

In[4}:=

2/Sqrt [Pi] Integrate [Exp [-tA2], t]

Out{4}=

Erf [t]

1.8.7 Polynomials

When working with polynomials, one often wants to get information about their structure, or about certain coefficients. The functions listed in Table 1-102 are of great help for such tasks.

=

(a + x)A2 (b - x) A2

In{1]:=

poly

Out{1}=

(b -

In{2):=

Length [poly]

Out[2}=

2

In[3}:=

Length[Expand[poly]]

Out{3}=

9

In[4}:=

Exponent [poly, x]

Out[4}=

4

x) 2 (a + x)2

The list of the coefficients-in increasing order, starting with the constant termis given by: In[5}:=

CoefficientList [poly, x]

Oulf~=

{a 2 b 2 , -2 a 2 b + 2 a b 2 , a 2

In[6}:=

CoefficientList[poly, {a, b}]

Out[6}=

4 -2 x 3 , x 2 }, {2 x 3 , -4 x 2 , 2 x}, {{x,

4 a b + b 2 , 2 a - 2 b, l} {x 2 , -2 x, l}}

215

1.8 More Selected Tools

There are many functions for calculations with polynomials (see Table 1-103). We already know some of them from Section 1.4.1. In[7]:=

PolynomialQuotient [x"10 + x"3 + 1, x"S - 1, x]

Dut[7]=

1 + x5

In[S]:=

PolynomialRemainder [x" 10 + x" 3 + 1, x" 5 - 1, x]

Dut[S]=

2 + x3

In[9]:=

Decompose [x"10 + x"S + 1, x]

Dulf~=

{1 + x + x 2 , x 5 }

In[10]:=

Decompose [1 - 3x + x"2 - 3x"3 + 2x"4 + x"6, x] 3 x + x2 , x

DUlf10= {1 In[11]:=

Expand[%[ [1]]

Dut[11]= 1 -

o

(1 + x 2 )}

/. x -> %[ [2]]]

3 x + x 2 - 3 x 3 + 2 x4 + x 6

Summary Expression

Meaning

Length [poly]

the length (of the current form)

variables [poly]

the list of the variables

Exponen t [poly, x]

the maximum power of x

Coefficient [poly, expr]

the coefficient of expr in poly

Coefficient [poly, expr, n]

the coefficient of expr"

CoefficientList[po~,

x]

CoefficientList[po~,

{xl'

the list of coefficients of the variable x (from xO through xLength [poly] ) x2'

... , } ] the matrix of the coefficients of the variables Xi (the terms which are independent of the variables come first)

Table 1-102: The structure of polynomials

216

1. Basics

Expression

Meaning

Polynomial Quotient [poly], polY2' xl

the result of dividing poly] by polY2 (as polynomials in x), with the remainder dropped

PolynomialRemainder [poly], POlY2' x]

the remainder from dividing poly] by polY2

PolynomialGCD [poly], polY2]

the greatest common divisor

PolynomialLCM [poly], polY2]

the least common multiple

PolynomialMod [poly], m]

the polynomial reduced modulo m

Factor [poly]

factor a polynomial

FactorSquareFree [poly]

pull out squared factors

FactorTerms [poly, x]

factor terms which are independent of x

FactorList [poly] FactorSquareFreeList [poly] FactorTermsLis t [poly, {x] , x2'

show the results as lists

Cyclotomic [n, x]

... } ] the cyclotomic polynomial of order n in x:

II( x-e 2nik) n k

Decompose [poly, x]

write a polynomial as a composition of simpler polynomials

Resul tan t [poly! ' polY2' x]

the resultant of two polynomials

Table 1-103: Calculations with polynomials



1.8.8 Linear Algebra, Linear Programming

Systems of linear equations can not only be solved with Solve, but also with LinearSol ve. To use the latter function, the system has to be written in matrix form. For large, sparse matrices, this should be the most efficient way. Analogous to the above, there are two versions of the tools for linear programming: LinearProgramming (for matrices), and ConstrainedMax and ConstrainedMin (for inequalities).

217

1.8 More Selected Tools

o

Summary

Expression

Meaning

LinearSolve[m, b]

solve the matrix equation m . x

LinearSolve[m, b, ZeroTest ->

/l

== b x == b; use the

solve the matrix equation m . function/to test if matrix elements are zero (e.g., Mod [#, 2] &)

NullSpace[m]

a list of vectors which form a basis of the null space of m (vectors x with m . x == 0)

RowReduce[m]

the row-reduced form of m

SingularValues[m]

return u, mD, v from the equation m = uT mD v, where mD is diagonal

Pseudolnverse[m]

the pseudoinverse; minimize the sum of the squares of the matrix m . Pseudolnverse [m] - 1

QRDecornposition[m]

the QR decomposition of a numerical matrix

SchurDecornposition[m]

the Schur decomposition of a numerical matrix

JordanDecornposition[m]

the Jordan decomposition

LUDecornposition[m]

the LU decomposition (a list {j, perm} with a matrix / and a permutation perm)

LUBackSubstitution[{j, perm} , b]

return the vector x, which solves the equation m . x == b (see LUDecornposition)

ConstrainedMax [j, {x, y, ... } ]

{inequalities} ,

the global maximum of/in the domain specitied by the inequalities

ConstrainedMin [j, {x, y, ... } ]

{inequalities} ,

the global minimum of/in the domain spec itied by the inequalities

LinearPrograrnrning[c, m, b]

the vector x which minimizes c . x, subject to the constraints m . x ~ b and x ~ 0

Table 1-104: Linear algebra and linear programming



1.8.9 File Manipulation

Mathematica contains many tools for the manipulation of files and directories. These functions can be combined with the programming language, which makes them very attractive

218

1. Basics

In{1]:=

d = Directory []

Out{1]=

Internal: Desktop Folder :Applications : Mathematica

In{2]:=

Save ["dummy", d]

In{3]:=

FileNames []

Oulf~=

{Defaults, Documents, dummy, Help, Kernel, Mathematica, Packages, SKPackages}

In{4]:=

CopyFile[#, StringJoin[#, "_", ToString [FileByteCount [I] ] ] ] & ["dummy"]

Out{4]=

dummy-55

In{5]:=

FileNames ["dummy*"]

Out{5]=

{dummy, dummy-55}

In{6]:=

DeleteFile [%]

In{7]:=

FileNames []

Oulf~=

{Defaults, Documents, Help, Kernel, Mathematica, Packages, SKPackages}

o

Summary Expression

Meaning

Directory [ )

the current directory

SetDirectory ["dir" 1

change the current directory

ResetDirectory[)

change back to the last current directory

ParentDirectory[)

the parent directory

HomeDirectory [ )

the personal "home" directory

Table 1-105: Directories Expression

Meaning

CreateDirectory[ "name" 1

create a directory

DeleteDirectory [" name" 1

delete an empty directory

DeleteDirectory["name" ,

delete a directory and all files and directories that it contains

DeleteContents -> True)

Table 1-106: Changing directories

219

1.8 More Selected Tools

Expression

Meaning

RenameDirectory [ "nameJ" , " name2"]

rename a directory

CopyDirectory [ "nameJ" , "name2"]

copy a directory

Table 1-106: Changing directories Expression

Meaning

FileNames []

list all files in the current directory

FileNames ["form"]

list all files that match a pattern; a list of patterns can be used, as well; see Section 2.6.7 for string patterns

FileNames [forms, {"dirJ" ,

" dir2" ,

... } ]

FileNames [forms, dirs, n]

list all file names in the given directories take into account all subdirectories up to n levels down

Table 1-107: Searching files Expression

Meaning

CopyFile ["fileJ" , "file2" ]

copy jileJ to jile2

RenameFile [ "fileJ" , "file2" ] rename jile J to jile2 DeleteFile ["file"]

delete a file

FileByteCount ["file"]

show the number of bytes in a file

FileDate ["file"]

show the date of the last modification

SetFileDate ["file"]

change the modification date

FileType [ "file" ]

show the type of a file

Table 1-108: Working with files



1.8.10 Custom Configuration

Mathematica can be configured in flexible ways, to meet the user's personal needs. This is done either by adding definitions to the file i nit. m, or by saving a configured binary version of the program (this is not possible on all platforms).

220

D

1. Basics

The Initialization File

When we launch Mathematica, the contents of the file i nit. m are evaluated automatically. We can therefore use this file for any tasks which should be done at the beginning of each session, e.g., to load certain packages. On UNIX systems, it is even possible to keep several versions of the i nit. mfile: The current directory, from which Mathematica was started, is searched first. We can therefore keep different files in different directories and choose between them, by changing to the appropriate directory before starting Mathematica.

The i nit. mfile already contains some commands (initialization of graphics, etc.), which normally should not be changed. But we can add any Mathematica expressions to change the default behavior of the program. A common type of configuration can be set up by adding commands to load packages or, even better, by declaring that certain symbol names belong to certain packages (with DeclarePackage, see Section 2.5.2). This assures that the package is loaded whenever we use the symbol name. We may have written our own packages or want to install packages in a directory which normally is not searched. In such a case, we can extend the search path by adding commands like

SPath = Join[$Path, {"Disk:Mathernatica:MyPackages"}]; (Macintosh) or

SPath = Join[$Path, {"-/rnrna/rnypackages"}]; (UNIX) to i nit. m. We can as well change the way Mathematica functions behave; we will talk about these techniques in the next part of the book. If s.uch a change shall be activated at all times, we can add it to the i nit. mfile. Mathematica does not automatically rewrite logarithms of products as sums of the logarithms: In[1]:=

Log [a b]

Out{11=

Log [a b]

We might want to change this. The following expressions add such a definition for the Log function (see Subsection "Changing Built-in Functions" on page 260): In{21:=

Unprotect [Log]; Log [x_ y _]

: = Log [x] +Log [y]; Protect [Log] ;

221

1.8 More Selected Tools In[3]:=

Log [a b]

Out[3]=

Log [a]

+ Log [b]

If this shall be done automatically for every session, add the following line to i nit. m: Unprotect[Log]i Log[x_ y_]

~

o

:= Log[x]+Log[y]i Protect[Log]i

Be very careful when applying such changes. They can easily have unexpected side effects.

Saving a Dump Image

The Dump command saves the whole Mathematica binary in its current state (on UNIX systems). We can use it to save an image of a long session, which can be used to continue the session exactly where we stopped. Or we can create a custom binary, for instance, with certain packages preloaded. An application of Dump could look like this: Dump ["myMath",

$Line=O i

« i n i t .m]

This resets the line number to zero and loads the in it. mfile at start-up. The file my Mat h can easily be a couple of Megabytes large. Dumping is therefore not a good tool just to save data; it is better to use the Save command for that (see Section 1.5.2).

o

Summary File

Contents

init.m this file contains Mathematica expressions which are evaluated each time a new session is started

Table 1-109: The initialization file Variable Meaning $ Pa th

a list of directories, in which files are searched

Table 1-110: The global variable for the search path

222

1. Basics

Expression

Meaning

Dump [ "filename" 1

write the binary image of the current state of Mathematica to a file

Dump [ "filename" , init 1

write the binary image of the current state of Mathematica to a file; evaluate in it when the image is executed

Table 1-111: Saving binary images of Mathematica



1.8.11 Resources

It is useful to have some tools which control memory and time resources, especially for large calculations (see also: Chapter 3.4).

o

Time

Long calculations can be aborted after a chosen time with the function TimeConstrained. Its first two arguments are the expression to be evaluated and the time limit. If we pass an optional third argument, this expression is used in case the time constraint is not met. As an example, we factor random numbers and interrupt longer calculations after one second, with the result" di f f i cuI t " . In[1J:=

Table [ n = Random [Integer, {10 A 19, 10 A 20}]; TimeConstrained[{n, FactorInteger[n]}, 1, {n, "difficult"}], {5}] II TableForm[#, TableHeadings -> {None, {"Number\n", "Factors and Multiplicities\n"}}]&

Out[1]//TableForm=

Number

Factors and MUltiplicities

37869249568112469125

5 23 13171912893256511

38231672239692596621

11 1 19 1 182926661433935869 1 3 3701

3 1 1

1

1

223

1.8 More Selected Tools 20314913557695638379

1829677885048693

28650641190318440430

2 3 5 57829 16514575265189

40089152812797997394

difficult

1 1

1 1 1 1

Several other functions (see Table 1-112) can be used for timings and for the conversion of time and date.

o

Memory

Mathematica uses a lot of memory. This is not much of a problem on computers with enough RAM. For large calculations, we might have to use virtual memory. Of course, this will degrade the performance, as soon as the system has to access the disk. Certain operating systems allow us to control the amount of memory given to a program. On a Macintosh, we select the program file and choose Get Info. The lower part of the window, which now appears, contains an editable field for the memory. Some programs have a "meter", which gives information about the memory used. As soon as the meter starts to fill up, it is a good idea to save our valuable work. The kernel functions MemoryInUse and MaxMemoryUsed (see Table 1-113) return information about the memory used. ByteCount shows how many bytes are used to store an expression. In[2]:=

Table [ByteCount [(a+b) "i],

Out[2}=

{ 24 ,

60, 60, 6 0, 6 0, 60,

{i, lO}]

60, 60, 6 0, 60}

Of course, this depends on how the (mathematical) expression is written: In[3}:=

Table[ByteCount[Expand[(a+b)"i]],

Oulf~=

{24, 140, 256, 372, 488, 604, 720, 836, 952, 1068}

{i,

lO}]

The function MemoryConstrained is analogous to TimeConstrained.

224

1. Basics

In{4]:=

Table [MemoryConstrained [Expand [ (a+b) Ai], 500, "too large"], {i, 10}]

Oulf~=

{a + b, a 2 + 2 a b + b 2 , a 3 + 3 a 2 b + 3 a b 2 + b 3 , a 4 + 4 a 3 b + 6 a 2 b2 + 4 a b3 + b4 , a 5 + 5 a 4 b + 10 a 3 b 2 + 10 a 2 b 3 + 5 a b 4 + b 5 , too large, too large, too large, too large, too large}

The function Share minimizes the amount of memory used-but it can try our patience, if we do not apply it to specific expressions, only. It shares the storage of common subexpressions. In{S]:=

«Calculus' Ellipticlntegrate'

In{6]:=

MemorylnUse[]

Out{6]=

3445400

In{7]:=

Share [] II Timing

Out{7]=

{l8.7 Second, 843256}

In{8]:=

MemorylnUse[]

Out{8]=

2602832

o

Summary Expression

Meaning

Date []

the date and time

AbsoluteTime []

the number of seconds since 1-1-1990 ("absolute time")

SessionTime [ ]

the number of seconds since the beginning of the session

TimeUsed [ ]

the number of CPU seconds

Pause [n]

pause for n seconds

FromDate [date]

convert a date into absolute time (see above)

ToDate [time]

convert an absolute time into a date

Timing [expr]

the CPU time and the result of expr

TimeConstrained [expr, t]

evaluate expr, stopping after t seconds

TimeConstrained [expr, t, Jailexpr]

retumJailexpr if the time constraint is not met

Table 1-112: Functions for time and date

225

1.8 More Selected Tools

Expression

Meaning

MemoryInUse [ ]

the number of bytes currently used

MaxMemoryUsed []

the maximum number of bytes used in the current session

ByteCount [expr]

the number of bytes used by expr

Leaf Count [expr]

the number of (indivisible) subexpressions of expr

Share [expr]

optimize the memory used for expr

Share []

optimize all of the memory

MemoryConstrained [expr, b]

evaluate expr, stop if more than b bytes are requested

MemoryConstrained [expr,

retumJailexpr if the memory constraint is not met

b, Jailexpr]

Table 1-113: Functions in connection with the memory

Part 2.

Structure

228

2. Structure

In Part I, we have looked at direct applications of Mathematica, without worrying about the details of its syntax. It is now high time to deepen our understanding of what is really happening. In this part of the book, we will learn how to define more complicated functions, how to change the behavior of built-in functions, and how to write programs. At the same time, we will understand why Mathematica does not always do what a naive user might expect. Every input and output of Mathematica is an expression, which can be altered (Chapter 2.1). To grasp mathematical facts, we have to be able to identify patterns. They are the subject of Chapter 2.2. In Chapter 2.3, we study transformation rules and definitions, which act on certain patterns. Chapter 2.4 covers the evaluation scheme of Mathematica. At this point, we will learn more techniques for programming, which will be further explored in the third part of the book. A program should be written modularly. The tools for localization and modularization will be covered in Chapter 2.5. It is necessary to handle text (Chapter 2.6), in order to inform the user of a program about partial results, errors, the state of evaluation, etc.

o

About the Picture

The self-intersecting spiral surface is produced by: In[1]:=

ParametricPlot3D [ {

}

,

r Cos[3u], r Sin[3u], Sin[u]

{u, 0, 2Pi}, {r, 0, I}, PlotPoints -> {70, 10}, Boxed -> False, Axes -> False]

2.1 Expressions

• 2.1

229

Expressions

Surprisingly, the structure of every input or output of Mathematica is very simple: All we type or see is an expression. The work done by Mathematica consists of rewriting expressions, according to the given transformation rules (with - > or : » and definitions (with = or : =), until the expression does not change anymore.



2.1.1 The Structure of Expressions

Each expression has a head and one or several "parameters", which are put into brackets and separated by commas. Each parameter can again be an expression. For instance, the expression f [x y] is the prototype of a simple expression with two parameters. Its head is f, its parameters are x and y. I

The function FullForm allows us to view any expression in its standard notation. For f [x y], we get nothing new. I

In[1j:=

f [X, y]

/ /

FullForm

Out[1jllFullForm= f [x, y]

The next example is a little more interesting. In[2j:=

X

+ x"2 - Sin[z]

==

a / / FullForm

Out[2]//FuIlForm=

Equal [Plus[x, Power [x, 2], Times[-l, Sin[z]]], a]

On the first level, we see the head Equal and the corresponding two parameters. The first one is again composed (with head Plus) and can be taken apart further, and so on. The second parameter is the symbol a. TreeForm prints expressions with their different levels on different lines. In[3j:=

X

+ x" 2 - Sin [z]

==

a / / TreeForm

Out[3jl/TreeForm=

Equal [ I Plus[x,

, Power [x, 2]

I

]

Times[-l,

] Sin[z]

,

a]

230

2. Structure

The head and the "parameters" can have very different meanings, depending on what they stand for. We have quoted the word "parameter", to make this clear. Table 2-1 shows some of the possibilities. Head

"Parameter"

Examples

function

arguments, parameters

f [x), Sin [x) BesselJ[l, 1. 5)

command

arguments, parameters

Expand [ (a+b) "100) Short[%, 3)

operator

operands

x + y (full form: Plus [x, yJ) x = a (fullform:Set[x, aJ)

head

elements

List[a, b, c) (or {a, b, c} )

object type

contents

Hue[h, s, b)

Table 2-1: Some meanings of the parts of expressions Despite these different meanings, Mathematica treats all expressions uniformly. The function Head returns the head of an expression. In[4]:=

x"2 + x - Sin[z] == a / / Head

Out[4]=

Equal

We can use it to see that numbers have hidden heads. In[5}:=

Head /@ {1, l+I, 1.1}

Oulf~=

{Integer, Complex, Real}

We have mapped the function Head onto the list, to get the heads of its elements (see Section 1.6.2).

o Summary Expression

Meaning

FullForm [expr)

full standard notation of the expression expr

TreeForm [expr)

the representation as a "tree"

Head [expr)

the head of an expression

Table 2-2: The representation of expressions and parts of expressions

231

2.1 Expressions

o Exercises 1. What is the head of a symbol? 2. Analyze the structure of the following equation: x



I

I

[t]

+ a x

I

+ x [t]

[t]

== 0

2.1.2 Working with Parts of Expressions

We know many list operations (see Section 1.6.3). Many of them can also be applied to expressions. In{1j."=

expr = 1 + x + x"2

In[2}:=

Part [expr, 1]

Out[2}=

1 + x + x

In[3}:=

Append [expr, 0]

Out[3}=

1 + x + x

-

Sin [z]

a;

2 Sin[z]

2

-

Sin[z] -- a -- 0

Posi tion returns the position of a subexpression or a pattern (see Chapter 2.2). In[4}:=

position [expr, x]

Out[4}=

{ { 1,

2},

{ 1, 3, 1 } }

It treats the expression like a nested list. The tree form shows this more clearly: In[S]:=

TreeForm [expr]

Out[S]I/TreeForm=

Equal

[I

,

Plus[l, x,

, Power [x, 2]

I Times[-l,

a]

]

]

Sin[z]

The search can be restricted to certain levels of the "tree". The methods for specifying such levels are similar for all functions which accept levels: A number n means all levels 1 through n, {n} the level n only, {n I' n2} the levels n 1 through n2, and Infini ty all levels.

232

2. Structure

In[6}:=

position [expr, x,

Out[6}=

{ { 1,

MapAt

3,

{3} 1

1} }

can be used, for instance, to apply a function at this position (see Sec-

tion 1.6.2): In[?]:=

MapAt [Cos, expr, {1, 3, 1} 1

Oulfn=

1 + x + Cos[x]2 - Sin[z]

o

==

a

Summary

Expression

Meaning

Depth [expr]

the maximum number of indices needed to specify a part of expr, plus one

Level

[expr, levelspec]

the partial expression on a given level; Table 2-4 shows the possible level specifications levelspec

Posi tion [expr, pattern] Posi tion [expr, pattern, [evelspec]

the positions on which the pattern is found the positions on the level(s) levelspec, at which

pattern is found MapAt [f,

expr, n]

apply fto the element at position n (n can be a list, to denote the position in a nested expression)

Table 2-3: The structure of expressions Expression

Meaning

n

the levels 1 through n

In}

the level n, only

In], n2}

the levels n] through n2

Infinity

all levels

Table 2-4: The specification of levels

o

Exercise

1. Find at least two ways to replace the Sin by a Cos in:

f[l + Sin[x A 2]]

2.2 Patterns

233

• 2.2 Patterns In order to easily handle mathematical objects, one has to be able to specify not only single symbols, but also whole classes of expressions. In Mathematica, this is done with patterns.



2.2.1 Simple Patterns

The basic element of a pattern is the blank _. It stands for "anything". We might give the "anything" a name. For instance, x_ denotes it with the name x. The left hand sides of transformation rules lhs - > rhs (or lhs : > rhs, see Section 2.3.1) and of definitions lhs = rhs or lhs : = rhs are treated as patterns.

o

Patterns in Transformation Rules

We can replace z by a in the following expression: In[1]:=

expr = 1 + y"2 + y"3 + z"2 + y"2 Sin[z];

In[2]:=

expr I. z - > a

Out[2]=

1 + a 2 + y2 + y3 + y2 Sin [al

Maybe, the bases of all squares should be replaced by a. To achieve this, we set up a rule for the pattern "anything squared". It is not even necessary to give the "anything" a name. In[3]:=

expr /. _ "2 -> a"2

Ouq~=

1 + 2 a 2 + y3 + a 2 Sin[z]

If all powers have to be replaced by the corresponding powers of a, we use the following pattern: It is necessary to give the degree of the power the name n here, because it appears on the right hand side of the rule.

234

2. Structure

In[4}:=

expr /.

Oulf~= 1

An_

- > a An

+ 2 a 2 + a 3 + a 2 Sin[z]

We might also define a pattern for a sum: In[5}:=

expr /. yAn_ + yAm_ -> f [n, m]

Oulf~=

1 + z2 + f[3, 2] + y2 Sin[z]

o

Patterns in Function Definitions

Afunction of the form

is, in our new terminology, a definition, which evaluates expressions matching the pattern f [anything]. Usually, the anything has to be given a name (in our case x), which can be used on the right-hand side. In[6}:=

f [x_]

In[7]:=

f [a]

Out[7}=

a2

: = XA 2

Even in definitions of the form g[x]

or g [x]

= ...

the left-hand side g [x] is a pattern-but a very restrictive one, it does not contain any freedom and only matches exactly g [x] . In[B]:=

9 [x]

In[9}:=

g[a]

Out[9}=

g[a]

In[10}:=

g[x]

Out[10}= x

:= xA2

2

Another example is a function which only evaluates when two identical arguments are given. The corresponding pattern uses the same name twice:

2.2 Patterns

In[12}:=

h [1 , 2 ]

Out[12}= h [1, In[13}:=

235

2]

h [a, a]

Out[13}= k [aJ

o

Searching Patterns

Several functions find given patterns in an expression. We already have met one of them, Po sit i on, in Section 2.1.2: In[14}:=

position [expr, _ A2]

Out[14}= {{ 2 },

{ 4 },

{ 5,

1 }}

The function Count counts the elements that match a pattern in a list. In[15}:=

Count [{a, b A 2, c A 3, 1},

_A_]

Out[15}= 2

If we use it on a general expression, a level has to be specified for the search (see Table 2-4 on page 232)-otherwise, only the top level is taken into account. In[16):=

Count [expr, _ A2]

Out[16}= 2 In[17}:=

Count [expr, _ A2, Infinity]

Out[17}= 3

Cases works in an analogous manner to Count. It lists the subexpressions matching a given pattern. In[1B}:=

Cases[{a, b A 2, c A 3, 1},

Out[1B}= {b 2 , In[19]:=

_A_]

c3}

Cases [expr, _ A2, Infinity]

Oulf1~= {y2, z2, y2}

We can even give it a rule, to replace these subexpressions by something else.

236

2. Structure

In[20}:=

Cases [expr,

OUlf20= {2,

An_ -> n, Infinity]

3, 2, 2}

DeleteCases deletes the parts of an expression that match a pattern. Its syntax is analogous to Cases, i.e., only the first level is searched, if not otherwise specified. In[21]:=

DeleteCases [expr, _ A_]

Out[21}= 1 + y2 Sin [z 1 In[22]:=

DeleteCases[expr,

Oulf2~=

1 + Sin[zl

-

A

-, Infinity]

We may need to find subexpressions which cannot easily be specified with a pattern. In such cases, the function Select can help. It is usually applied to lists and returns a list of the elements which pass a test, i.e., the test returns True. The test function can be built-in (e.g., NumberQ) or self-defined (e.g., the pure function # rhs

Cases [expr, pattern, levelspec]

the elements on a given level (see Table 2-4) of an expression that match pattern

DeleteCases [expr, pattern]

delete all elements matching pattern

DeleteCases [expr, pattern, levelspec]

delete all elements on a given level (see Table 2-4), matching pattern

position [expr, pattern]

list the positions of all objects matching pattern

position [expr, pattern, levelspec]

list the positions of objects on levelspec (see Table 2-4), matching pattern

Select [list, crit]

list the elements for which the test crit returns True

Select [list, crit, n]

list the first n elements for which crit returns True

Table 2-6: Patterns in lists and other expressions

D

Exercises

1. Expand (a + b + c)lO and consider the resulting expression. Delete all addends which contain a and some power of b (except b itself). In the resulting expression, find all addends containing b5 . 2. Generate a table of 1000 random integers between 1 and 10000. Construct the list of primes appearing in the table.



2.2.2 Restricted Patterns

One often wants to restrict a pattern with certain conditions, especially for function definitions. We have met an example for this in Section 1.6.3, where the definition of the cross product had to be restricted to vectors of length three, with a condition of the form definition /; condition.

2. Structure

238 In[1]:=

W

cross [u_, v _] : = RotateLeft[u RotateLeft[v] - RotateLeft[u] v] VectorQ[u] && VectorQ[v] && Length[u] == 3 && Length[v] == 3

/;

Notice that this kind of restriction only makes sense for delayed definitions with: = (and delayed rules with : >, see Section 2.3.1), because = (and -» would immediately evaluate their right-hand sides. A pattern itself can be restricted with a condition, using / ; . In{2]:=

t1 [a_ /; a > 2, b -

In{3]:=

t1 [1, 9]

Out{3]=

t1 [1,

In{4]:=

t1[3, 9]

Out{4]=

c

/; b > 3]

.-

c

9]

In this case, the equivalent fonn In{5]:=

t2 [a_, b_]

:=

C

/;

a > 2 && b > 3

probably is easier to read. If the condition would mix a and b, only the fonn In{5]:= could work.

Another way of restricting patterns is by specifying a head (Integer, Real, Complex, Symbol, List, etc.). We write the head directly after the blank (e.g., x_ Integer). The following function only evaluates lists and selects all the elements which are greater or equal to one: In{6]:=

selectGreaterOne [v_List]

. - Select [v, #>1&]

In{7]:=

selectGreaterOne [a + 2]

Oulf~=

selectGreaterOne[2 + al

In{8]:=

selectGreaterOne[{l, 2, a, 3}]

Out{8]=

{ 2,

3}

A third form of restriction is by using test functions, which are applied to the candidates. The syntax for this is: pattern ? test

239

2.2 Patterns

Such a pattern only matches expressions, for which the function test returns the value True. The function test cannot contain named parts of the pattern (as in / ;), but sometimes, it gives clearer conditions.

We can use built-in or self-defined test functions. In[9]::

div2 [n_ ?EvenQ]

In[10]::

div2[3]

: = n/2

Out[10]: div2[3] In[11]::

div2[4]

Out[11]: 2 In[12]::

fac [n_? (# > 0 && IntegerQ[#]&)]

In[13]::

fac [-1]

:= n!

Out[13]: fac[-l] In[14]::

fac [10]

Out[14]: 3628800 In[15]::

multAdd[{x_List, y_List} ? MatrixQ]

In[16]::

multAdd[{{l, 2},

Out[16]: multAdd [ { {1, In[17]::

2},

mul tAdd [ { {1, 2},

Out[17]: {11,

{4,

.- {x • y, x + y}

{3, 4, 5}}]

{3, 4, 5}}] {3,

4}}]

6}}

Mathematica contains a lot of functions which are useful for tests. Their name ends with a Q. In[18]::

?*Q

AtomQ DigitQ Ell ipticNomeQ EvenQ FreeQ HypergeometricPFQ IntegerQ IntervalMemberQ LegendreQ LetterQ

ListQ LowerCaseQ MachineNumberQ MatchLocalNameQ MatchQ MatrixQ MemberQ NameQ NumberQ OddQ

PartitionsQ PolynomialQ PrimeQ SameQ StringMatchQ StringQ SyntaxQ TrueQ UnsameQ UpperCaseQ

240

2. Structure LinkConnectedQ LinkReadyQ

OptionQ OrderedQ

ValueQ VectorQ

They have the common property of always returning True or False; if the result is not clear, they return False. That is in contrast to Positive, Negative, and NonNegati ve. These functions can remain unevaluated. In[19):=

NwnberQ [a]

Out[19)= False In[20):=

Positive I@ {-1, a, 1}

Oulf2~=

{False, positive[al, True}

We can use TrueQ to construct a test which returns False, if it cannot be decided with the current knowledge. In[21):=

TrueQ [Positive [#] ]& I@ {-1, a, 1}

Out[21)= {False,

False, True}

For equalities or inequalities, we have the predefined functions SameQ [x, y] or UnsameQ [x, y] . They are equivalent to TrueQ [x == y] or TrueQ [x ! = y] , and can be abbreviated by x === y or x =! = y. In[22):=

a == 1

Out[22)= a In[23):=

1

a --- 1

Out[23)= False

o

Summary Expression

Meaning

pattern Ii condition a pattern that only matches if condition returns True rule Ii condition

a (delayed) rule that only matches if condition returns True

Table 2-7: Patterns and rules with restrictions

241

2.2 Patterns

Pattern

Meaning

x_head

a pattern for expressions with a given head

x_Integer

a pattern for integers

x_Real

a pattern for approximate numbers

x_Complex

a pattern for complex numbers

x_Rational a pattern for rational numbers

Table 2-8: Patterns for special heads Expression

Result

SameQ[x, y] x === y

True if x andy are identical expressions, otherwise False

UnsameQ[x, y] x =!= y

True if x andy are not identical, otherwise False

NumberQ [expr]

True if expr is some kind of a number, otherwise False

IntegerQ [expr]

True if expr is an integer, otherwise False

EvenQ [expr]

True if expr is an even integer, otherwise False

OddQ[expr]

True if expr is an odd integer, otherwise False

PrimeQ [expr]

True if expr is a prime, otherwise False (actually, a probabilistic algorithm is used)

VectorQ [expr]

True if expr is a vector, otherwise False

VectorQ [expr, test]

True if expr is a vector and test returns True for all elements, otherwise Fa 1 s e

MatrixQ [expr]

True if expr is a matrix, otherwise False

MatrixQ [expr, test]

True if expr is a matrix and test returns T rue for all elements, otherwise False

PolynomialQ [expr, {xl' x2' ... } ]

True if expr is a polynomial inxl' x2, otherwise False

OrderedQ [ {xl' x2'

... } ]

True if xl, x2, ... are in standard order, otherwise False

MernberQ [list, pattern]

True if pattern matches an element of list, otherwise False

MernberQ [expr , pattern, levelspec]

True if pattern matches an element of list on the levels levelspec (see Table 2-4 on page 232), otherwise False

FreeQ [expr , pattern]

True if pattern does not match any part of expr, otherwise False

Table 2-9: Some test functions which always return True or False

242

2. Structure

Expression

Result

FreeQ [expr, pattern,

T rue if pattern does not match any part of expr on the levels levelspec (see Table 2-4), otherwise False

levelspec]

Ma tchQ [expr , pattern]

True if pattern matches expr, otherwise False

ValueQ [expr]

True if a value has been defined for expr, otherwise False

AtomQ [expr]

True if expr does not contain sUbexpressions, otherwise False

Table 2-9: Some test functions which always return True or False Expression

Meaning

positive [x]

True for a positive number, False for a negative number or zero

Negative [x]

True for a negative number, False for a positive number or zero

NonNegative [x]

True for a positive number or zero, False for a negative number

Table 2-10: Test functions which do not always evaluate

o

Exercises

1. Rewrite the function cross (see In[1]:=), such that the arguments are tested on the left-hand side of the definition. Are there other solutions?

2. Find different definitions for a function, which returns True exactly when evaluated for a list of three real numbers whose squares sum up to less than one. 3. Calculate MemberQ [{x, xAn} FreeQ.



I

nl and explain the result. Compare to

2.2.3 More Complicated Patterns

Pattern matching is one of the most important tools for mathematical programming. Mathematica knows many ways of defining complicated patterns in simple ways.

243

2.2 Patterns

o

Naming Parts of Patterns

We can define a named pattern by writing:

x:pattern The name can then be used, for instance, on the right-hand side of a transformation rule. In[1]:=

{a, b, Sin[al, Sin[bl} I. x:Sin[_l

Out[1]=

{a, b, p[Sin[a]2], p[Sin[b]2]}

-> p[xA21

If two parts of a pattern have the same name, they must be identical. This allows us to define constraints in an elegant way. In[2]:=

{f[h[l], h[21]' f[h[l], h[l]]} I. f[x:h[_], x_l

Out[2]=

{ f [h [1],

o

-> x

h [ 2 ] ], h [1] }

Complex and Rational Numbers

Complex and rational numbers have a special format. In[3]:=

FullForm [1 - 11

Out[3]IIFuIlForm= Complex[1, In[4]:=

-1]

Full Form [2! 31

Out[4]IIFuIlForm= Rational [2,

3]

It is therefore necessary to identify the real and imaginary parts with a pattern of the form Complex [a_, b_l. In[5]:=

1 -

I I. Complex [a_, b_l -> {a, b}

Out[5]=

{ 1,

-1 }

Similarly, Rational [a_ , b_l returns the numerator and the denominator of a rational number. In[6]:=

2/3 I. Rational [a_, b_l

Out[6]=

{ 2,

3}

-> {a, b}

244

o

2. Structure

Alternatives for Patterns

We can use the "or" operator natives.

I to define patterns consisting of two or more alter-

In[?]:=

x + xA2 + x A3 + y

Out[?]=

3 c + y

/. x

I XA

-> c

Another example could be the following definition:

In[9]:=

{d[a b], d[a + b], d[a]}

Out[9]=

{ da,

da , d [ a 1 }

Neither of the two alternatives matches a itself. In the next subsection, we will learn how this special case can be included without the need to add a new alternative.

o

Optional Arguments, Default Values

Mathematica identifies patterns by their structure (FullForm), and not by their mathematical content. But many mathematical rules contain special cases, which lead to different patterns. Let us look at: In[10]:=

add [x_, y_]

:= x

+ y

This function shall also be evaluated for a single argument. What happens with our definition in such a case? In[11]:=

add [a]

Out[11]= add [a 1

Here, it is useful to define optional arguments, by writing the default value behind a colon In[12]:=

add[x_, y_:O]

In[13]:=

add [a]

Out[13]= a

.- x + y

2.2 Patterns

245

Sums, products, and powers already have the predefined default values of 0,1, and 1 for optional arguments. They can be activated by writing a dot after the blank. Our next example shows that a missing addend is replaced by its default value of 0: + y _]

In[14}:=

s [x_.

In[15}:=

s [a + b]

Out[15}= mySurn [a, In[16]:=

b

•-

mySum [x,

y]

1

s [a]

Out[16}= mySurn [ 0,

a1

This allows us, for instance, to extract the coefficients of a linear function.

In[18]:=

lin[x + 1, x]

Out[18}= {1,

1}

The default value of 1 was used for a here. The next example replaces a missing b by 0: In[19}:=

lin [x, x]

Out[19}= {1,

o

O}

Variable Numbers of Arguments, Functions with Optional Arguments

We can combine a variable number of arguments into a pattern. Two blanks C _ or x __ ) stand for one or more arguments. : = {x}

In[20}:=

makeList [x__ ]

In[21}:=

makeList [a, b, c]

Out[21}= {a,

b, c}

Three blanks

C __ or x___ ) can be used for zero or more arguments.

Many built-in functions, for instance the graphics functions, allow a variable number of options. These (zero or more) optional arguments have to be put at the end of the parameter list, to avoid ambiguities.

246

2. Structure

The options are passed in the form option -> value. According to a convention in Mathematica, the default values for options (e.g., the options of a functionJ) are assigned to Options [j] .

=

{optl -> defl, opt2 -> def2}

In[22}:=

Options [fwithOpts]

Oulf2~=

{optl -> defl, opt2 -> def2}

We can now use expressions like name /.

{opts} /. Options [f]

to extract the values of the options-the rules are evaluated from left to right. In[23}:=

opt! /. Options [fWithOpts]

Out[23}= de fl In[24]:=

opt! /. opt! -> 3 /. Options [fWithOpts]

Out[24}= 3

This allows us, for instance, to define a function which returns the argument and the values of the options as a list: In[25}:=

fWithOpts [x_, opts ___ ?OptionQ] : = {x, optl, opt2} /. Flatten[{opts}] /. Options[fWithOpts]

This version (thanks to Leszek Sczaniecki from WRI) uses OptionQ to test for appropriate rules. It also works with possibly nested lists of options. In[26}:=

fWithOpts [a]

Oulf2~=

{a, defl, def2}

In[27}:=

fWithOpts [a, opt2 -> q]

Out[27}= {a,

o

defl, q}

Repeated Patterns

Patterns can as well be repeated, by writing two dots ( .. ) for a pattern repeated once or more times, and three dots ( ... ) for zero or more repetitions. This makes it easy to define patterns which consist of several copies of the same subpattern. This should be distinguished from patterns of the form x__ , where general sequences of arguments are allowed.

The following function j generates a list of its arguments, provided that all of them match the pattern h [_ ] .

2.2 Patterns

247 := {x}

In[28]:=

j[x:h[_] •• ]

In[29]:=

j[h[l], h[2], h[S]]

Out[29]= {h [1], In[30]:=

h [2],

h [5] }

j [h [1], h)

Out[30]= j [h [1],

h]

It is possible to use alternatives in repeated patterns. In[31]:=

Cases [(f [a], f [a, b, a], f [a, b, c)}, f [(a I b) .• ]]

Out[31]= {f [aJ,

o

f [a, b, a]}

Summary Pattern

Meaning

Complex [x_ , y-]

a complex number x + iy

Rational [x_ , y-]

a rational number x/y

Table 2-11: Special patterns Pattern

Meaning

x_

any single expression, to be named x

x_h

any expression with head h, to be named x

x:pattern

an expression to be named x, matching pattern

pattI

I

patt2

...

a pattern that can be written in different forms; alternatives

x_ :v

an expression (to be named x); if omitted, it is replaced by v

x_h:v

an expression with head h; if omitted, it is replaced by v

x_

an expression with a built-in default value (see below)

x_ + y-.

the default value for y is 0

x_ y- .

the default value for y is 1

x_ "y_ .

the default value for y is 1

--

a sequence of one or more arguments

x __

a sequence of one or more arguments, to be named x

x __ h

a sequence of one or more arguments with heads h, to be named x

Table 2-12: Different types of patterns

248

2. Structure

Pattern

Meaning

--x ___

a sequence of zero or more arguments

x___ h

a sequence of zero or more arguments with heads h, to be named x

expr ..

an expression or pattern is repeated one or more times

expr . ..

an expression or pattern is repeated zero or more times

a sequence of zero or more arguments, to be named x

Table 2-12: Different types of patterns

o

Exercises

1. Write the definition

d[a x_

I

a

+

x_J

:=

da

in such a way that it also evaluates for a alone. 2. For each of the following "types" of arguments, define a function which only evaluates for the given "type" and returns the input as the result: • any numbers, • approximate numbers, • lists, • vectors (without sublists), • vectors consisting of numbers, • lists of lists. 3. Define a function which returns the list of the coefficients of quadratic polynomials in a given variable. Compare to the built-in function CoefficientList.



2.2.4 Example: A Simple Integrator

Mathematical handbooks, such as integration tables, contain many rules, which are applicable for certain types of mathematical expressions, only. By using patterns, such rules can easily be implemented in Mathematica: One only has to write down definitions, which apply to the selected pattern and return the desired result. It is no problem to define functions which do different things on different types of

249

2.2 Patterns

input, because Mathematica automatically selects the right definition, when it evaluates an expression containing the head of the function (see Section 2.3.2 for more details). Let us, for instance, set up a little integration function mylntegrate (see [Wo19l], Section 2.3.13), by collecting definitions which apply to certain patterns. As a start, we set two definitions for linearity. In[1}:=

myIntegrate [y_ + z_, x_ 1 : = myIntegrate[y, xl + myIntegrate[z, xl

In[2]:=

myIntegrate [c_ y _, x_ 1 : = c myIntegrate [y, xl /; FreeQ[c, xl

The integral of a constant or an integer power of the variable (except -1) can be written as: In[3]:=

myIntegrate[c_, xl

In[4]:=

myIntegrate[x_"n_o, x_l FreeQ[n, xl && n != -1

:=

c x /; FreeQ[c, xl 0-

x"(n+1)/(n+1) /;

These definitions already allow the integration of a polynomial. In[S}:=

myIntegrate[a x"2 + b x + c + l/x, xl

Out[S]=

c x +

b x2

-2--

+

a x3

-3--

+

mYlntegrate[~, xl

Functions like 1 Ix cannot be integrated yet. This is not disturbing, because the corresponding term is simply returned in its unevaluated form. Let us add one more rule. In[6]:=

myIntegrate [11 (a_ 0 x_ + b_ 0), x_ 1 0Log[a x + bl/a I; FreeQ[{a, b}, xl

This gives: In[7}:=

myIntegrate[a x"2 + b x + c + l/x, xl

Out[7]=

c x +

b x2

-2--

+

a x3

-3--

+ Log[xl

250

2. Structure

Mathematica itself (Versions 2.0 and higher) uses a completely different method for integration-basically, the Risch algorithm ([Ris68]).

o Exercise 1. Extend the above integrator by some more rules.

251

2.3 Transformation Rules and Definitions

• 2.3 Transformation Rules and Definitions We now use patterns for the construction of transformation rules and definitions. They are used to transform expressions in the desired way.



2.3.1 Transformation Rules

o

The Simplest Use of Transformation Rules

We have seen several times that a transformation rule can be applied to an expression by writing expr /. lhs -> rhs

or expr /.

{lhs 1 -> rhs 1 , Ihs 2 -> rhs 2 ,

.•• }

(see Section 1.4.1). In[1]:=

expr = x"2 + y"2

Out[1]=

x

In[2]:=

rule1

Outf2]=

{x -> 1, Y -> 2}

In[3]:=

expr /

Outf3]=

5

2

2

+ Y

{x -> 1, y -> 2}

. rule1

We can even apply a nested list of transformation rules. In such a case, the results of applying the different transformation rules to the expression is returned. In[4]:=

rule2 = {x -> 2, y -> 2}

Ouq~=

{x -> 2, Y -> 2}

In[5]:=

expr /. {rule1, rule2}

Out[5]=

{ 5,

8}

252

o

2. Structure

Multiple Evaluation of Transformation Rules

When evaluating an expression of the form expr /.

{lhs 1 -> rhs 11 Ihs 2 -> rhs 21

... }

Mathematica tries to use the rules Ihs j -> rhsj (from the left to the right) on the parts of expr. As soon as a pattern Ihs j matches a part, the transformation is performed and the next part of expr is considered. Every rule is tried only once on each part of the expression. In[6}:=

expr I.

Out[6}=

b 2 + (a + y) 2

{x ->

(y

+ a)

Y -> b}

I

Maybe the rule for y should also be applied for (a + y) /\ 2. We can achieve this by chaining the rules. In[7}:=

expr I. x - > (Y + a)

Out[7}=

b 2 + (a + b) 2

I. Y - > b

This is complicated, and often not easy in large expression. But Mathematica also has a / / . operator, which applies a transformation rule repeatedly, until nothing changes anymore. In[B]:=

expr I I.

Out[B}=

b 2 + (a + b) 2

{x ->

(y

+ a)

1

y

-> b}

Because the left-hand sides of transformation rules can be general patterns, we are able to calculate factorials by multiple evaluations of transformation rules. In[9}:=

fac[5]

Out[9}=

120

II. {fac[O] -> 1, fac[n_] -> n fac[n-1]}

Of course, the opposite sequence of rules does not work. In[10}:=

fac[5]

II. {fac[n_] -> n fac[n-1], fac[O] ->

Out[10}= 0

The value 0 matches both patterns, and the first one is chosen.

1}

2.3 Transformation Rules and Definitions

o

253

Optimization

Large lists of transfonnation rules (lhs - > rhs) can be converted into an optimized fonn, a dispatch table, by using the Dispatch function. This makes the evaluation much more efficient. In[11}:=

rules = Table [s [i] -> Sin [i],

In[12}:=

dispRules

In[13}:=

s[6000]

Oulf1~=

{l.OS Second, Sin[6000]}

In[14}:=

s[6000]

= Dispatch [rules] ;

/. rules // Timing

/. dispRules // Timing

Out[14}= {O. 4 Second,

o

{i, 10000}];

Sin [6000] }

Delayed Transformation Rules

The right-hand side of an immediate transfonnation rule (with -» is evaluated when the rule is defined. In[15}:=

immRule

Out[15}=

x_ -> x

x_ - > Expand [x]

If we want to apply it to a factored polynomial, it will not change anything, because the evaluation of the right-hand side already has been done in Out[15]=, with the result x. In[16]:=

(a + b) A2 /. immRule

Out[16}=

(a

+ b) 2

To achieve the expansion, the evaluation of the right-hand side of the rule must be delayed until the rule is applied. This is what a delayed transformation rule of the fonn lhs : > rhs does. delRule = x - : > Expand [x] Out[17}= x - :> Expand [x] In[17}:=

In[1B}:=

(a + b) A2 /. delRule

Out[1B}= a

2

+ 2 a b + b2

254

o

2. Structure

Summary

Expression

Short Form

Meaning

Rule [lhs, rhs]

lhs -> rhs

an immediate transformation rule, transforming lhs into rhs

RuleDelayed[ lhs, rhs]

lhs : > rhs

a delayed transformation rule, transforming lhs into rhs, where rhs is evaluated when the rule is applied

ReplaceAll [expr, rule]

expr I. rule

apply a (simple) transformation rule to the expression expr

ReplaceAll [expr, {rule], rule2' ... } ]

expr I. {rule] , rule2'

ReplaceAll [expr, {rules], rules2' ... } ]

expr I. {rules], rules2'

... }

apply several transformation rules return the list of the results of apply-

... } ing the (lists of simple) transformation rules rules], rules2' ...

ReplaceRepeated[ expr, rule]

expr II. rule

apply the rules several times, until nothing is change anymore apply the rule to the entire expression

Replace [expr, rule]

Table 2-13: Defining and applying transformation rules Expression

Meaning

Dispatch [{lhs] -> rhs] , Ihs 2 -> rhs 2 , ... } ]

generate an optimized form (dispatch table) of a list of (simple) transformation rules

Table 2-14: Optimizing transformation rules

o

Exercises

1. Use a directly applied transformation rule to calculate the tenth Fibonacci number.

The corresponding recursion is defined by: fib(O)

= fib(1) = 1, fib(n) = fib(n-l) + fib(n-2).

2. Study the difference between / . and Replace (see Table 2-13).

2.3 Transformation Rules and Definitions



255

2.3.2 Definitions

Definitions are rules, which not only are applicable to single expressions, but are defined for the remainder of a Mathematica session-or until they are cleared "by hand". They are applied whenever the pattern on their left-hand side matches an expreSSIOn. Just as for transformation rules, definitions can be immediate or delayed.

o

Immediate and Delayed Definitions

The correspondence between transformation rules (with -> or : » on the one hand, and definitions (with = or : =) on the other, is basically very simple: • lhs = rhs means: The rule lhs - > rhs shall be applied whenever the pattern lhs matches. • lhs : = rhs means: The rule lhs : > rhs shall be applied whenever the pattern lhs matches.

There are some more subtle differences in the evaluation of transformation rules and definitions, which will be discussed in Subsection "Patterns, Transformation Rules, and Definitions" on page 274. Apart from these differences, definitions (with = or : =) just set up permanent transformation rules for certain patterns. They are used until they are cleared (with Clear) or until the session ends. 1&

During a long session, one might forget that definitions have already been set for some symbol or pattern. This can lead to irritating results. Therefore, it is a good habit to use definitions only when they are meant to be final. Before that, for instance for testing the effect of definitions, it is better to use transformation rules (- > and : ». Because of the above correspondence, the transformation rules can easily be used to tryout a definition on selected expressions. A second security measure is to use distinct and self-explanatory names for all objects.

When reading a definition of the form lhs = rhs, Mathematica evaluates rhs. Thereafter, the result is substituted wherever the pattern lhs matches. The left-hand side might be a specific expression (e.g., x = value or f [xl = value) or a more general pattern (e.g., f [x_l = value). The first case only applies to the symbol x or the expression f [x 1 , the second transforms anything matching f [_ 1 . In[1}:=

demol [xl = x

Out[1}=

x

256

2. Structure

In[2]:=

{demol [x], demol [y] }

Out[2]=

{x, dernol [y] }

In[3]:=

demo2 [x_] = x

Out[3]=

x

In[4]:=

{demo2 [x], demo2 [y] }

Out[4]=

{x, y}

As soon as the right-hand side contains calculations, the immediate definition can pose problems. In[5]:=

demo3 [x_]

Expand [x]

Out[5]=

x

In[6]:=

demo3 [ (a+b) A2]

Out[6]=

(a + b) 2

For such cases, the delayed definition lhs : = rhs has to be used. Its right-hand side is evaluated when the definition is applied. : = Expand [x]

In[7]:=

demo4 [x_]

In[B]:=

demo4 [(a+b) A2]

Out[B]=

a2 + 2 a b + b2

We can use delayed definitions for "simple assignments" as well. Let us look at the following example, as a final word about the difference between = and : =. In[9]:=

b = 1

Out[9]=

1

(b has the value 1) In[10]:=

a := b

(a does no yet have a value) In[11]:=

b = 2

Out[11]= 2

(b has the value 2)

2.3 Transformation Rules and Definitions In[12}:=

257

a

Out[12}= 2

(a is evaluated according to the current value of b)

This is in contrast to: In[13}:=

b

=

1

Out[13}= 1

(b has the value 1) In[14}:=

a = b

Out[14}= 1

(a is evaluated according to the current value ofb, which is 1) In[15}:=

b = 2

Out[15}= 2

(b has the value 2) In[16}:=

a

Out[16}= 1

(a still has the same value)

Within nested evaluations, the difference between immediate and delayed definitions can dramatically effect the efficiency (see Exercise 2). It therefore is essential to really think about what the right type of definition is-instead of, for instance, just using delayed definitions every time.

o

The Order of Evaluation

The following two lines define a program f ac for the factorials: : = n fac [n-l]

In[17}:=

fac [n_]

In[18]:=

fac [0] = 1

Out[18}= 1

258

2. Structure

The second definition is set immediately, because fae [0] shall evaluate to the value 1. The first definition, in contrast, needs a : =, since the right side has to be evaluated several times, each time for the current value of n. In[19]:=

fac [100]

Oulf1~=

9332621544394415268169923885626670049071596826438162146\ 85929638952175999932299156089414639761565182862536979\ 20827223758251185210916864000000000000000000000000

When evaluating this expression, Mathematica does the following: It checks, which definitions and rules are applicable for fac [100]. The second one surely is not, but the one first is. Therefore, 100 is filled into the pattern n_ and used as n on the right -hand side. The result of this evaluation is 100 f ac [ 9 9 ] . Again, all definitions are tested for f ac [ 9 9]-and again, the first one matches. This process is repeated until the first definition matches fac [0] and finishes the recursion.

The important point is that Mathematica uses specific rules (in our case: the second) before more general rules (in our case: the first). This assures that the recursion terminates--even though the sequence of setting the definitions was opposite. We can use??f to look at the definitions for f. They are printed in the order used for pattern matching. In[20]:=

??fac Global'fac fac [0] fac[n_]

lIE

=

1 :=

n*fac[n - 1]

Mathematica tries to use specific rules before general rules.

Rules on the same level of generality are treated in the same order as they were set. We can use DownVal ues to change this order "by hand" (see Table 2-17).

D

Definitions with Memory

A definition of the form j[x_]

: = f[x]

= rhs

saves all values off which are calculated. The next time such a value is used, it does not have to be recomputed.

259

2.3 Transformation Rules and Definitions

For the factorials, this looks as follows: : = facFast [n]

In[21}:=

facFast [n_]

In[22}:=

facFast [0] = 1

=n

facFast [n-1]

Out[22}= 1

It does not make a difference when called for the first time: In[23}:=

facFast [10]

Ouq2~=

{0.266667 Second, 3628800}

/ / Timing

But now, all factorials up to 10 are registered: In[24}:=

??facFast

Global'facFast facFast[O] 1 facFast[l] 1 facFast[2] 2 facFast[3] 6 facFast[4] 24 facFast[5] 120 facFast[6] 720 facFast[7] 5040 facFast[8] 40320 facFast[9] 362880 facFast[10] = 3628800 facFast[n_] := facFast[n] = n*facFast[n - 1]

Therefore, their calculation is much faster from now on. In[25}:=

facFast [10]

/ / Timing

Ouq2~=

{0.05 Second, 3628800}

This method can be useful when calculating values for the first time-for instance, if the algorithm passes certain values several times, as in a recursive program for the Fibonacci numbers (see Exercise 1). Of course, we have to pay for the speedup by an increased usage of memory.

o

Associated Definitions

Definitions of the form

260

2. Structure

or f [g [x_]]

= ...

are associated to the symbol f ("downvalue" of f). We might want to associate them to the symbol g ("upvalue" of g), for instance, if f is a built-in function. We already know the corresponding syntax from Section 1.8.2. There, we have declared the symbol r as real, by writing: In[26}:=

r

/:

1m [r]

= 0

Out[26}= 0

There is a shortcut for this: In[27]:=

1m [r]

"=

0

Out[27}= 0

It automatically associates the definition with the argument on its left-hand side. In[28]:=

?r

Global'r 1m [rJ

"= 0

This works for delayed definitions in an analogous manner: In[29]:=

Integrate [g [x_l, x_]

In[30]:=

Integrate [g [t], t]

Out[30}= gint [t,

": = gint [x, xl

t J

In Section 3.1.6, we will see that such associated definitions can be used for object oriented programs.

o

Changing Built-in Functions

It might be necessary to change built-injunctions. This should only be done after careful consideration, and if other ways, for instance associated definitions, do not work. Let us try the following definition:

261

2.3 Transformation Rules and Definitions In[31}:=

Re [x_]

:

=

x

1m [x]

/;

==

0

SetDelayed: :write: Tag Re in Re[x_l is Protected. Out[31}= $Failed

Mathematica does not want us to change its built-in function Re. But we can override this security measure by using Unprotect. In[32}:=

Unprotect [Re]

Out[32}= {Re } In[33}:=

Re [x_l

:

=

x

1m [x]

/;

==

0

Of course, the function should be protected again: In[34}:=

Protect [Re]

Out[34}= {Re}

The real part can now be evaluated for our symbol r, which has been declared real in the last subsection. In[35}:=

Re [r]

Out[35}= r In[36}:=

? ?Re

Re[zl gives the real part of the complex number z. Attributes [Rel = {Listable, Protected} Re [x_l : = x /; 1m [xl == 0

o

Summary

• Specific rules and definitions are used before more general ones. Expression

Short Form

Set [lhs, rhsl

lhs

=

SetDelayed [lhs, rhsl

lhs

.-

j[x_l

Meaning

rhs

evaluate rhs and, thereafter, always replace the pattern lhs by this value

rhs

: = j[xl =

always replace the pattern lhs by the value of rhs, which is recalculated every time rhs

save all calculated values of f [xl

Table 2-15: Definitions

262

2. Structure

Expression

Short Form

Clear [x, y, ... J

x

g /: f[g [argsJJ

= rhs

g /: f[g [argsJJ

.-

= .,

y

Meaning

= . , ...

f[g [argsJJ "'- rhs

rhs f[g [argsJJ A:= rhs g [argj, arg2, ... J "'_ rhs

clear the definitions of x, y, ... associate the definition to g (instead off) associate the delayed definition to g associate the definition to all heads of argj, arg2, ...

Table 2-15: Definitions Expression Unprotect Protect

Meaning [Sj,

[Sj'

s2 '

s2 '

... J

... J

remove the protection (attribute Protected) of the symboIs Sj, s2, ... protect the symbols Sj, s2, ... (set the attribute Protected)

Table 2-16: Protecting and unprotecting symbols Expression

Meaning

DownValues [j]

return the list of "downvalues" off (rules for patterns which contain f as their head)

UpValues [fJ

return the list of "upvalues" off (rules which do not contain f as their top level head)

DownVal ues [fJ UpValues [j]

= rules

= rules

directly define the "downvalues" off directly define the "upvalues" off

Table 2-17: Detailed control over the order of definitions

o

Exercises

1. Define two functions which calculate the Fibonacci numbers (see Exercise 1 on page 254). The first one shall save the calculated values, the second one shall not do that. Compare the CPU timings of these two functions. 2. Explain: D[Sin[l/x] "2,

In[1]:=

y

In[2]:=

z:= D[Sin[1/x]"2,

{x, lO}]; {x, lO}];

263

2.3 Transformation Rules and Definitions

t.

x -> i ,

In[3]:=

Timing[Table[y

Oulf~=

{3.11667 Second, Null}

In[4]:=

Timing[Table[z

Oulf~=

{20.9333 Second, Null}

t. x -> i ,

{i,

lOll;]

{i,

lOll;]

3. Define a function fp (without using Unprotect), which evaluates fp[x_] + fp[y_]

to: fp[x + y]

What happens for a sum with more than two terms? 4. Set up definitions for a function nonNegati veQ, which is able to decide whether expressions are positive or zero (e.g., a positive number or an expression y} with x being real). It shall return True for positive expressions (or zero) and False for expressions which are negative or cannot be decided. We assume that the properties of symbols are defined with the functions Positive' Negative, NonNegative, and Im (e.g., positive [x] "= True or Im [ z] "= 0).



2.3.3 Attributes

Until now, we have used definitions to assign certain values, according to patterns, which are found in expressions. We also have the possibility to define more general properties of symbols, by giving the function an attribute. Attributes displays the attributes of an object. In[1):=

Attributes [Sin]

Out[1]=

{Listable, Protected}

The function Sin is Protected from unintentional changes and automatically evaluated for the elements of lists (Listable, see also: Section 1.6.1). More precisely: The attribute Lis tabl e has the effect of automatically threading the function over lists, by using Thread (see Section 1.6.4).

We can use SetAttributes to set an attribute. In[2]:=

SetAttributes [If I

Listable]

264

2. Structure

In[3}:=

Attributes [If]

Ouq~=

{Listable}

This assures that 1 f is automatically threaded over lists. In[4}:=

If [{a, b, c}, d, {e, f, g}]

Ouq~=

{If[a, d, el, If[b, d, fl,

1&

If[e, d, gl}

The attributes of functions must be set before the definitions.

The command ClearAttributes (or Attributes [f] attributes of a function. In[5}:=

ClearAttributes [If, Listable]

In[6}:=

Attributes [If]

Out[6}=

{}

= {}) clears the

A complete list of all possible attributes can be found in the summary of this section. Let us just look at the most important ones: • Orderless puts the arguments into their standard order. This corresponds to a commutative function. In[7]:=

SetAttributes [01, Orderless]

In[B}:=

01 [q,

Out[B}=

01 [3, 5, a, ql

a,S, 3]

• A function with the attribute F 1 a t is associative. In[9}:=

SetAttributes[fl, Flat]

In[10]:=

fl[fl[a, b]' c]

Out[10}= fl [a, In[11]:=

b, el

fl[a, b, b] /

Out[11}= fl [a,

. fl [x_,

x_] -> fl2 [x]

fl2 [fl [blll

• Due to the attribute Fla t, Mathematica could rearrange the arguments in such a way that the rule became applicable (Out[11J=). In this situation, one might ask if f 1 [ f 1 [b] , f 1 [b]] or f 1 [b, b] should be used to match the pattern. The second choice is made if the attribute One I den tit y has been set.

265

2.3 Transformation Rules and Definitions In[12}:=

SetAttributes [fl, OneIdentity]

In[13}:=

f1[a, b, b]

Out[13}= fl [a,

/. f1[x_, x_] -> f12[x]

fl2 [b]]

The function PI us is an example which carries this attribute: In[14]:=

Attributes [Plus]

Out[14}= {Flat,

Listable, OneIdentity, Orderless, Protected}

In[15}:=

a + b + b /. x_ + x_ - > two [x]

Oulf1~=

a + two[b]

Generally, attributes are given to symbols. But we also have the possibility of defining pure functions with attributes. This is done by passing the list of the appropriate attributes after the body of the function (written with Function).

o

In[16}:=

Function [x, x > 2] [{a, 2, 3}]

Oulf1~=

{a, 2, 3} > 2

In[17}:=

Function [x, x > 2, {Listable}] [{a, 2, 3}]

Oulf1~=

{a > 2, False, True}

Summary

• Attributes must be set before the definitions. Expression

Meaning

Attributes [f]

show the attributes off

= {attr] , attr2 ' ... } define attributes for f add attr to the attributes off SetAttributes if, attr] clear the attribute attr ClearAttributes if, attr]

Attributes [/]

Clear [/]

clear the definitions off

ClearAll [/]

clear the definitions and the attributes off

Table 2-18: Changing attributes

266

2. Structure

Expression

Meaning

Function [vars, body,

{attrl,

... } define a pure function with the attributes attrl, ...

Table 2-19: Pure functions with attributes Attribute

Meaning

Orderless

a commutative function, which is independent of the order of its arguments; the arguments are put into standard order

Flat

an associative funtion

Listable

fis automatically threaded over lists appearing in the arguments

Oneldentity

f[f[a 1 1, etc. is treated like a for pattern matching

Constant

all derivatives offare zero

Protected

the definitions off cannot be changed

Locked

the attributes off cannot be changed

ReadProtected the definitions off cannot be read HoldFirst

the first argument off is held unevaluated

HoldRest

all arguments off, except the first one, are held unevaluated

HoldAll

all arguments off are held unevaluated

Temporary

f is a local variable which is cleared after having been used

Stub

the function Needs is called on the context off, iffis used

Table 2-20: The possible attributes of an object!

o

Exercises

1. Find a simple way of defining a function pair, which takes any number of arguments and returns the corresponding symbol name, if two equal arguments are given, and otherwise None: In[4]:=

pair[p, a, p]

Out[4]=

p

In[5]:=

pair [a, b, c]

Outf5]=

None

2.3 Transformation Rules and Definitions

267

2. Extend the above function pair to a function pairs, which returns a list of all pairs appearing in the arguments: In[9]:=

pairs [pl, a, p2, p2, b, pl]

Out[9]=

{pl, p2}

2. Structure

268

• 2.4 Evaluation and Tools for Programming We now have to learn more about how Mathematica evaluates expressions. This will give us a full understanding of what happens to our input. It will also give us ultimate control over definitions and transformation rules-and therefore over almost everything which happens in Mathematica. The principal scheme of evaluation, which is used by most functions, is very simple. But some functions have their own special methods, especially loops and conditionals. We will see that such programming constructs-which are common in procedural programming languages, like Fortran, Pascal or C-can be implemented in Mathematica, but that we have even better tools here, which fit better into the functional programming style preferable in Mathematica.



2.4.1 Standard Evaluation

The basic evaluation scheme is that all definitions are used multiply, until nothing changes anymore. In more detail, this is done as follows: 1. evaluation of the head, 2. evaluation of each element in tum, 3. application of transformations associated with the attributes Orderless, Listable, and Flat, 4. applications of all definitions set by the user, 5. application of all built-in definitions, 6. evaluation of the result. By using the function Trace, we can trace all expressions which are generated during the evaluation (see also: Section 3.2.1). In[1]:=

a = 3;

In[2]:=

Trace [a A 2 + a + 1]

Out[2]=

{ { {a

, 3}, 3 2, 9}, { a , 3}, 9 + 3 + 1, 1 + 3 + 9, 13}

2.4 Evaluation and Tools/or Programming ~

269

Notice that the tree structure of an expression is basically evaluated from the bottom to the top, because point 2 of the above scheme introduces a recursion. This corresponds to the evaluation of nested function calls from the inside to the outside, as expected for a functional language. We already have used this property over and over again. In any case, the head is evaluated first.

In[3}:=

s = Sin;

In[4}:=

Trace [s [{ 0, a}]]

Out[4}=

{{s, Sin}, {{a, 3}, {O, 3}}, Sin[{O, 3}], {Sin[O], O}, {O, Sin[3]}}

{Sin[O], Sin[3]J

Definitions which are associated to inner symbols of expressions (in points 4 and 5), are evaluated before the ones associated to the outer symbols ("upvalues" before "downvalues"). In[5}:=

f[g[x_]]

In[6}:=

f [g [x_] ]

In[7):=

f[g[l]]

Out[7)=

r2

= rl; A= r2;

In more detail, the following order of evaluation is used for an expression of the form f [g [x] ] : 1. definitions for g, which were given by the user, 2. built-in definitions for g, 3. definitions for f, which were given by the user, 4. built-in definitions for f. Sometimes, Mathematica does a lot of work when trying to match a pattern-maybe more than the user is aware of. We can visualize such an effect in the following way: The function Print (see also: Section 2.6.1) prints expressions to the screen. It does not return a result, surely not True. If we define a function with the attribute Orderless, and use Print in a condition, it will try to produce a True with all possible permutations of the arguments. As as side effect, it prints the arguments for every choice: In[8]:=

SetAttributes [pr, Orderless]

In[9}:=

pr [x___ ]

: = 1 /; Print [x]

270

2. Structure 2, 31

pr [1,

In[10]:=

123 132 213 231 312 321 2, 3]

Out[10]= pr[l,

We can easily tum Mathematica into Sisyphos, this way.

D

Summary Expression

Meaning

Trace [expr]

the list of all expressions used in the evaluation of expr

Trace [expr , pattern]

the list of all expressions matching pattern used in the evaluation of expr

Trace [expr, s]

the list of all expressions used in the evaluation of expr, and belonging to rules associated to s

Print [exprl, expr2'

... ]

print the expressions to the screen, end with a newline

Table 2-21.' Getting information about the evaluation process

D

Exercises

1. Define In{1]:=

pI

=

Plus; b

=

1;

and analyze the evaluation of: In[2]:=

pI [Sin[pI [1 - b]],

5]

2. Make a definition (without using Unprotect), such that Mathematica returns the result fIntegral when the function f is being integrated: In[5]:=

Integrate [f [xl, xl

Oulf~=

flntegral[x]

2.4 Evaluation and Tools for Programming

271

3. Print all permutations of (q, s, f, q, w, s), which contain a pair at the beginning (see Exercise 1 on page 266).



2.4.2 Special Evaluation

D

Reasons for Special Evaluation

The standard evaluation scheme of Section 2.4.1 cannot be used for every expression. For instance, the left side of a definition (e.g., a = 7) cannot be evaluated. If it would evaluate and the left side already had a value (e.g., a = 3), this would give an undesired result (3 = 7). Therefore, definitions (Set) are treated in a special way. They have the attribute HoldFirst. In[1]:=

Attributes [Set]

Out[1}=

{HoldFirst, Protected}

HoldFirst assures that the first argument (i.e., the left side in the operator notation with =) is held unevaluated.

In analogous ways, the attributes HoldAll or HoldRest (see Section 2.3.3) can be used to keep other arguments unevaluated. Several other functions use these attributes, or their own control, to evaluate in special ways. Among them are plot functions, loops, conditionals, and pure functions.

D

Preventing and Enforcing the Evaluation

The function Ho 1 d can be viewed as an incarnation of the attribute Ho 1 dAll. In[2}:=

Attributes [Hold]

Oulf~=

{HoldAll}

It does nothing but prevent the evaluation of its arguments. Without a trick, we cannot see the full form of a definition. It evaluates before being passed to FullForm.

272

2. Structure

In[3]:=

FullForm[a

1]

Out[3]IIFuIlForm= 1

In such a case, Hold can be used to prevent the evaluation. In[4]:=

FullForm[Hold[a = 1]]

Out[4]IIFuIlForm=

Hold[Set[a,

III

An expression like 1 + 1 is another example for this: In[5]:=

Hold [1 + 1]

Out[5]=

Hold [1 + 11

We might not want to see the Hold, but still keep the expression unevaluated. This is what HoldForm does. In[6]:=

HoldForm [1 + 1]

Out[6]=

1 + 1

If such a held expression shall be evaluated after all, we can do that with ReleaseHold. In[7]:=

ReleaseHold [%]

Out[7]=

2

We have already seen in Section 1.5.2 that plot functions do not evaluate their first argument. The plot is created by evaluating the first argument at the points used to draw the figure. In[B]:=

Attributes [Plot]

Ouq~=

{HoldAll, Protected}

Therefore, the following command behaves different from what the user might expect: In[9]:=

Plot [Table [x A (lin),

{n, 10}], {x, 0, 2}]

273

2.4 Evaluation and Tools/or Programming

1

0.8 0.6 0.4 0.2

0.2

0.4

0.6

0.8

1

Plot: : plnr: CompiledFunction[{x}, «1», -CompiledCode-] [«1»] is not a machine-size real number at x = 0 .. Plot: : plnr: CompiledFunction[{x}, «1», -CompiledCode-] [«1»] is not a machine-size real number at x = 0.0833333. Plot: : plnr: CompiledFunction[{x}, «1», -CompiledCode-] [«1»] is not a machine-size real number at x = 0.166667. General: :stop: Further output of Plot::plnr will be suppressed during this calculation. Ou~~=

-Graphics-

Arguments of functions which are not evaluated because of an attribute (HoldAll, HoldFirst, HoldRest) can be forced to evaluate immediately with the Evaluate function. In[10]:=

Plot [Evaluate [Table [x A (l/n),

{n, 10}]],

{x, 0, 2}]

274

2. Structure

2

1.5

1

1.5

2

OUlf10= -Graphics-

o

Patterns, Transformation Rules, and Definitions

The left hand sides of transformation rules usually are evaluated. Therefore, the following expression does not change (D [x, y] gives 0): In[11]:=

Hold[D[x, y]]

Out[11]= Hold[D[x,

/.

D[x, y]

-> dxy

y]]

By using Li teral on the left hand side of a rule, it can be kept unevaluated. Our example does work now. In[12]:=

Hold[D[x, y]]

/.

Literal [D[x, y]]

-> dxy

Out[12]= Hold[dxy]

The evaluation of the right hand side of a transformation rule depends on whether it is immediate (-» or delayed (: ». In the first case, it is evaluated, in the second case not. In definitions with = and : =, the left side is only partially evaluated: Nothing happens with symbols; only the arguments of functions are evaluated, but not the functions themselves. In the following example, the middle definition is set for f [ 2 ] (and not for f 2 or even f [ 1 + 1] ). In[13]:=

f[2]

Out[13]= f 11

=

f2;

f[1+1]

=

f11;

f[2]

2.4 Evaluation and Tools for Programming

As we already know, the right hand sides of definitions are evaluated for kept unevaluated for: =.

275

=and

These rules for the evaluation might look a little complicated in such a detailed explanation. But their aim and their effect is that they behave "naturally" for the majority of all expression.

o

Other Functions with Special Evaluation

Several other functions need a special evaluation scheme to behave in a "natural" way: • The evaluation of iteration functions, like Table and Sum (but also Plot, Plot3D, etc.) is done as follows: In an expression like Table [j,

{i,

imax }]

the iterator i is localized first (see Section 2.5.1). Then the boundary imax is evaluated. As a whole, the expression f remains unevaluated, but it is evaluated for the different values of i. At the end, the global value of i is restored. • The Do loops (see Section 2.4.3) also use the above scheme. • For all conditionals (If, Which, Switch, see Section 2.4.3), only the argument corresponding to the first matching condition is evaluated. • Control structures (see Section 2.4.3) use their internally programmed evaluation schemes, which assures the correct flow.

• Combined logical expression (e.g., el && e2 && e3) are evaluated, from the left to the right, only until the result is clear. (In our example, this means that the evaluation returns False, as soon el> e2, or e3 evaluates to False. Otherwise, the expression is simplified; if el' e2, and e3 are True, the final simplification is True.) • For pure functions, the function body is not evaluated; the variables are localized automatically (see Chapter 2.5). • The function Trace allows tracing certain transformation rules (see Section 3.2.1). These are not evaluated. • Variable specifications in scoping constructs (Module, Block, see Section 2.5.1) are kept unevaluated.

276

o

2. Structure

Summary

Expression

Meaning

Hold [expr]

the expression expr is kept unevaluated

HoldForm[expr]

expr is kept unevaluated, but HoldForm not shown

ReleaseHold [expr]

Hold and HoldForm are removed from expr

HeldPart [expr, index]

a part of expr is pulled out and wrapped into a Hold

ReplaceHeldPart [expr, value,

a part of expr is replaced without evaluating it

index]

Li teral [pattern]

is equivalent to pattern for pattern matching, while pattern remains unevaluated

j[Evaluate [expr]]

evaluate expr, even if the attributes of/say that it should not be evaluated

j[ ... , Unevaluated [expr] ,

... ]

use the unevaluated form of expr as the argument of/ the definition is evaluated only if the condition test returns the value True

lhs : = rhs /; test

Table 2-22: Controlling the evaluation

o

Exercises

1. Explain: In[1]:=

Table [NumberQ [i], {i, 3}]

Out[1]=

{True, True, True}

In[2]:=

Table [Evaluate [NumberQ [i]], {i, 3}]

Ouq~=

{False, False, False}

2. Study the following definition in its FullForm: In[3]:=

f[{x:L, _} .• }]

:= Transpose[{x}]

When does the function evaluate? What does it do?

277

2.4 Evaluation and Tools for Programming



2.4.3 Conditionals, Loops, and Control Structures

Conditionals, iterations, and loops are central tools in procedural programs. Because most of them have special evaluation schemes, we treat them in this section. But we will also see that it is worthwhile to study and use Mathematica's tools for functional programs. These can be much more elegant and efficient than the direct translation of procedural algorithms.

o

Conditionals

We have seen (Section 2.2.2) that definitions of the form lhs : = rhs /; test can be used for conditionals. Typically, several definitions with conditions are set, such that one of them applies for every possible expression. In[1j."=

f1[x_]

.-

0 /; x < 0

In[2}:=

f1[x_]

.-

Exp[-x]

In[3}:=

Table[f1[i],

Out[3}=

{O, 1,

/; x >= 0

{ i, -1, 1}]

1}

E

Conditions can also be packed into a single expression by using the functions If, Which, or Swi tch. They resemble the analogous constructions used in procedural programming languages (Fortran, C, Pascal, etc.). The function

I f

If [test,

handles three or four arguments. They have the form: then, else]

If the test function test returns the value True, the expression then is evaluated; if test returns False, the expression else is evaluated In[4]:=

f2[x_]

:= If[xlJJ

The value of p is not the polynomial, but its FortranForm. It cannot be expanded:

312

2. Structure

In[3]:=

FullForm [p]

Out[3]1IFuIlForm=

FortranForm[Power[Plus[1.2, x], 2]]

To format the result as desired and still set the definition for the expression itself, the whole definition must be wrapped in FortranForm. In[4]:=

FortranForm[q = (1.2 + x)A2]

Out[4]1IFortranForm= (1.2 + x)**2 In[5]:=

Expand [ q]

Oulf~= 1.44

+

2.4 x + x 2

The same holds for TableForm, etc.

o Summary Expression

Meaning

OutputForm [expr]

the normal output format

InputForm [expr]

print expr as Mathematica input

TextForm [expr]

format as text (expressions in output form, strings like text)

CForm [expr]

print a version for the language C

FortranForm [expr]

print a version for the language Fortran

TeXForm [expr]

print a version for TeX

FullForm [expr]

print the full internal format

TreeForm [expr]

print different levels on different lines

TableForm [list]

print a list in the form of a table

MatrixForm [list]

print a list in the form of a matrix with equally sized cells

ColumnForm [list]

print the elements of a list as a column

PrintForm [expr]

print the internal printform representation

Table 2-39: Output formats

o

Exercise

1. Use an example to study the internal PrintForm.

2.6 Strings, Text, Messages



313

2.6.4 Formats for Numbers

Numbers can be formatted in different ways with NumberForm, ScientificForm, EngineeringForm,AccountingForm, PaddedForm,andBaseForm. Each function takes parameters and options for custom settings. These are listed in Table 2-40 and Table 2-41. In{1]:=

ScientificForm[E"lO.]

Out[1 ]/IScientificForm=

2.20265 10 4 In[21:=

EngineeringForm [%]

Out[2]/IEngineeringForm=

22.0265 10 3 In[31:=

NunilierForm[%,

{lS, lO}]

Out[3]/INumberForm=

22026.4657948067 In[41:=

PaddedForm[%, {lS, lO}, NumherPoint -> ",", DigitBlock -> 3, NumherSeparator -> {"

I

",

"""}]

Out[4]/IPaddedForm=

22' 026,465"794 "806"7 In[51:=

BaseForm [%, 2]

Out[511lBaseForm=

1.01011 2 214

o

Summary Expression

Meaning

NurnberForm [expr, tot]

print the reals in expr with tot digits precision

NumberForm [expr, {tot, frac} ]

print the reals in expr with tot digits precision and frac digits to the right of the decimal point

ScientificForm [expr]

print numbers in scientific notation

ScientificForm [expr, tot]

the scientific notation with tot digits

Table 2-40: Formats for numbers

314

2. Structure

Expression

Meaning

EngineeringForm [expr]

print numbers in engineering notation (the powers are multiples of 3)

EngineeringForm [expr, tot]

the engineering notation with tot digits

AccountingForm [expr]

the standard accounting notation

PaddedForm [expr, tot]

numbers are padded to leave room for tot digits

PaddedForm [expr,

numbers are padded to leave room for tot digits;frac digits are shown to the right of the decimal point

{tot, trac} ]

BaseForm [expr, b]

print numbers in the base b

MantissaExponent[x]

return a list containing the mantissa and the exponent of an approximate real number

MantissaExponent[x, b]

the mantissa and exponent in the base b

Table 2-40: Formats for numbers Option

Default

Meaning

DigitBlock

Infinity

the maximum length of the blocks

NumberSeparator

{II

NurnberPoint

" "

NurnberSigns

{

II _

{

"",

NumberPadding {

,", " "}

the string to insert at breaks between digits the string used for the decimal point

II,

II

II }

the strings used for negative and positive signs

the strings used for padding; • in NurnberForm " " , "0" } • in PaddedForm II "

}

SignPadding

False

padding between the sign and the digits

NumberFormat

Automatic

the function specifying how the mantissa, base, and exponent should be assembled

ExponentFunction

Automatic

the function used to determine the exponent

Table 2-41: Options used by the number formatting functions

o

Exercise

1. Experiment with the different number formats.

315

2.6 Strings, Text, Messages



2.6.5 Subscripts and Superscripts

Many mathematical expressions contain subscripts and superscripts, which should be shown in their natural notation. This is done by the functions Subscripted, Subscript, and Superscript. The first one prints the arguments of functions as subscripts. In[1]:=

Subscripted [x [a, b, c]]

Out[1}=

xa,b,c

To have the first two parameters only used as subscripts, we write: In[2]:=

Subscripted [x [a, b, c], 2]

Out[2}=

x a, b [ c 1

Subscripts and superscripts are created by giving a list with the start and the end positions for the subscripts, and another with these values for the superscripts. In[3}:=

Subscripted [x[a, b, c],

Out[3}=

xa b, c

{l,

l},

{2,

3}]

Single subscripts or superscripts are returned by Subscript or Superscript. They can be combined with SequenceForm and ColumnForm. In[4}:=

Out[4}=

SequenceForm [ "«< f[a", Subscript[s], Superscript[e], "] »>"] «< f[a

s

x,

" x, b",

be] »>

We can use these tools to define a function, which prints formulas containing partial derivatives in a compact notation. Let us look at the following expression:

= D[s[x,

In[5}:=

expr

Out[5}=

s ( 0 , 1 , 0) [x, y,

y, z],

{x, 2}] + D[s[x, y, z], y]

z 1 + s (2 , 0 , 0) [x, y,

z1

It is not easy to read it in this form-we want to define a better notation.

316

2. Structure

Let us first note that such partial derivatives are internally represented as Derivative [nl' ... J [f] [xl' ... J, where nb ... stands for the order of the derivative off with respect to the variable X I, ... : In{6:=

FullForm [%]

Out{6]1/FuIlForm=

Plus [Derivative [0, 1, 0] [s] [x, y, z], Derivative [2, 0, 0] [s] [x, y, z]]

We can therefore define an alternative format pdeForm for partial derivatives by: In{7]:=

pdeForm [e_1 : = e /. Derivative [n__ ] [f_] [x__ ] :> SequenceForm[f, Subscript [", "], Subscript Flatten [Table [# [[111, {# [ [2] 1 }] & /@ Transpose[{{x}, {n}}]ll

@@

This gives us the following output: In{8]:=

pdeForm[expr1

Out{8]=

s ,y + s ,xx

Partial differential equations often contain further indices to denote the components of vector functions: In{9]:=

Out{9]=

equOfCont = Plus @@ (D[t[x, #] [x, y, z], #1& f [x] == 0 f[x]

+ (t[x, z]) (0,0,1) [x, y,

(t[x,

==

°

y])(O,l,O)[x,

y,

z]

z]

+

/@

{x, y,

z}) +

+

(t[x,

x])(l,O,O)[x,

y,

z]

In this case, it is necessary to distinguish between the variables and the indices. We have to ask, for instance, for the list of the functions which contain indices. Given the list, we can define: In{10]:=

pdeForm[e_, indexed_List] := e /. {Derivative [n__ 1 [f_?(MemberQ[indexed, #]&) [i __ 11 [x__ ] :> SequenceForm[f, Subscript[i], Subscript[","], Subscript @@ Flatten[Table[#[[1]], {#[[2]]}]& /@ Transpose [{ {x}, {n}}]] 1,

317

2.6 Strings, Text, Messages Derivative [n__ ] [C] [x__ ] :> SequenceForm[f, Subscript [", "], Subscript Flatten[Table[#[[l]], {#[[2]]}]& /@ Transpose [{ {x}, {n}}] 11, f_?(MemberQ[indexed, #1&) [i __ 1 -> SequenceForm[f, Subscript[i]1, f_?(MemberQ[indexed, #]&) [i __ 1 [ ___ 1 -> SequenceForm[f, Subscript[i11}

@@

This returns: In[11]:=

pdeForm[equOfCont,

{t, f}]

Out[11]= fx + txx,x + txy,y + t xZ,z

o

The above result has the disadvantage that is cannot be used for further calculations. In[12]:=

FullForm [%]

Out[12]IIFuIlForm=

Equal [Plus [SequenceForm[f, Subscript[x]], SequenceForm[t, Subscript [x, x], Subscript[","], Subscript[x]], SequenceForm[t, Subscript [x, y], Subscript[","], Subscript[y]], SequenceForm[t, Subscript [x, z], Subscript[", "], Subscript[z]]], 0]

In the next section, we will therefore define an analogous function, which acts as a "wrapper" and affects the printing only, just as we are used to from the built-in formatting functions, like TableForm. We can use the functions Prefix, Postfix, and Infix, to define operators in prefix, postfix, or infix notation. In[13]:=

Prefix [myOperator [xl,

"!!

="l

Out[13]= !! =x

o

Summary Expression

Meaning

Subscripted [j[xl' X2'

... ]

Subscripted [j[xl ' x2'

... ] , n]

]

the arguments off are written as subscripts the first n arguments ofj are written as subscripts

Table 2-42: Special formats

318

2. Structure

Expression

Meaning ... l,

Subscripted [{[xl' X2' {do,

d l }.

{no,

nl}

1

the arguments do through d l are written as subscripts, no through nl as superscripts

Subscript [xl

write x as subscript

Superscript [xl

write x as superscript

Prefix [{[xl, hl

prefix notation: h x

Postfix [{[xl, hl

postfix notation: x h

Infix [j[x, y,

infix notation: x h y ...

... l, hl

Table 2-42: Special formats Expression

Meaning

Derivative [nl' n2, ... l

en [xl'

x2,

... l

the nl th derivative of/with respect to xl' the n2th with respect to Xz, etc.

Table 2-43: The full notation for derivatives

o

Exercises

1. Write a 3x3 matrix with general, indexed elements in its natural notation. 2. What happens if Infix is used for a function with more than two arguments?



2.6.6 Custom Formats

By using Forma t, we can write our own custom-made formatting functions. We might want to define our own integrator (see Section 2.2.4) and display unevaluated integrals in a form resembling the normal mathematical notation. This can be done with: In{1]:=

Format [myIntegrate [x_, t_ Symbol 1 1 .SequenceForm["S ", x, "d", tl

In{2]:=

myIntegrate [x A 2, xl

Out{2]=

S x 2 dx

If the font we use for input and output contains the integral sign J, we might choose it, instead ofs.

319

2.6 Strings, Text, Messages

Such a definition only affects the OutputForm of the pattern. We can pass a second arguments to Format, if a definition should be added to a built-in format. A TeXForm for myIntegrate could thus be given by: In[3}:=

Format [mylntegrate [x_, t_ Symbol], TeXForm] SequenceForm["\int d", t, "\,", x]

In[4}:=

TeXForm [mylntegrate [f [t"2], t]]

.-

Out[4j1lTeXForm=

\int dt\,f({t A 2})

It now produces the same TeX statement as the "normal" integral function. In[5}:=

TeXForm[Integrate[f[t"2], t]]

Out[5}llTeXForm=

\int dt\,f({t A 2})

We can use the ideas of the last section (pdeForm) to define our own format for partial derivatives, which only affects the printed results, but not their internal representation in Mathematica (like TeXForm, etc.). Our function shall be named PDEForm and remove the corresponding heads of expressions. In[6}:=

Forma t [PDEForm [e_, ___ ], PDEForm]

:= e

Just as we did in the last section, we can now start to define output formats for it. In[7}:=

Format[PDEForm[e_], OutputForm] := e /. Derivative [n__ ] [e] [x__ ] :> SequenceForm[f, Subscript[","], Subscript @@ Flatten[Table[#[ [1]], {#[ [2]] }]& /@ Transpose [{ {x}, {n}}]]]

In[B}:=

Format [PDEForm[e_, indexed_List], OutputForm] := e /. {Derivative [n__ ] [f_?(MemberQ[indexed, #]&) [i __ ]] [x__ ] :> SequenceForm[f, Subscript[i], Subscript[","], Subscript @@ Flatten[Table[#[[l]], {#[[2]]}]& /@ Transpose[{{x}, {n}}]]], Derivative [n__ ] [f_] [x__ ] :> SequenceForm[f, Subscript [", "], Subscript @@ Flatten[Table[#[[l]], {#[[2]]}]& /@ Transpose [{ {x}, {n}}]]],

320

2. Structure f_?(MemberQ[indexed, #]&) [i __ ] -> SequenceFor.m[f, Subscript[i]], f_?(MemberQ[indexed, #]&) [i __ ] [ ___ ] -> SequenceFor.m[f, Subscript[i]]}

For an expression like: In[9}:=

expr = D[s[x, y, z], {x, 2}] + D[s[x, y, z], y]

Out[9}=

s ( 0 , 1 , 0) [x,

y,

z]

+ s (2 , 0 , 0) [x, y,

z]

PDEForm now produces: In[10}:=

PDEFor.m [expr]

Out[10}IIPDEForm=

s

,Y

+ s

,xx

The internal representation is no longer affected. In[11}:=

FullFor.m [%]

Out[11 }IIFuIlForm=

Plus [Derivative [0, 1, 0] [s] [x, y, z], Derivative[2, 0, 0] [s] [x, y, z]]

o

Summary Meaning

Expression Format [expr]

;= form

Format [expr, type]

; = form

define a print form for expr define a print form of type for expr

Table 2-44: Custom print formats

o

Exercises

1. The function pair [a, b] shall have two arguments. These shall be printed as a pair: {a, b}.

2. Write a package which defines and exports the above function PDEForm.

2.6 Strings, Text, Messages



321

2.6.7 Strings

The functions ToCharacterCode and FromCharacterCode can be used to convert strings into the corresponding ASCII codes of the single characters, and VIce versa. In[1]:=

ToCharacterCode [ II text "]

Out[1}=

{116, 101, 120, 116}

In[2]:=

FromCharacterCode [%]

Out[2]=

text

With Characters, a string is separated into a list of single characters. In[3]:=

Characters [ II text I I ]

Oulf~=

{t, e, x,

t}

Special characters (see Table 2-45) can be placed within strings. They must be preceded by a \. In[4]:=

Print ["text\nmore text on a new line")

text more text on a new line

A set of functions serves for the manipulation of strings (see Table 2-48). They work and are named in analogy to the corresponding list manipulation functions (see Table 1-72 on page 155). In[5}:=

Stringlnsert["abde", "C", 3)

Out[5]=

abcde

We can use ToString and ToExpression to convert expressions into strings and vice versa. In[6]:=

ToString [Sin [x))

Out[6]=

Sin [xl

In[7]:=

Head [%)

Out[7]=

String

322

2. Structure

InfB]:=

ToExpression["Expand[(a + b}A2] II]

OutfB}=

a2 + 2 a b + b2

The metacharacters (place holders) * and

o

Inf9}:=

StringMatchQ ["aabcc",

Outf9}=

True

@ are

used to define string patterns.

"a*c"]

Summary Special Character

Meaning

\"

the character " within a string

\\

the character \ within a string

\*

the character *

\@

the character @

\b

a backspace

\n

a newline

\r

a carriage return,

\t

a tab

\"A through \"Z

control characters

\"a through \"a

\nnn

an 8-bit character (octal)

\ .nn

an 8-bit character (hexadecimal)

\ :nnnn

a 16-bit character (hexadecimal)

Table 2-45: Special characters Character

Meaning

*

zero or more characters

@

zero or more characters, without uppercase letters

Table 2-46: Metacharacters, place holders in strings

323

2.6 Strings, Text, Messages

Expression

Meaning

Characters ["string"]

the list of the single characters

ToCharacterCode ["string"]

the list of the ASCII codes

FrornCharacterCode[n]

the character corresponding to the ASCII code

FrornCharacterCode [{nI' n2'

... } ]

the string corresponding to the ASCII codes

ToString [expr]

convert an expression into a string

ToExpression [ "string" ]

convert a string into an expression

Table 2-47: Converting text and expressions Expression

Meaning

StringLength [s]

the length

StringJoin [sI' s2, ... ]

join strings

sl s2

StringJoin [sI' s2]

StringReverse [s]

reverse a string

StringTake [s, n], etc.

the first n characters (variants are analogous to Take, see Table 1-72 on page 155)

StringDrop [s, n],etc.

drop the first n characters

Stringlnsert [s,

snew 1

insert at the position n

n]

StringPosition[s, sub], etc. StringReplace [s,

{si -> sPI'

StringMatchQ ["string",

find the position of a substring sub

... }

"pattern" ]

]

replace substrings does a string-pattern match?

Table 2-48: The manipulation of strings

o

Exercise

1. Write a function which works like StringTake, but does not use StringTake.



2.6.8 Messages

We have noticed several times that Mathematica generates warnings and error messages, when appropriate.

324 In[1]:=

2. Structure 1/0 1

Power: :infy: Infinite expression - encountered.

o

Out[1}=

ComplexInfini ty

Such messages can be turned Off. In[2}:=

Off [Power: : infy]

In[3}:=

1/0

Oulf~=

ComplexInfinity

On reactivates them. In[4}:=

On [Power: :infy]

We can define messages for our own functions. Just like the ... : : usage strings (see Subsection "A Prototype for Packages" on page 302), they consist of the function name, a : :, followed by a chosen tag which identifies the message. For a function ndi v, a message definition might look like: In[5}:=

ndiv: : infy

=

"Infinite expression encountered.";

We now use the Message command to generate the message, where appropriate. In[6}:=

ndiv[a_, b_] := If[b == 0, Message[ndiv::infy]; Infinity, N[a/b]

In[7}:=

ndi v [1, 0 ]

ndiv::infy: Infinite expression encountered. Out[7}=

Inf ini ty

We can even add information, which uses the situation at "run time", to the message,. This is done by inserting place holders C 1 " etc.) into the message string. Analogous to StringForm, these place holders will be replaced by the current values of the further parameters of Me s sage.

325

2.6 Strings, Text, Messages In[8]:=

ndi v: : infy = "Infinite expression ndiv['l', '2'] encountered.";

In[9]:=

ndiv[a_, b_] := If[b == 0, Message[ndiv::infy, a, b]; Infinity, N[a/b]

In[10]:=

ndi v [1, 0]

ndiv: :infy: Infinite expression ndiv[l, 0] encountered. Out[10]= Infinity

Error messages can even be used for the flow control of programs: The function Check returns its second argument, if an error message is generated during the evaluation of its first argument. Otherwise, the "normal" result is returned. In[11]:=

checkForError[a_, b_]

In[12]:=

checkForError [ 1, 2 ]

:= Check[ndiv[a,

b], err]

Out[12]= 0.5 In[13]:=

checkForError [1, 0]

ndiv: :infy: Infinite expression ndiv[l,

0] encountered.

Out[13]= err

It is important to notice that Check only handles errors which occur during the evaluation of its first argument. Errors occurring during the evaluation of the arguments of the function which calls Check (in our case: checkForError), will not be caught. In[14]:=

checkForError [ 1 , 01\0 ]

o Power: :indet: Indeterminate expression 0 Out[14]= If[Indeterminate

==

encountered.

0, Message[ndiv::infy, 1,

Indeterminate]; Infinity,

1 N[Indetermlnate]]

This can be seen better with a Trace command.

326 In[15]:=

2. Structure checkForError [1, 0 A 0]

/ / Trace

Power: :indet: Indeterminate expression

°°encountered.

Oulf1~= {{0°, {Message [Power: :indet, 0°], Null}, Indeterminate}, checkForError[l, Indeterminate], Check[ndiv[l, Indeterminate], err], {ndiv[l, Indeterminate], If[Indeterminate == 0, Message[ndiv::infy, 1, Indeterminate]; Infinity, 1

N[indeterminate]]}'

If[Indeterminate == 0, Message [ndiv: :infy, 1, Indeterminate]; Infinity, 1

N[indeterminate]]}

The error message was not produced within Check, and therefore cannot be caught by it. We can restrict Check to specific massages. This is done be adding further arguments, as, for instance: In[16]:=

Check [Sqrt [a, b], err, Sqrt:: argx]

Sqrt: : argx: Sqrt called with 2 arguments; 1 argument is expected. Out[16]= err

Other error messages are no longer caught, now. In[17]:=

Check [ 1/0, err, Sqrt:: argx] 1

Power::infy: Infinite expression - encountered. OUlf1n= ComplexInfinity

°

Besides error messages, there are two more standard types of messages, usages f: : usage and notesf: : notes (see also: Section 2.5.2).

327

2.6 Strings, Text, Messages

o

Summary Expression

Meaning

Off [s: : tag]

suppress messages of a certain type

On[s: :tagJ

reactivate the messages of a given type

Messages [sJ

the messages associated to s

Message[s: :tagJ

print a message

Message [s: : tag,

exprl'

... J

print a message, and replace 'i' byexpri

Check [expr, Jailexpr]

evaluate expr; return the result if no messages are generated, and otherwise Jailexpr

Check [expr, Jailexpr,

only check for the given messages

sl : : tl '

s2: : t2'

... J

Table 2-49: Messages Meaning

Expression s: : tag

=

" string"

J: :usage J: :notes

= =

the definition of a custom message

"string"

the documentation of a function

"string"

notes for a function

Table 2-50: Types of messages

o

Exercise

1. Use Check to assure that myRoot from Section 2.5.1 returns err in case of an error.

Part 3.

Programming

330

3. Programming

We have looked at the main elements of the programming language Mathematica in the previous chapters. In this final part of the book, we want to optimize their application. Following [WoI88], we start with an overview of the programming methodologies possible in Mathematica (Chapter 3.1). We continue be studying the techniques of debugging, and by writing some example packages (Chapter 3.2). Chapter 3.3 is devoted to the numerics, whereas Chapter 3.4 shows how long calculations can be handled in practical ways.

o

About the Picture

The following commands produce the "suspended" knot: In[1}:=

Needs ["LinearAlgebra' CrossProduct' "]

In[2]:=

absV[v_?VectorQ]:= Sqrt[Plus

In[3]:=

surfacePoint [curve_, t_, angle_, scale_] : = Module[{tang = D[curve, t], perp1, perp2}, perp1 = {tang[[2]], -tang[[l]], O}; perp2 = Cross[tang, perp1]; scale (perp1/absV[perpl] Cos [angle] + perp2/absV[perp2] Sin[angle])

In[4]:=

curve

In[5}:=

p1 = ParametricPlot3D [Evaluate [ curve + surfacePoint[curve, t, angle, .3]], {t, -pi, 2Pi}, {angle, 0, 2Pi}, PlotPoints -> {150, 15}, DisplayFunction -> Identity];

In[6]:=

p2 = ParametricPlot3D [Evaluate [ curve + surfacePoint [curve, t, SOt, .3]], {t, 2Pi, 3Pi}, PlotPoints -> 3000, DisplayFunction -> Identity];

In[?]:=

Show [Graphics3D [ {{EdgeForm[AbsoluteThickness[.05]], p1[[1]]}, {AbsoluteThickness[l], p2[[1]]}}], Axes -> False, Boxed -> False, ViewPoint -> {1.3, 1.5, 4.5}]

@@

(v"2)] /; Length [v]

3

{(1 + .4 Cos[3/2 t]) Cos[t], (1 + .4 Cos[3/2 t]) Sin[t], Sin[3/2 t]};

3.1 Programming Methodologies

331

• 3.1 Programming Methodologies An attractive aspect of Mathematica is the richness of possible programming methodologies. A programmer who primarily knows languages like C, Pascal, Modula-2, or Fortran, will probably start by translating the algorithms used for these languages directly to Mathematica. As we have seen, this is possible, but usually not the most elegant solution. By applying functional or rule-based programming techniques, mathematical algorithms can often be written in a more compact, easy to read, and efficient way. Our explanations are kept compact and illustrated by simple examples, only. The book by Roman Maeder [Mae9l] gives a much deeper treatment of these concepts.



3.1.1

Procedural Programming

The structure and implementation of procedural programs is well known. They use control structures like Do, While, and For, and conditionals like If, Which, and Swi tch (see Section 2.4.3) to control the flow. For the definition of local variables, there are scoping constructs like Module (see Section 2.5.1). Let us illustrate this style by a little program which converts integers to numbers in the base 256, represented as lists. We will need such a function in Section 3.2.3: To encrypt text messages with RSA (see Section 1.3.3), we will take the ASCII codes of the characters, and interpret the resulting list as a number in the base 256, which is then converted into a decimal integer. The inverse transformation leads to the above problem.

A solution using procedural style might look like this: In[1J:=

makeList1 [num_Integer] : = Module[{res = {}, rem = num}, While[rem != 0, PrependTo[res, Mod [rem, 256]]; rem = Quotient[rem, 256]]; res

In[2J:=

makeList1 [111111111111]

Out[2J=

{ 2 5,

2 2 2, 189, 1, 19 9 }

332

3. Programming

This program is not satisfactory, because it uses two local variables, and the flow has to be controlled with a Whi 1 e loop. We will write a recursive version in the next section, which brings a great improvement.



3.1.2 Recursive Programming

All modern languages allow recursive function calls. They can be used for compact solutions of problems which naturally are formulated by a recursion. This makes an explicit control of the flow unnecessary. It is very easy to define initial conditions in Mathematica. They are given as a specific definition, which is automatically evaluated before the more general definition for the recursion (see Sections 2.3.2 and 2.4.1). The restriction of arguments can be used for final criteria, as well.

The problem from the last section can be solved in a recursive fashion by two simple definitions. In[3]:=

makeList2 [0] = {};

In[4]:=

makeList2 [num_Integer] .Append [makeList2 [Quotient [num, 256]], Mod [num, 256]]

In[5]:=

makeList2 [111111111111]

Ou~~=

{25, 222, 189, 1, 199}

Note that we have not started a new session here, because we want to compare the two implementations.

What about the timings of the two programs? In[6]:=

makeList1 [10 A 100] / / Timing

Oulf~=

{0.15 Second, {18, 73, 173, 37, 148, 195, 124, 235, 11, 39, l32, 196, 206, 11, 243, l38, 206, 64, 142, 33, 26, 124, 170, 178, 67, 8, 168, 46, 143, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OJ}

In[7J:=

makeList2 [10 A 100] / / Timing

Oulfn=

{0.1 Second, {18, 73, 173, 37, 148, 195, 124, 235, 11, 39, l32, 196, 206, 11, 243, l38, 206, 64, 142, 33, 26, 124, 170, 178, 67, 8, 168, 46, 143, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, OJ}

3.1 Programming Methodologies

333

The recursive implementation is definitely faster, even though the handling of the recursive calls also involves some expenditure. But the main argument for the second version is its clarity. For simple recursive problems, there often are fast iterative algorithms as well. But for most cases of complicated algorithms, a short recursive implementation is better then a long and sophisticated iterative one.

Recursive algorithms which use intermediate results several times, should be implemented by saving these intermediate results (see Subsection "Definitions with Memory" on page 258). The definition of the Fibonacci numbers (see Exercise 1 in Section 2.3.2) is a nice example for this effect. A version which does not save these results, takes a lot of time. In[8]:=

fib1 [0] = 1; fib1 [1]

In[9]:=

fib1[n_]:= fib1[n-1]

In[10]:=

Timing[fib1[16]]

OUlf10= {4.66667 Second,

= 1; + fib1[n-2]

1597}

It is speeded up dramatically by writing: In[11]:=

fib2 [0]

= 1; fib2 [1] = 1;

In[12]:=

fib2[n_]

In[13]:=

Timing [fib2 [16]]

Oulf1~=

{0.133333 Second, 1597}

:= fib2[n]

= fib2[n-1]

+ fib2[n-2]

We run into problems when we try to calculate a larger Fibonacci number: In[14]:=

Timing[fib2[200]]

$RecursionLimit: :reclim: Recursion depth of 256 exceeded. $RecursionLimit: :reclim: Recursion depth of 256 exceeded. $RecursionLimit: :reclim: Recursion depth of 256 exceeded. General::stop: Further output of $RecursionLimit: :reclim will be suppressed during this calculation. Oulf1~=

{3.18333 Second, 96151855463018422468774568 Hold[fib2[73 - 2JJ + 155576970220531065681649693 Hold[fib2[74 - 2JJ +

334

3. Programming 96151855463018422468774568 Hold[fib2[73 - llJ + 155576970220531065681649693 Hold[fib2[74 - Ill}

Mathematica does not want to evaluate that one. Because it is easy to inadvertently produce infinite recursions, there is a safety mechanism: After a certain recursion depth, the calculation is interrupted. The depth is controlled by global variable $RecursionLimi t, which can be changed. (Courageous users can even set it to Infini ty.)

We are quite sure that our program terminates. Let us therefore increase $RecursionLimi t. For a fair comparison of the timings, the function f ib2 must be redefined. In[15}:=

$RecursionLimit = 1000

Out[15}= 1000

=

Clear[fib2]; fib2 [0]

In[17}:=

fib2[n_]

In[1B}:=

Timing [fib2 [200]]

Oulf1~=

{1.61667 Second, 45397369416530795319729696969741061923\ 3826}

:= fib2[n]

1; fib2 [1]

=

In[16}:=

= fib2[n-1]

1;

+ fib2[n-2]

For this specific task, an iterative algorithm is still faster. It starts for the value two and calculates the Fibonacci numbers "from bottom to top". In[19}:= In[20}:=

In[21}:=

fib3 [0]

=

1; fib3 [1]

=

1;

fib3 [n_] : = Module[{i, fn = 1, fn1 = 1, fn2}, Do [fn2 fn1; fn1 = fn; fn = fn1 + fn2, fn

{i, 2, nIl;

Timing [fib3 [200]]

Out[21}= {O. 533333 Second,

33826}

4539736941653079531972969696974106192\

The following version is even faster (see [Mae91)). It reduces the number of local variables to two, by working with lists. In[22}:=

fib4 [0]

=

1; fib4 [1]

1;

3.1 Programming Methodologies In[23]:=

In[24]:=

fib4 [n_] : = Modu1e[{fn1 = 1, fn2 = 1}, Do[{fn1, fn2} = {fn1 + fn2, fn1

fn1},

{n - 1}];

Timing [f ib4 [200] ]

Out[24]= {O. 316667 Second,

33826}

o

335

4539736941653079531972969696974106192 \

Summary Variable

Meaning

$RecursionLimi t

stop the evaluation after reaching this number of recursions

Table 3-1: The global variable for the maximum recursion depth



3.1.3 Functional Programming

In an interactive environment like Mathematica, results are being developed in steps. The procedural programming style is not very useful for this kind of work, because it uses flow control, which makes it hard to replace or insert parts of programs. The elements of afunctional program are functions, as the name implies. Their results are used as parameters or arguments of other functions. The whole program consists of nested function calls. Control structures can often be realized with iterators (as in Sum, etc.). An important tool of functional programs are the pure functions, which can be mapped or applied to lists (see Section 1.6.2). A functional program will, for instance, approximate Euler's constant by: In[1]:=

N[Sum[l/il,

Out[1]=

2.71828

{i, 0, 10}]]

It it quite competitive compared to the C-style program: In[2]:=

r = 1;

In[3]:=

For[i = 1, i 0

:= cis

:= c

laplace[a, t, s]

:= n!/sA(n+1)

I;

I;

I;

3.1 Programming Methodologies In[6]:=

In[7]:=

laplace [a_ / t_, t_, s_] : = Module [{tt}, Integrate [laplace[a, t, ttl,

337

{tt, s, Infinity}]

laplace [a_. Exp [b_. + c_. t_], t_, s_] : = laplace[a Exp[b], t, s - c] /; FreeQ[{b, c}, t]

This solves the following transfonnation very quickly: In[8]:=

laplace[t A 3 Exp[-3t], t, s]

Out[8]=

6 (3-:-~)4

The package Calculus' LaplaceTransform' contains a much more complete list of definitions. It therefore also takes longer (see Exercise 1).

o

In[9]:=

«Calculus' LaplaceTransform'

In[10]:=

LaplaceTransform[t A 3 Exp[-3t], t, s]

Out[10]=

---§----

(3 + s) 4

Exercise

1. Compare the tlmmgs of the above function laplace with LaplaceTransform from Calculus' LaplaceTransform', for some simple examples.



3.1.5 Programming with Constraint-Propagation

Transfonnation rules and definitions are directed. They are applied if a certain pattern matches. In some cases, it might be preferable to work with constraints. This is done by defining equations, which are solved with Solve. This does not mark any special direction; the equations can be solved for any chosen variable or parameter. Let us look at the equations for the trajectory of a particle, which is shot with an initial velocity vO at an angle a from the point (xO, yO, zO), in the gravitational field (g):

338 In[1}:=

3. Programming eqns = { x y z

xO + vO Cos [a] t, yO + vO Sin[a] t zO } ;

-

g t"2/2,

We might eliminate the time to get the parabola. In[2}:=

Solve [eqns, y, t]

Ouq~=

{{y -> (Sec[a]2 (-(g x 2 ) + 2 g x xO - g x0 2 + 2 v0 2 yO cos[a]2 + 2 v0 2 x Cos [a] Sin[a] 2 v0 2 xO Cos [a] Sin[a])) / (2 v0 2 )}}

We can also look for the initial conditions, such that after one second, the particle has flown one meter in the x and y directions each (for a given va). In[3}:=

Solve[eqns I. {x -> 1, y -> 1, z -> 0, t {xO, yO, zO}]

Out[3}=

{{xO -> 1 - vO Cos[a], yO -> ~_~_g_:_~_yQ_§~~l~l

zO

->

O}}

-> 1},

2

Or we can look for the angle a, which yields the longest x-distance, until the particle arrives at y = 0 (for a given initial position of Xo = Zo = 0, Yo = 1, and initial velocity Vo = 1). This can be solved by first eliminating the time and looking at the parabola. In[4}:=

parabola = Solve [eqns I. {xO -> 0, yO -> 1, zO -> 0, vO -> 1}, y, t]

Out[4}=

{{y->

§~~1~1:_i:i9_~:L_~_~_~g§~~1:_~_~_~_~g§1~1_§~~1~lL}} We now calculate the x values, at which the trajectories end (i.e., y = 0).

= Solve [y ==

0 /. parabola [ [1] ], x] II Simplify

In[5}:=

yZero

Ouq~=

{{x -> (-(Sqrt[2] Sqrt[Cos[a]2 (1 + 4 g - Cos[2 a])]) + Sin [2 a]) / (2 g)}, {x -> (Sqrt[2] Sqrt[cos[a]2 (1 + 4 g - Cos[2 a])] + Sin[2 a]) / (2 g)}}

3.1 Programming Methodologies

339

Because we look at the parabolas, there are two solutions, corresponding to the positive and the negative time direction. By using a numerical value for g, the endpoints-as a function of the angle a, from 0 to 90° -look as follows: In[6]:=

g = 9.81

Out[6]=

9 . 81

In[?]:=

Needs ["Graphics' Graphics' "]

In[8]:=

Plot[Evaluate[x /. yZero], {a, 0, Pi/2}, Ticks -> {piScale, Automatic}]

Oulf~=

-Graphics-

Only the positive time direction (with positive x-values) is of interest. It corresponds to the upper curve. We can select it by noticing that it is positive for a = O. In[9]:=

Select[x /. yZero, positive[# /. a -> 0]&]

Oulf~=

{0.0509684 (Sqrt[2] Sqrt[Cos[a]2 (40.24 - Cos[2 all] + Sin[2 all}

We look for the maximum of this function. Since this leads to a transcendental equation, we solve it numerically. In[10]:=

FindMinimum[-%[ [1]], {a, I}]

Out[10]= {-0.462887,

{a -> 0.21676}}

Notice that the optimal angle is not 45° = It/4 '" 0.785, because the initial position is not at the same height as the end position.

340



3. Programming

3.1.6 Data Types, Object-Oriented Programming

Mathematica does not ask/or data types. Despite that, arguments of functions can be restricted to certain "types", with patterns of the form x_ head, x_ ? test, or conditions like expr /; condition. By using the heads of objects, as in the example below, data types can therefore be simulated. Object-oriented programming is an alternative to modular programming: One does not collect functions which do similar things, but functions which operate on similar objects. One therefore defines objects, and afterwards methods which manipulate the objects. We might, for example, consider a function for printing. In a modular program, such a function contains code to print every possible object. In an object oriented program, in contrast, the object itself (e.g., a window) contains its printing code.

Mathematica allows us to associate definitions to certain "types" of objects (see Subsection "Associated Definitions" on page 259). This makes it possible to overload operators. The operator-in the example below: Equal-has a different meaning, which depends on the type of object it operates on. This is not possible in languages like Pascal or Modula-2.

Let us now look at an example which has nothing to do with mechanics or mathematics. As a side effect, it illustrates the elegance of Mathematica, even for "ordinary" programming tasks. We want to compare and sort lists of names. We start by introducing a "data type" name, which stands for objects containing two strings for the first and the last name. These objects shall be printed in a natural way: In[1]:=

name /: Format [name [f_String, I_String]] SequenceForm[f, " ", 1]

In[2]:=

name ["Stephen", "Wolfram"]

Out[2]=

Stephen Wolfram

:=

Such names shall now be compared. They are considered equal, if the first and the last names match. By associating the definition to the type name, we can overload the built-in function Equal. In[3]:=

Equal [name [fl_String, ll_String], name [f2_String, 12_String]] A:= fl

f2 && 11

12

3.1 Programming Methodologies In[4]:=

Equal [name ["Stephen", "Wolfram"], name ["Stephen", "Wolfram"]]

Out[4]=

True

In[S]:=

Equal [name ["Stephen", "Clinton"], name ["Stephen", "Wolfram"]]

Out[S]=

False

341

Unfortunately, associated definitions are only possible at the top level of the arguments. If a list of names should be sorted, overloading is not possible anymore--except by changing the Sort function "by force". We therefore define our own sort function by using the built-in Sort, and passing it a second parameter with a custom ordering function, which uses the last names first. In[6]:=

nameSort[x:{nameLString, _String] •• }] := Sort [x, OrderedQ[ { StringJoin[#1[[2]], #1[[1]]], StringJoin[#2[[2]], #2[[1]]] }]&]

In[7]:=

nameList = { name ["Stephen", "Wolfram"], name ["Stephen", "Clinton"], name["Bill", "Wolfram"], name["Bill", "Clinton"] };

In[8]:=

name Sort [nameList]

Ouq~=

{Bill Clinton, Stephen Clinton, Bill Wolfram, Stephen Wolfram}

342

3. Programming

• 3.2 Developing Programs Most nontrivial programs contain errors. Let us therefore first look at the techniques of debugging. Then, a couple of simple and educational packages will be developed, which the reader can use as a starting point for his or her own work.



3.2.1 Debugging

The functions Trace and Dialog are the main tools for debugging. Of course, in the case of simple programs, the function Print (see Table 2-37 on page 308) can also be quite useful.

o

Tracing the Evaluation

We have already met the function Trace in Section 2.4.1. Because its output usually is quite lengthy, it can be restricted to certain subexpressions. Let us consider the following calculation: In[1]:=

For[i = 1; j = 1; p 5, p < 1000, i++, p = Prime[j + i]; j = Floor[Sqrt[(p+1)A2]]]

The details of its evaluation can be visualized with Trace. In[2]:=

Trace[For[i = 1; j = 1; p = 5, p < 1000, i++, p = Prime[j + i]; j = Floor[Sqrt[(p+1)A2]]]]

ouq~=

{For[i

=

1; j

=

1; p

=

p = Prime[j + i]; j {i = 1; j = 1; p = 5, {p = 5, 5}, 5}, {{ p,

5, p < 1000, i++,

=

Floor[Sqrt[(p + 1)2]]], {i = 1, 1}, {j = 1, 1}, 5}, 5 < 1000, True},

{p = Prime[j + i]; j = Floor[Sqrt[(p + 1)2]], { { { { j, 1 }, { i, 1 }, 1 + 1, 2}, Pr ime [2], 3}, p = 3, {{{{{{p, 3}, 3 + 1, 1 + 3, 4}, 4 2 , 16}, Sqrt[16]'

3},

Sqrt[16], 4}, Floor[4], 4}, j = 4, 4}, 4}, { i ++ , { i, 1 }, {i = 2, 2}, 1 }, {{ p , 3}, 3 < 1000, True },

{p = Prime[j + i]; j = Floor[Sqrt[(p + 1)2]], { { { {j, 4}, { i, 2}, 4 + 2, 2 + 4, 6}, Pr ime [ 6], 13},

13, 13}, {{{{{{p, 13}, 13 + 1, 1 + 13, 14}, 14 2 , 196}, Sqrt[196] , Sqrt[196], 14}, Floor[14] , 14}, j = 14, 14}, 14}, {i++, {i, 2}, {i = 3, 3}, 2}, {{p, 13}, 13 < 1000, True}, p

=

343

3.2 Developing Programs

{p = Prime[j + i]; j = Floor[Sqrt[(p + 1)2]], { { { {j, 14 }, { i, 3}, 14 + 3, 3 + 14, 1 7 }, Pr ime [ 1 7] , 59}, p = 59, 59}, {{{{{{p, 59}' 59 + 1, 1 + 59, 60}, 60 2 , 3600}, Sqrt[3600], Sqrt[3600], 60}, Floor[60], 60}' j = 60, 60}' 60}' {i++, {i, 3}, {i = 4, 4}, 3}, {{p, 59}, 59 < 1000, True}, {p = Prime[j + i]; j = Floor[Sqrt[(p + 1)2]], { { { { j, 60 }, { i, 4 }, 60 + 4, 4 + 60, 64 }, Pr ime [ 64] , 311}, p = 311, 311}, {{{{{{p, 311}, 311 + 1, 1 + 311, 312}, 312 2 , 97344}, Sqrt[97344] , Sqrt[97344] , 312}, Floor[312], 312}, j = 312, 312}, 312}, {i++, {i, 4}, {i = 5, 5}, 4}, {{p, 311}, 311 < 1000, True}, {p = Prime[j + i]; j = Floor[Sqrt[(p + 1)2]], {{{{j, 312}, {i, 5}, 312 + 5, 5 + 312, 317}, Prime[317], 2099}, p = 2099, 2099}, {{{{{{p, 2099}, 2099 + 1,1 + 2099, 2100}, 2100 2 , 4410000}, Sqrt[4410000] , Sqrt[4410000] , 2100}, Floor[2100] , 2100}, j = 2100, 2100}, 2100}, {i++, {i, 5}, {i 6, 6}, 5}, {{p, 2099}, 2099 < 1000, False}, Null}

This is a lot of output. We might just want to trace the evaluations of j : In[3}:=

Trace[For[i = 1; j = 1; p = 5, p < 1000, i++, p = Prime[j + i]; j Floor[Sqrt[(p+1)A2]]], j]

Out[3}=

{ { { { { {j,

{{{{{j,

1}}}}}, {{ { { {j, 4}}}}}, {{ { { {j, 14}}}}}, 60}}}}}, {{{{{j, 312}}}}}}

The output can be restricted to any suitable pattern, which is given as a second argument (as the j, above), In[4}:=

Trace[For[i = 1; j = 1; p = 5, p < 1000, i++, p = Prime[j + i]; j Floor[Sqrt[(p+1)A2]]], p = -]

Out[4}=

{{{p = 5}}, {{p 3}}, {{p = 13}}, {{p = 311}}, {{p = 2099}}}

All definitions are listed by:

{{p = 59}},

344

3. Programming

In{5]:=

Trace[For[i = 1; j = 1; p = 5, p < 1000, i++, p = Prime[j + i]; j Floor[Sqrt[(p+1)A2]]],

- = -] Out{5]=

{ { {i = 1}, { j = 1}, {p = 5}}, {{ p = 3}, { j = 4}}, {{i 2}}, {{p = 13}, {j = 14}}, {{i = 3}}, {{p 59}, {j = 60}}, {{i = 4}}, {{p 311}, {j = 312}}, {{i = 5}},

{{p

2099},

{j

=

2100}},

{{i

=

6}}}

The options listed in Table 3-3 allows us to gain an even more detailed control over the tracing. In{6]:=

Out{6]=

Trace[For[i = 1; j = 1; p = 5, p < 1000, i++, p Prime[j + i]; j Floor[Sqrt[(p+1)A2]]], TraceOn -> Floor]

=

{{{{Floor[4], 4}}}, {{{Floor[14], 14}}}, {{{Floor[60], 60}}}' {{{Floor[312], 312}}}, {{{Floor[2100J, 2100}}}}

This traced every evaluation of Floor.

D

Dialogs

Mathematica even allows us to directly manipulate and debug running programs, with dialogs. Several methods can be used to initiate such a dialog:

• by the selection of the corresponding command of the front end (i n s pee t, Enter Inspector Dialog, etc.) or after the interruption of a calculation with and c, • with TraceDialog, • by a Dialog command in the program. Let us illustrate this with a long calculation, which is interrupted after a couple of seconds (Interrupt Calculation... , and c, etc.). In{?]:=

Do[n = N[Sqrt[i]]'

{i, 100000000}]

The command Enter Dialog or ins pect can now be used to start a Mathematica subsession-the original calculation stays interrupted during the dialog. With normal Mathematica commands, the current values can be inspected, for instance, i and n.

345

3.2 Developing Programs (Dialog) In[B]:=

i (Dialog) Out[B]=

4271 (Dialog) In[9]:=

n (Dialog) Out[9]=

65.3452

The dialog is closed with a Return []

command or the corresponding command of the front end (Exit Dialog). The long calculation should probably be aborted after that. This changes In!7]:= to:

= N[Sqrt [i]],

In[10]:=

Do [n

Out[7]=

$Aborted

{i,

lOOOOOOOO}]

TraceDialog starts a dialog for every expression used in the evaluation. This usually is too much of the good. In the next example, it is therefore restricted to a pattern of the form y = a_ . + _ A4. In[B]:=

y = t; TraceDialog[Do[y y = a_. + _ A4]

Expand[(y + i)A2],

{i, 5}],

TraceDialog::dgbgn: Entering Dialog; use Return[ 1 to exit.

Ouq~=

y

=

9 + 12 t + 10 t 2 + 4 t 3 + t 4

Let us inspect the value of i: (Dialog) In[10]:=

i (Dialog) Out[10]=

2

We can now change anything we want. For instance, the parameter t can be set to 1.

346

3. Programming

(Dialog) In[11]:= t 1

=

(Dialog) Out[11}=

1

Again, the dialog is left by: Return[]

This gives us a numerical value, instead of a polynomial, for y. In[9]:=

y

Oulf~=

5408554896900

The Dialog command starts a dialog, when it is met. In[10]:=

f [0]

In[11}:=

f[n_]

In[12}:=

f [5]

= 1;

:= (If[n==3, Dialog[]]; n f[n-l])

We might now use the function Stack to see the list of the heads of all expression which are currently being evaluated. (Dialog) In[13}:=

Stack [] (Dialog) Out[13}=

{CompoundExpression, Times, CompoundExpression, Times, CompoundExpression, Dialog}

Stack [pattern] returns the list of expressions matching pattern. Everything which is currently being evaluated is given by: (Dialog) In[14}:=

Stack[_] (Dialog) Out[14}=

{If [5 == 3, Dialog [ ]]; 5 £ [5 - 1], 5 £ [5 - 1], If[4 3, Dialog[]]; 4 £[4 - 1], 4 £[4 - 1], If [3 == 3, Dialog [ ]]; 3 £ [3 - 1], Dialog [] }

or all multiplications by:

347

3.2 Developing Programs (Dialog) In[15]:=

Stack [Times L] ] (Dialog) Out[15]= {5 f [5 -

1],

4 f [4 -

1]}

Again, Return[]

closes the dialog and inserts a line Out[12}=.

o

Summary

Expression

Meaning

Dialog []

open a dialog

Dialog [expr]

open a dialog with expr as the value of %

TraceDialog [expr]

open a dialog for every expression which is used for the evaluation ofexpr

TraceDialog [expr, pattern]

open a dialog for every expression matching pattern, which is used for the evaluation of expr

Stack []

show the current evaluation stack

Stack [pattern]

list the expressions currently being evaluated and matching pattern

Return []

exit the dialog, using % as the return value

Return [expr]

exit the dialog, using expr as the return value

Trace [expr]

list all expressions used in the evaluation of expr

Trace [expr, pattern]

list all expressions used in the evaluation of expr that match pattern

Trace [expr, s]

list all expressions used in the evaluation of expr and which are associated to s

Table 3-2: Debugging Option

Default

Meaning

MatchLocalNames

True

x can stand for x$nnn

TraceAbove

False

show the evaluation chains which contain the chain matching pattern

Table 3-3: The options for Trace (using pattern)

348

3. Programming

Option

Default

Meaning

TraceBackward

False

show the expressions which precede pattern in the chain

TraceDepth

Infinity the maximum nesting of the traced chains

TraceForward

False

show the expressions which come later than pattern in the chain

TraceOff

None

switch off tracing for expressions matching pattern

TraceOn

-

start tracing when pattern is encountered (only)

TraceOriginal

False

the form of the expressions is tested before its head and its arguments are evaluated (if set to True)

Table 3-3: The options for Trace (using pattern)

o

Exercise

1. Experiment with dialogs .



3.2.2 Example: NonNegativeQ'

We start our programming examples by writing a package which exports a function NonNega ti veQ. It shall return True when a symbol definitely cannot be negative-e.g., lal, or a 2 with a being real-and False in all other cases. This will be of great help for extending the Abs and Arg functions to complex symbols (see Section 3.2.3). The reader may compare his or her solution to Exercise 2 in Section 2.5.2 with the function NonNegativeQ developed in this section.

Mathematica contains the functions Posi ti ve, Negati ve, and NonNegati ve. They only evaluate for numbers (in Version 2.2 of Mathematica). Let us use them to define properties of symbols as well, for instance: {n[t]:=

p I: Positive[pl = True;

This gives a first definition for NonNegati veQ: {n[2]:=

NonNegati veQ [x_ 1 : = True I; Posi ti ve [xl

I I NonNegative [xl

General::spelll: Possible spelling error: new symbol name

3.2 Developing Programs

349

"NonNegativeQ" is similar to existing symbol "NonNegative". In[3}:=

NonNega t i veQ [p]

Out[3}=

True

We use this definition as a starting point for the package. Its context shall be named SKPackages'NonNegativeQ'. This implies that the file must be named Non Neg at i v eO. mand be put into a directory S KPac k age s . According to the prototype of a package (see Section 2.5.2), let us therefore save the following lines in this file: BeginPackage["SKPackages'NonNegativeQ'''); Off [General: :spelll); NonNegativeQ: :usage = "NonNegativeQ[expr) returns True if expr is obviouslY,not negative and else False. Properties of symbols can be defined with the functions Positive, NonNegative and Negative (e.g., x /: positive[x) = True). Real symbols can be declared by definitions like a /: Im[a) = 0"; On[General: :spelll); Begin["'Private''') ; NonNegativeQ[x_)

.- True /; Positive[x)

NonNegativeQ[x_)

.- False

II

NonNegative [x)

End [) ; EndPackage[) ;

The Off [General: : spelll) suppresses the above warning (see Table 2-49 on page 327).

The directory S KPac k age s must be on the search path of Mathematica. The path can be configured (see Section 1.8.10) and depends on the computer system. We might choose our home directory (~) on a UNIX system, or the directory Pac k age s. On a notebook front end, we have to format every input cell as an initialization cell (see Subsection "Formatting Packages" on page 305). We now remove the symbol NonNegativeQ from the context Global', and load the skeleton package. In[4}:=

Remove [NonNegativeQ]

350

3. Programming

In[5]:=

< 256

.-

In[22]:=

rSADecode [I_List, d_ Integer, n_ Integer] : = listToString [rSADecodeNumber [#, d, n]& /@ 1]

This simplifies the work of the sender and of the receiver considerably. In[23]:=

rSAEncode ["A message", e, n]

Oulf2~=

{232777853355630, 119102268498990}

In[24]:=

rSADecode [%, d, n]

Out[24]= A message

3.2 Developing Programs

359

The above definitions can be combined into the package SKPackages 'RSA ' , by capitalizing the initial letters of the function names, and adding the documentation strings and the context commands. The package which comes with the software to this book (see Subsection "Software" on page 5) basically consists of these functions. Additionally, it also contains two more tools for the generation of large primes, which we will discuss in Section 3.4.1. In[25]:=

«SKPackages' RSA'

In[26]:=

RSAEncode ["Another message", e, n]

Oulf2~=

{219477757962283, 217133284251131, 232771246315198}

In[27]:=

RSADecode [%, d, n]

Out[27]= Another message



3.2.5 Example: Perturbation \

The modelling of physical systems typically leads to differential equations which cannot be solved symbolically. The most powerful computer algebra system will not resolve that problem. One has to be satisfied with numerical or approximate solutions. Unfortunately, numerical solutions are not very useful for the understanding of parameter-dependencies, because one often gets data sets which can only be visualized in two or three dimensions. In contrast to that, suitable approximate solutions can display the main physical properties in formulas. These formulas are capable of showing difficult relationships in a compact fashion. In this section, we want to give a short and compact introduction to the method of producing approximate solutions by series expansions. We will put together the foundation of a package, which belongs to the distributed software (see Subsection "Software" on page 5). A complete coverage of these methods fills whole books, for example: [KS78], [Nay73], [NayS 1], [EK94], or [RAS7]. Let us assume that our differential equation contains a small parameter oscillation with a slightly nonlinear spring:

x+ x + EX 3 = o.

E.

It could be an

(3.1)

We will try to solve this equation by a series expansion of the form (3.2) By substituting (3.2) into the left hand side of Equation (3.1), we get a power series in E. Since it has to vanish for every (small) E, the coefficient of every power of E has to vanish. This gives us a sequence of coupled differential equations. We assume that the first one (for xo) can be solved for the given initial conditions. This solution will then appear as an inhomogeneity in the equation for Xl. In this way, the equations can be solved step by step up to a certain order, and the sum (3.2) should be an approximation of the solution of Equation (3.1).

360

3. Programming

For an implementation of this process in M athematica, we start by combining the differential equation and the initial conditions as a list. In{1]:=

equations = {x" [t] + x[t] + eps x[t] A3 -- 0, x[O] == 1, x' [0] == O}

Out{1}=

{x[t]

+ eps x[t]3 + x"

[t]

==

0,

x[O]

==

1, x' [0]

==

O}

We now have to replace the function x [ t] and its derivatives by a polynomial in E. Let us recall that the pattern for derivatives has the following form (see Table 2-43 on page 318): In{2}:=

FullForm[x '

I

[t]]

Out{2}IIFuIIForm= Derivative [2] [x] [t]

We can therefore use In{3}:=

equations /. {

x[t_] -> Swn[epsAi x[i] [t], {i, 0, 2}], Derivative [n_] [x] [t_] -> Sum[epsAi Derivative [n] [x[i]] [t], {i, 0, 2}] } Out{3}=

{x[O] [t] eps

+ eps x[l] [t] (x[O][t]

(x[O])"[t] 0,

x[O] [0]

(x[O]) '[0]

+ eps2 x[2] [t]

+ eps x [ l ] [ t ]

+ eps

(x[l])"[t]

+ eps x[l] [0] + eps

+

+ eps2 x[2][t])3 +

+ eps2

(x[2])"[t]

+ eps2 x[2] [0]

(x[l])' [0]

+ eps2

==

1,

(x[2])' [0]

==

O}

to substitute a quadratic polynomial, for instance. (It would be possible to combine the function and its derivatives into a single pattern, by replacing the head x by a pure function. But this has the disadvantage that it only works for the differential equations, and not for the initial conditions.) We now extract the list of the equations corresponding to the different powers of E. This function is called polyOrderList (poly, because one could also use more general functions of E). It expects as arguments a list of equations, the unknown function, the small parameter, and the maximum order.

361

3.2 Developing Programs In[4]:=

polyOrderList [equations_List, x_, eps_, maxOrder_Integer] := Module[{j, h = Head [x] , substEqu}, substEqu = equations I. {

h[t_] -> Sum[epsAi h[i] [t], {i, 0, maxOrder}], Derivative [n_] [h] [t_] -> Sum[epsAi Derivative[n] [h[i]] [t], {i, 0, maxOrder}] } I I ExpandAll; Table[Map[Coefficient[#, eps, j]&, substEqu, {2}], {j, 0, maxOrder}]

In our example, it returns the following equations, up to the order 2: In[5}:= Out[5}=

= polyOrderList [equations, x[t], eps, 2] { {x [ 0] [t] + ( x [ 0] ) [t] == 0, x [ 0] [0] == I, (x[O]) [0] == OJ, {x[O] [t]3 + x[l] [t] + (x[I]) [t] == 0, x[l] [0] == 0, (x[I]) [0] == O}, {3 x[O] [t]2 x[l] [t] + x[2] [t] + (x[2]) [t] == 0,

eqnList

I

I

I

I

I

I

I

x[2] [0]

== 0,

(x[2])

I

[0]

I

== O}}

These equations shall now be solved step by step. We try to think functionally and develop a function which takes the solution of one order and produces the solution of the next order. The solutions are treated as transformation rules containing pure functions, analogous to DSol ve (see Out[50)= on page 75). In[6}:=

DSolve[eqnList[[1]], x[O], t] II Simplify

Ouq~=

{{x[O]

-> Function[t,

Cos[t]]}}

The solutions of the different orders are combined into lists. We begin with the order O. = % [ [1] ]

In[7}:=

r

Ouq~=

{x[O]

-> Function[t,

Cos[t]]}

With the help of sol veOrder, the solution of the next order is added. In[B}:=

solveOrder[rule_, equation_] := Append [rule, DSolve[equation I. rule, x[Length[rule]], t] [[1, 1]]] II Simplify

In[9}:=

solveOrder [r, eqnList [[2]]]

Ouq~=

{x[O]

-> Function[t, Cos[t]],

362

3. Programming

x[l]

-> Function[t,

-(Sin[t] (6 t + Sin[2 t])) ------------16------------]}

This function can now be folded with the list of equations. The starting point has to be an empty result list. In[10]:=

polyOrderSolutionRuleListPure [equations_List, x_, t_, eps_, maxOrder_Integer] := Module[{h = Head[x], solveOrder}, solveOrder[rule_, equation_] := Append [rule, DSolve[equation I. rule, h[Length[rule]], t] [[1, 1]]] II Simplify; Fold [solveOrder, {}, polyOrderList[equations, x, eps, maxOrder]]

In[ll]:=

polyOrderSolutionRuleListPure [equations, x[t], t, eps, 2]

Out[ll]= {x[O]

-> Function[t, Cos [t]],

.

- (Sin[t] (6 t + Sin[2 t])) ------------16------------],

x[l]

-> Functlon[t,

x[2J

-> Function[t, (23 Cos[tJ - 72 t 2 Cos[t] 24 Cos[3 t] + Cos[5 tJ + 96 t Sin[t] 36 t Sin[3 tJ) / 1024J}

-

The solution of these differential equations take some time. It is therefore a good idea to inform the user about what is going on at the moment. This can be done with Print commands. Furthermore, the cases should be caught, where a symbolic solution is not found. Particularly, it sometimes happens that the initial conditions cannot be met-if the small parameter multiplies the highest derivative. Let us add an error message for this: In[12]:=

perturbation:: inising = "The differential equation of order '1' does not have a solution which satisfies the given initial conditions. Consider attempting a singular perturbation.";

The refined function now looks like this: In[13]:=

polyOrderSolutionRuleListPure [equations_List, x_, t_, eps_, maxOrder_Integer] := Module[{h = Head[x], solveOrder}, solveOrder[rule_, equation_] := Module[{i, res}, If [! FreeQ [rule, "error"], Return ["error"] ] ; i = Length[rule]; Print["Solving equation of order ", i, " •.. "];

3.2 Developing Programs

363

res = DSolve[equation I. rule, h[i], t] II Simplify; Which [ !FreeQ[res, DSolve], Return ["error"] , res == {}, Message[perturbation::inising, i]; Return ["error"] , True, Append [rule, res[[l, 1]]] ];

Fold [solveOrder, {}, polyOrderList[equations, x, eps, maxOrder]]

For the above equation, we now get: In[14}:=

polyOrderSolutionRuleListpure[equations, x[t], t, eps, 2]

Solving equation of order 0 Solving equation of order 1 Solving equation of order 2 Out[14}= {x [0]

-> Function [t, Cos [t]] ,

. -(Sin[t] (6 t + Sin[2 t])) x[l] -> Functlon[t, ------------16------------], x[2] -> Function[t, (23 Cos[t] - 72 t 2 Cos[t] 24 Cos[3 t] + Cos[5 t] + 96 t Sin[t] 36 t Sin[3 t]) I 1024]}

The next case activates the error message. In[15}:=

polyOrderSolutionRuleListPure [ {eps x" [t] + x' [t] + x[t] == 0, x[O] -- 1, x' [0] -- O}' x [t], t, eps, 2]

Solving equation of order 0 ... perturbation::inising: The differential equation of order 0 does not have a solution which satisfies the given initial conditions. Consider attempting a singular perturbation. Out[15}= error

The user might not want the solutions in the form of pure functions, but rather as a list of the actual solutions in the different orders. This is returned by:

364 In[16]:=

3. Programming polyOrderSolutionList [equations_List, x_, t_, eps_, maxOrder_Integer] :=

Module [ {

h = Head [x] ,

pure = polyOrderSolutionRuleListPure[equations, x, t, eps, maxOrder] },

If [! FreeQ [pure,

"error"], Return ["error"]] ;

Drop [FoldList [Plus, 0, Table[epsAi h[i] [t] In[17]:=

/. pure, {i, 0, maxOrder}]], 1]

straight = polyOrderSolutionList[equations, x [t] , t, eps, 2]

Solving equation of order 0 Solving equation of order 1 Solving equation of order 2 Oulf1~=

{Cos[tj, Cos[tj -

(6 t + Sin[2 tj) ------------16-------------,

eps Sin[tj

Cos[tj - ~P§-§~~1~1-1~6~-~-§~~1~-~lL + (eps 2 (23 Cos[tj - 72 t 2 Cos[tj - 24 Cos[3 tj + Cos[5 tj + 96 t Sin[tj - 36 t Sin[3 tj)) / l024} In[18]:=

Plot[Evaluate[straight /. eps -> .1], {t, 0, 10}, PlotStyle -> {Dashing[O], Dashing[{.l, .OS}], Dashing[{.OS, .OS}]}]

10

Oulf1~=

-Graphics-

365

3.2 Developing Programs

These functions can be used as a starting point for the package. We capitalize their first letters, and add documentations and the context commands. The package SKPackages' Perturbation' contains the result, and some more techniques: Expansions of the form (3.2), straight forward expansion, most often contain terms which grow polynomially (secular terms); they are useful for "small" times only, up to about 1/£. Let us look at the above solution in the case of £ = 0.5. It is instructive to plot it in the phase space of x and its time derivative. In[19]:=

ParametricPlot [Transpose [ {straight, D[straight, t]}] I. eps -> .S II Evaluate, {t, 0, 10}, PlotStyle -> {Dashing[O], Dashing[{.l, .OS}], Dashing[{.OS, .OS}]}]

/

/

--- -- /",2

" -'-

-Graphics-

"-

~

-0.5

Oulf1~=

...........

...........

---

\

).5

Except for the order zero, which corresponds to the linear pendulum, all solutions diverge for large times t. This does not make sense physically, because the system is conservative and its energy will not grow. One needs refined methods to handle such resonance effects. One of the simplest uses a power series (in £) for the frequency, as well. The coefficients of this series are then chosen such that the secular terms vanish. This is called the method of strained coordinates. It is implemented as the function StrainedSolutionList in the package SKPackages' Perturbation' . In[20]:=

Needs [" SKPackages' Perturbation' "]

In[21]:=

strained = StrainedSolutionList [ equations, x[t], t, eps, 2] Solving equation of order 0 ... Removing secular terms of order 0 ... Solving equation of order I ...

366

3. Programming Removing secular terms of order 1 Solving equation of order 2 ... Removing secular terms of order 2

Out[21}= {Cos [t],

Cos [t] eps Sin[(l + ~_§2§) t] Sin[2 (1 + ~_§2§) t]

--------------------16---------------------

Cos[t] eps Sin[(l + ~_§2§) t] Sin[2 (1 + ~_§2§) t]

--------------------16---------------------

+

2

(eps 2 Sin[(l + ~_§2§ - ~!25~§-) t] 2 (23 Sin[2 (1 + ~_§2§ - ~!25~§-) t] -

Sin[4 (1 +

~_§2§

-

~!25~§~)

t])) I 512}

These solutions behave decently for large times and resemble the physical reality. In[22}:=

ParametricPlot [Transpose [ {strained, D[strained, t]}] I. eps -> .5 II Evaluate, {t, 0, 10}, PlotStyle -> {Dashing [{}], Dashing [{ .1, • OS}] , Dashing [ { . OS, • OS} ] } ]

0.5

-0.5

Oulf22}= -Graphics-

The problem of initial conditions which cannot be satisfied (see Out[15}=) can also be solved. This is done be introducing boundary layers, where the coordinates are "blown up" appropriately (e.g., by scaling t to tie). The solutions are then developed in this boundary layer and outside. They can be combined to give a matched and composite solution. The function MatchedSolutionList does that.

367

3.2 Developing Programs In[23]:=

MatchedSolutionList [ {eps x" [t] + x' [t] + x[t] == 0, x[O] tau == t/eps, x[t], t, tau, eps, 1]

a, x[1]

Preparing Solving outer equation of order 0 Solving inner equation of order 0 Matching order 0 ... Solving outer equation of order 1 Solving inner equation of order 1 Matching order 1 ... Calculating composite solution " . Setting initials ...

- b E + ~-=-~-~ b E1 - t + a------E t / eps E tleps ' (a - b E) t b El - t eps - b El - t/eps eps + ----------E tleps b El - t eps t}

Oulf2~= {b El -

t

+

-- b}'

3. Programming

368

• 3.3 Numerics Programs doing numerical calculations surely will not run as fast in Mathematica as in a compiled language, like C or Fortran. But the development is much quicker and easier in its interactive and rich environment. It therefore pays off-even for large programs-to develop and test the algorithms in Mathematica, and to tum to the faster languages only if the computing times start becoming too long. Mathematica even allows the compilation of numerical expression, which can speed up things considerably. We will talk about this technique in Section 3.3.1.

In contrast to compiled languages, Mathematica can also handle any desired precision. This will be covered in Section 3.3.2. There is a large number of built-in numerical functions (NDSol ve, NIntegrate, etc.). They all contain a lot of options, which can be used for the control of more subtle aspects of the algorithms. These are treated in Section 3.3.3.



3.3.1 Compiling Expressions: Fractals

Mathematica's expression compiler can be illustrated by the calculation of fractals. This brings some color into our work.

Let us again look at Newton's method for the search of zeros of functions (see Section 2.4.3). We start, for instance, with the following polynomial: In[1]:=

f[z_J

= z"5 - 1

Out[1}=

-1 + z5

Its derivative is: In[2}:=

fp [z_ J = D [f [z J I

Out[2}=

5 z4

Z

J

As we have seen in Section 2.4.3, one step of Newton's method consists of the application of the pure function

369

3.3 Numerics

=

In[3]:=

fl

Function[{z}, z - f[z]/fp[z]]

Out[3]=

Function[{z}, z -

~~lh]

to the last approximation of the zero. The fixed point of this iteration is the root. In[4]:=

FixedPoint [fl, 2.]

Out[4]=

1.

We can further speed up the calculation by forcing the evaluation of the expression in the pure function, so that it does not need to be calculated for every step. In[5]:=

f2 = Function[{z}, Evaluate[z - f[z]/fp[z]]]

Out[5]=

-1 + z5 Function[{z}, z - -------]

In[6]:=

FixedPoint [f2, 2.]

Out[6]=

1.

In[7]:=

Do [FixedPoint [fl, 2.],

Oulfn=

{1.38333 Second, Null}

In[B]:=

Do [FixedPoint [f2, 2.],

Oulf~=

{O.8 Second, Null}

5 z4

{lOO}]

II Timing

{lOO}] II Timing

The Compile tool can be used to write pure functions that primarily contain numerical calculations in a compiled form, which evaluates considerably faster. Its syntax is analogous to the above pure function.

= Compile[{z},

In[9]:=

cl

Evaluate[z - f[z]/fp[z]]]

Out[9]=

-1 + z5 CompiledFunction[{z}, z - ----4--' -CompiledCode-] 5 z

In[10]:=

FixedPoint[cl, 2.]

Out[10]= 1. In[11]:=

Do [FixedPoint [cl, 2.],

Out[11]= {O. 1 Second,

{lOO}]

II Timing

Null}

This speedup is achieved by passing compiled functions quite directly to the processor or the numerical coprocessor-with the disadvantage that their precision cannot be controlled anymore. They just use machine-precision arithmetic (see Section 3.3.2).

370

3. Programming

Let us now extend our algorithm to the complex plane. The polynomial has five complex roots. In[12}:=

n

= Exponent [f [xl,

xl

Out[12}= 5

They all lie on the unit circle. We can start at a chosen point of the complex plane, and ask, to which fixed point Newton's method (see Equation (2.1) on page 282) will converge. At first, our implementation will cause problems, because Compile expects real, numerical values, when used in the above form. In[13}:=

cl [1. + Il

CompiledFunction::cfr: Argument 1. + I at position 1 should be a machine-size real number. Out[13}= O. 75 + O. 8 I

We have to explicitly state that z is complex. This is done as follows (see also Table 3-4): In[14}:=

c2

=

Compile[{{z, _Complex}}, Evaluate[z - f[z]/fp[zll]

Out[14}= Compi ledFunction [ {z} , In[15}:=

c2 [1. + I]

Oulf1~=

0.75 + 0.8 I

-1 + z5 z - ----4--' -CompiledCode-) 5 z

Of course, the calculation with complex numbers will double the timings. In[16]:=

Do [FixedPoint [c2, 2.],

Oulf1~=

{0.2 Second, Null}

{lOO}] II Timing

At the origin, the tangent to the function is horizontal. This poses the danger of a numerical overftow--even though the evaluation of c2 does "work", without the problems it should actually have. In[17]:=

c2 [0 • ]

Out[17}=

o.

+ O.

I

371

3.3 Numerics

We can bypass the problematic cases by moving points, which lie very close to the origin, to a point far out "by hand", and by keeping points with very large absolute values there. This produces a fast convergence of the points with possible numerical problems. A first try might look as follows: In{18j:=

c3 = Compile [{ {z, _Complex}}, Which [ Abs[z] < 10."-10, 10."20, Abs[z] >= 10."10, 10."20, True, Evaluate[z - f[z]/fp[z]]]]

Oulf1~= CompiledFunction[{z}, Which[Abs[z] 10

Abs[z] >= 10. ,10. -CompiledCode-]

20

10.- 10 , 10. 20 , f[z] ,True, Evaluate[z - fp[zl]]'
= 10. "10, 10. "20, True, expr] 1 ]

-10 ,10. 20 , CompiledFunction[{z}, Which[Abs[z] < 10. -1 + z5 Abs[z] >= 10. 10 ,10. 20 ,True, z - - - - - r - ] ' 5 z -CompiledCode-]

Despite the conditional, the timing is still remarkable: In{20j:=

Do [FixedPoint [comp, 2.],

{1 0 O}]

/ / Timing

OUlf20= {0.233333 Second, Null}

As a next step, each fixed point (i.e., zero of the polynomial) is given a color. We do this by mapping the color circle to the complex plane and using the argument of the complex number for the coloring. The corresponding function findColorOfPoint has a second parameter, which contains the maximum number of colors. It can be used to split the color circle into the necessary number of sectors.

3. Programming

372 In[21]:=

findColorOfPoint [e_, max_] : = If[Abs[e] >= 10"10, Hue[l, 0, 0], Hue[Round[N[Arg[e] max/(2 Pi)]]/N[max]]]

The points with a large absolute value (see In[1B]:=) are mapped to black.

Finally, we use a grid on the complex plane as initial values for the iteration and find the corresponding fixed points. The initial points are colored according to "their" fixed points. In[22]:=

generateTable [comp_, {left_, right_, horStep_}, {bottom_, top_, vertStep_}, max_] := Table [ findColorOfPoint[FixedPoint[comp, N[x + I y]], max], {y, bottom, top, vertStep}, {x, left, right, horStep}]

We deliberately changed to order of the iterators. This is because we want to use the table for a picture with RasterArray. The function RasterArray fills the rows from bottom to top. The rows correspond to our x-coordinate (the real part).

~

Let us, for instance, calculate the following table: In[23]:=

points = generateTable [comp, {-1., 1.,

.OS},

{-1., 1.,

.OS}, n];

This table contains Hue values for the colors. RasterArray can directly use them to produce a picture. In[24]:=

Show [Graphics [RasterArray[points]], AspectRatio -> Automatic]

3.3 Numerics

373

Out[24}= -Graphics-

The whole calculation can be combined in a single function. We use the exponent n of zn - 1 as a parameter. In[25}:=

showFractal [exponent_Integer? (#>1&), {left_, right_, horStep_}, {bottom_, top_, vertStep_}] := Module[{z, f, fp, comp, findColor}, f = zAexponent - 1; fp = D [f, z]; comp = With[{expr = z - f/fp}, Compile[{{z, _Complex}}, Which [ Abs[z] < 10.A-10, 10.A20, Abs [z ] > = 10. A10, 10. A2 0 , True, expr]]]; findColor[e_] := If[Abs[e] >= 10 A10, Hue[l, 0, 0], Hue [Round[N[Arg[e] exponent/(2 pi)]]/N[exponent]]]; Show [ Graphics [RasterArray[Table[ findColor[FixedPoint[comp, x + I y]], {y, bottom, top, vertStep}, {x, left, right, horStep}]]], AspectRatio -> Automatic]]

In[26}:=

showFractal[6, {-.2,

.2,

.01}, {.7,

.9,

.OOS}]

3. Programming

374

Oulf2~=

-Graphics-

A finer grid-and more patience-produces more detailed pictures, for instance in the case n = 7, the Color Plate 5 on page IV. The function has to be slightly modified for negative exponents (see Exercise 3). By choosing z-7-1, we get the Color Plate 6 on page IV. We have to use a lot of memory for these calculations: Each point is saved as a Hue object with its color specifications. To save large fractals to files, it is therefore advisable to write a number for the color into the table, instead of the whole Hue object (see Exercise 5). The Newton iteration leads from a starting point, over several points of the plane, to the fixed point. One might try to color all the points which are passed by each iteration, to save time. Depending on the number of grid points, this can improve the timings slightly, but it does not always help. The disadvantage of such an algorithm are the disturbances on the fractal borders, which arise because the algorithm uses points which are not lying exactly on the grid. FindRoot also uses Newton's method, and does work for complex numbers. The advantage of our program is the better control over the algorithm and the improved efficiency for these very special iterations (see Exercise 4).

375

3.3 Numerics

o

A Possible Problem I am trying to compile a vector function:

'B'

In[1]:=

{x"2 + y"2, ArcTan[y/x]}]

c = Compile[{x, y},

Compile: : cph:

2 Expression {x

2 + y

y , ArcTan[-]} with head List

x cannot be compiled.

Out[1}= CompiledFunction [{x, y}, {x 2 + y2, ArcTan [~] } , -CompiledCode-]

What is wrong here? Lists cannot be compiled (in Version 2.2 of Mathematica). You have to compile the components:

h

In[2]:=

c = Compile[{x, y}, #]& /@ {x"2 + y"2, ArcTan[y/x]}

ouq~=

{CompiledFunction[{x, y}, x 2 + y2, -CompiledCode-], CompiledFunction[{x, y}, ArcTan[~], -CompiledCode-]}

o

In[3}:=

Through [c [1, 1]]

Ouq~=

{2., O.785398}

Summary

Expression Compile [ {xl' x2'

Meaning

... } ,

a compiled pure function (of type CompiledFunction); the xi must be numerical variables

expr]

... },

Compile [ { {xl' tl },

{X2'

Compile [vars, expr,

{{PI' ptl} ,

t2},

expr]

... } ]

a compiled function with variables xi of the type ti; the possible types are: - Integer, - Real, - Complex, True I False a compiled function, where subexpressions of expr, matching the pattern Pi' are of type pti

Table 3-4: Compiled functions

376

o

3. Programming

Exercises

1. Estimate the memory needed to save a fractal of the size of your screen (e.g., lOOOxlOOO points).

2. Generate other fractals for polynomials of the form zn-1. 3. What needs to be changed for the handling of negative exponents? Generate some fractals for negative exponents. 4. Write a program which uses FindRoot. Compare the results and the timings. 5. Write a program which saves fractals in a compact fashion to a file. How can you produce the corresponding pictures? 6.



Write a program which accepts exponents other than integers.

3.3.2 Precision and Accuracy

Mathematica distinguishes two types of numerical numbers: machine-precision numbers and arbitrary-precision ones. If nothing is said explicitly, then machineprecision is used. This type of arithmetic is advantageous because of its efficiency.

The function Precision returns the precision, which is the number of significant decimal digits in a number. In[1}:=

{Precision[3.], Precision[N[Pi]]}

Out[1}=

{16, 16}

The number of digits used for machine-precision depends on the computer type. It is typically between 16 and 19 digits.

If we explicitly give or ask for more digits, Mathematica changes to arbitraryprecision arithmetic. In[2}:=

{Precision [3.00000000000000000000000000000], Precision[N[Pi, 25]]}

Out[2}=

{ 3 0,

25}

Mathematica keeps track of the possible precision within every calculation. It is therefore not possible to start with machine-precision and to ask for a result with higher precision later on.

377

3.3 Numerics In[3]:=

N [Sqrt [3 . 0], 30]

Oulf~=

1.732050807568877

In[4]:=

Precision [%]

Out[4]=

16

The command SetPrecision fixes the precision of numerical values. If not enough digits are available, it uses padding with binary zeros. In[5]:=

r

3.2;

In[6]:=

r

SetPrecision[r, 30];

In[7]:=

Precision [r]

Out[7]=

30

In general, the binary zeros are not decimal zeros. 30]

In[8]:=

N [r ,

Oulf~=

3.20000000000000017763568394003

Let us now subtract a number which is only slightly different from r. In[9]:=

r - 3.200000000000000000000001

Oulf~=

1.77635683 10- 16

The precision of the result is considerably lower because of "roundoff errors". In[10]:=

Precision [%]

Out[10]= 8

Besides the above precision (relative error), Mathematica also keeps track of the accuracy, which is the number of significant digits to the right of the decimal point (absolute error). In[11]:=

Accuracy [%%]

Out[11]= 24

The accuracy can be controlled with SetAccuracy. The precision and the accuracy change for every calculation: the multiplications and divisions primarily affect the accuracy, sums and differences affect the

378

3. Programming

precision. Mathematica tries to do every calculation with the best possible precision and accuracy. If we need to trace the endpoints of intervals explicitly, it is preferable to use Interval and the related functions (see Table 3-6).

o

Summary Expression

Meaning

Precision [x]

the number of significant decimal digits in x ("relative error")

Accuracy [x]

the number of significant decimal digits to the right of the decimal point in x ("absolute error")

SetPrecision[x, n]

create a number x with n digits of precision, by padding with binary zeros, if necessary

SetAccuracy [x, n]

create a number x with n digits of accuracy, by padding with binary zeros, if necessary

Chop [expr]

replace all numbers with magnitude less than 10- 10 by 0

Chop [expr, dx]

replace all numbers with magnitude less than dx by 0

N[expr]

the numerical value of expr, using machine-precision numbers

N [expr,

the numerical value of expr with n-digit precision

n]

Table 3-5: Controlling the precision and the accuracy Expression

Meaning

Interval [{min, max} ]

the range of values between min and max

In tervalMemberQ [int, x]

return True if x is a member of the interval, otherwise False

IntervalUnion [intI' int2'

... ]

IntervalIntersection [intI' int2'

the union of intervals

... ] the intersection of intervals

Table 3-6: Interval calculations



3.3.3 Controlling Numerical Built-in Functions

The numerical functions for the solutions of equations, differential equations, integrals, sums, products, etc. can be controlled with several options. These are summarized at the end of this section. The default values for the options normally pro-

379

3.3 Numerics

duce useful results. But for more pathological functions, problems might arise. Such numerical difficulties most often correspond to sensitivities of the results on the exact choice of the options. The problems often can be resolved by adjusting the precision and the accuracy, or by adjusting other parameters of the algorithms. 1&

If we increase the precision of internal calculations above machine-precision, e.g., with the option WorkingPrecision, we have to define the relevant numerical values with enough precision.

Let us try to calculate the following integral: In[1]:=

i1

=

Nlntegrate [Sin [1 Ix],

{x,

.004, 1}]

Nlntegrate: :slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, oscillatory integrand, or insufficient WorkingPrecision. Nlntegrate: :ncvb: Nlntegrate failed to converge to prescribed accuracy after 7 recursive bisections in x near x = 0.00604903. Out[1}=

0.50448

We get warnings about numerical problems. Because the function is highly oscillatory, the number of the recursive subdivisions has to be increased. In[2]:=

i2 = Nlntegrate[Sin[l/x], MaxRecursion -> 20]

{x,

.004, l},

Nlntegrate::slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, oscillatory integrand, or insufficient WorkingPrecision. Out[2}=

0.504063

A warning still appears, and the result is considerably different from the above. We can now try to increase the precision. This makes the messages disappear. In[3]:=

i3 = Nlntegrate[Sin[l/x], {x, .004, l}, MaxRecursion -> 20, workingPrecision -> 30]

Oulf~=

0.5040633306678297171

What are the differences between the results?

380

3. Programming

In[4]:=

{il - i2, i2 - i3}

Out[4]=

{O. 000416557,

-2.45542 10- 11 }

What is the precision and the accuracy of the last result? In[5]:=

Through[{Precision, Accuracy} [i3]]

Out[5]=

{ 2 0,

20}

We are in the happy situation that a very good numerical approximation of the exact result is available for this integral.

D

In[6]:=

res = Integrate[Sin[l/x], {x, 4/1000, 1}]

Out[6]=

-Cos Integral [1]

In[7]:=

N[res - i3, 21]

Out[7]=

-8. 10- 20

+ Cos Integral [250]

+ Sin[l]

-

Sin[250]

--250---

Summary

Expression

Meaning

FindRoot [eqn,

{x,

xo} ]

search a numerical solution to the equation eqn, by starting with the variable x at Xo and xl (symbolic derivatives are not available)

FindRoot [eqn, {x,

{xo,

xl} } ]

FindRoot [eqn, {x,

Xstart'

Xminf

x max } ]

{eqnl' eqn2' ... }, xo},

{Y,

Yo},

FindMinimum [I, {x,

search a numerical solution to the equation eqn, by starting with the variable x at Xstart; the search is stopped when the interval [xmin' xmaxl is left search a numerical solution to a system of equations {eqnl'

FindRoot[ {x,

search a numerical solution to the equation eqn, by starting with the variable x at Xo

xo} ]

NDSolve [eqn, x, t]

... ]

eqn2' ... } with the given variables and starting points

search a local minimum off, by starting with the variable x at

Xo numerically solve a system which consists of a differential equation and initial conditions eqn in x, where the independent variable x runs from tmin to tmax

Table 3-7: Numerical functions

381

3.3 Numerics

Expression

Meaning

NDSolve [eqn, {x, y, '" }, {t, (min' {max} ]

numerically solve a system of differential equations and initial conditions

NIntegrate [j,

numerically integrate (possible singularities are tested at the end points); multidimensional integrals are similar to Integrate

{x,

xmax} ]

xminl

NIntegrate [j, {x,

XO'

Xl'

a numerical integral which tests for singularities at the given intermediate points; a numerical line integral

... , Xk} ]

NSolve [eqn, var]

all solutions of the polynomial equation eqn in the variable var

NSolve [eqn, var, n]

all solutions of the polynomial equation eqn in the variable var; the result is given to n-digit precision

NSum[j,

numerically evaluate a sum

{i,

iminf i max } ]

NSum[j, {i,

numerically evaluate a sum with steps di

iminf imax1 di} ]

NProduct [j, {i, iminl i max } ]

numerically evaluate a product

NProduct [I, {i, iminf imax1 di} ]

numerically evaluate a product with steps di

Table 3-7: Numerical functions Option

Default

Meaning

AccuracyGoal

Automatic Infinity

the digits of absolute accuracy sought (Infini ty its the default ofNSum and NProduct)

Compiled

True

whether the function should be compiled

WorkingPrecision

$MachinePrecision the number of digits used in the internal computations

Table 3-8: The common options for all numerical functions Option

Default

Meaning

DampingFactor

1

the damping factor in Newton's method

Table 3-9: Further options for FindRoot

382

3. Programming

Option

Default

Meaning

Jacobian

Automatic

the Jacobian of the system

Maxlterations

15

the maximum number of iterations

Table 3-9: Further options for FindRoot Option

Default

Meaning

Gradient

Automatic

the list of the gradient functions {D[j, xl, D[j, yl, ... }

Maxlterations

30

the maximum number of iterations

PrecisionGoal

Automatic

the precision sought in the value of the function at the minimum

Table 3-10: Further options for FindMinimum Option

Default

Meaning

MaxSteps

500

the maximum number of steps

MaxStepSize

Directedlnfinity[ll

the maximum size of each step

PrecisionGoal

Automatic

the digits of precision sought

StartingStepSize

Automatic

the initial step size used

Table 3-11: Further options for NDSol ve Option

Default

Meaning

GaussPoints

Automatic

the initial number of sample points

MaxRecursion

6

the maximum number of recursive subdivisions

Method

Automatic

the algorithm used

MinRecursion

0

the·minimum number of recursive subdivisions

PrecisionGoal

Automatic

the digits of precision sought

SingularityDepth

4

the number of recursive subdivisions before changing variables

Table 3-12: Further options for NIntegrate

383

3.3 Numerics

Option

Default

Meaning

Method

Automatic

the method to use: Integrate or Fi t

NSumExtraTerms

12

the number of terms to use in the extrapolation

NSumTerms

15

the number of terms to use before the extrapolation

PrecisionGoal

Automatic

the digits of precision sought

VerifyConvergence

True

whether to explicitly test for convergence

WynnDegree

1

the degree of the algorithm

Table 3-13: Further options for NSum Option

Default

Meaning

Method

Automatic

the method of use: Integrate or Fit

NProductExtraTerms

12

the number of terms to use in the extrapolation

NProductTerms

15

the number of terms to use before the extrapolation

PrecisionGoal

Automatic

the digits of precision sought

verifyConvergence

True

whether to explicitly test for convergence

WynnDegree

1

the degree of the algorithm

Table 3-14: Further options for NProduct

384

3. Programming

• 3.4 Long Calculations: RSA Some calculations require considerable computing times. In such cases, the user does not want to wait for hours in an interactive session; it is much more preferable to run the process in the background. These techniques will be introduced by looking at the generation of large prime numbers, suitable for the encryption with RSA. At the same time, we will learn some elementary ways of communicating with other programs.



3.4.1

Primes for RSA

Let us tum to the RSA encryption system again, which already has been treated in the Sections 1.3.3 and 3.2.4. We used large primes p and q to encode and decode messages. For the system to be save-according to today's the knowledge-the primes should have a hundred or more digits and be chosen at random. How can we find such large primes? Exercise 4 in Section 1.3.3 shows that the function Prime, which returns the nth prime, is much too slow for this task (it has to know the n-l st prime, etc.). There are sophisticated algorithms to find primes suitable for RSA (see [Mau89]). But by using some patience instead of refinement, we will succeed as well. Our method will be basically a random search, until a number with the desired properties is found. The time used for such a naive method does not need to bother us too much, because the generation of primes can be done in the background, using computer resources at otherwise idle times. In other words, the RSA machine can be used to generate primes and save them in a secret list, whenever no encoding or decoding is being done. As soon as we need new primes, we take and delete them from this list.

For a prime p to be really good for RSA, it not only needs to be large, but p-l should also have a large prime factor. This assures that other attacks, which are based on special algorithms for factoring will hopefully not succeed. The condition for a large factor can be met as follows: Of course, p-l is even for a large prime p. We can therefore look at (p-l )/2. If this is prime, the condition is met. Otherwise, we divide (P-l)/2 by 2, 3, ... , k. If one of the results is prime, (p-l )/2, and therefore p-l itself, has a large prime factor, the result of the division. If, of the other hand, the divisions do not produce a prime up to some reasonably small divisor k, we reject the candidate p. The implementation of this test is called GoodRSAPrimeQ. We use a capital letter, because it will be the same as the one in the package SKPackages 'RSA ' .

3.4 Long Calculations: RSA

385

The function tests if a given number n is prime, and, in the case of a prime, if the above condition is met. A second parameter controls the maximum number of divisions k. In[1]:=

GoodRSAPrimeQ [n_, k_] : = PrimeQ[n] && Module[{d = 1, m = (n-1)/2}, While[d rsa-primes-100.log &"]

Out[17}= 0

The job uses our control file rsa-primes-lOO.control as its input and writes its normal output to a log file r s a - p rim e s - 1 00 . log. According to Gener a tePr ime s, the actual results are saved in the file r s a - p rim e s - 100. After some time, some hours on a SPARCstation 1+, we get "good RSA primes" like: p[lJ = 332715112660848742187755808851902864945816936127\ 9160142523661652581105578513717982486654235124785151

o

Structured Communication with External Programs, MathLink

Mathematica is also capable of structured communication with external programs. The corresponding protocol is called MathLink. It allows us to call external programs from Mathematica, or to call Mathematica from other programs. For instance, the front ends use MathLink to pass calculations to the kernel and to get the results from the kernel. Such things are very interesting for programmers, but they are outside of the scope of this book. If a detailed documentation of MathLink did not come with Mathematica, it can be requested from Wolfram Research.

392

o

3. Programming

Summary Expression Put [expr,

Short Form expr »

"file" ]

IIftle

Meaning write an expression to a file, close with a newline

li

Pu tAppend [expr , "file" ] expr »> llfile

II

append an expression to a file, close with a newline

Table 3-16: Simple writing to files Expression

Meaning

Definition [s]

the definitions corresponding to the symbol s

FullDefini tion [s]

the definitions corresponding to the symbol s, and all the symbols on which these depend

Table 3-17: Definitions Expression Run [exprl' expr2'

Meaning

... ]

write expr; in printed form, separated by spaces, and run it as an operating system command (not on all platforms)

RunThrough [ "command" , expr]

execute an external command, giving the printed form of expr as input; read the result as Mathematica input

!command

run the line as an operating system command

expr »

the text form of expr is sent to an external command

«

" !command"

" !command"

the output of an external program is read as Mathematica input

Install ["program"]

start an external program and install the Mathematica definitions to call it; the program has to use MathLink

Uninstall [link]

quit the external program, remove the M athematica definitions

Table 3-18: External programs

o

Exercise

1. Write a version of generatePrimes which only uses PutAppend.

3.4 Long Calculations: RSA

o

393

Final Remark

We now have met 674 of the 1129 built-in Mathematica objects (in Version 2.2), and some packages; it is a good point to stop here. As was said at the beginning, it is not the aim of the book to cover every possible application or problem, because this would take a life-time. Rather, the reader should now be able to handle and solve his or her problems himself or herself. I wish a lot of success and fun.

• References o

Some Books about Mathematica

[AB92/1]

Abell, M. and J. Braselton: Mathematica by Example. Academic Press, London, 1992.

[AB92/2]

Abell, M. and 1. Braselton: The Mathematica Handbook. Academic Press, London, 1992.

[AB93]

Abell, M. and 1. Braselton: Differential Equations with Mathematica. Academic Press, New York, 1993.

[Bla91]

Blachman, N.: Mathematica: A Practical Approach. Prentice-Hall, Englewood Cliffs, 1991.

[Bla92]

Blachman, N.: Mathematica Quick Reference, Version 2. AddisonWesley, Redwood City, 1992.

[BKM92]

Boyland, P., J. Keiper, E. Martin et al.: Guide to Standard Mathematica Packages. Mathematica Technical Report, Wolfram Research, Champaign, 1992.

[BPU91]

Brown, D., H. Porta and J. Uhl: Calculus and Mathematica. AddisonWesley, Redwood City, 1991.

[BD92]

Burbulla, D. C. M. and C. T. J. Dodson: Self-Tutor for Computer Calculus Using Mathematica. Prentice-Hall, Englewood Cliffs, 1992.

[Cam90]

Cameron, S.: The Mathematica Graphics Guidebook. Addison-Wesley, Redwood City, 1990.

[Cra91]

Crandall, R. E.: Mathematicafor the Sciences. Addison-Wesley, Redwood City, 1991.

[CR91]

Crooke, P. and J. Ratcliffe: Guidebook to Calculus with Mathematica. Wadsworth, London, 1991.

[EL91]

Ellis, W. Jr. and E. Lodi: A Tutorial Introduction to Mathematica. Brooks/Cole, Pacific Grove, 1991.

[FL92]

Finch, J. and M. Lehman: Exploring Calculus with Mathematica. Addison-Wesley, Redwood City, 1992.

[Fre94]

Freeman, J. A.: Simulating Neural Networks with Mathematica. Addison-Wesley, Reading, 1994.

396 [GG91]

Gray, T. W. and J. Glynn: Exploring Mathematics with Mathematica. Addison-Wesley, Redwood City, 1991.

[GG92]

Gray, T. and 1. Glynn: The Beginners Guide to Mathematica 2. Addison-Wesley, Redwood City, 1992.

[GKW93]

Gaylord, R. 1., S. N. Kamin and P. R. Wellin: Introduction to Programming with Mathematica. Telos/Springer, New York, 1993.

[Mae91]

Maeder, R. E.: Programming in Mathematica, Second Edition. Addison-Wesley, Redwood City, 1991.

[Mae94]

Maeder, R. E.: The Mathematica Programmer. AP Professional, Boston, 1994.

[ST94]

Shaw, W. T. and J. Tigg: Applied Mathematica: Getting Started, Getting it Done. Addison-Wesley, Reading, 1994.

[Ske93]

Skeel, R. and J. Keiper: Elementary Numerical Computing with Mathematica. MacGraw-Hill, New York, 1993.

[Ski90]

Skiena, S.: Implementing Discrete Mathematics: Combinatorics and Graph Theory with Mathematica. Addison-Wesley, Redwood City, 1990.

[Var91]

Vardi, I.: Computational Recreations in Mathematica. Addison-Wesley, Redwood City, 1991.

[Vari93]

Varian, H. et al.: Economic and Financial Modeling with Mathematica. Springer, New York, 1993.

[Vve92]

Vvedensky, D.: Partial Differential Equations with Mathematica. Addison-Wesley, Redwood City, 1992.

[Wag91]

Wagon, S.: Mathematica in Action. Freeman, New York, 1991.

[WoI88]

Wolfram, S.: Mathematica,A System for Doing Mathematics by Computer. Addison-Wesley, Redwood City, 1988.

[WoI91]

Wolfram, S.: Mathematica, A System for Doing Mathematics by Computer, Second Edition. Addison-Wesley, Redwood City, 1991.

[WoI92]

Wolfram, S.: Mathematica Reference Guide. Addison-Wesley, Redwood City, 1992.

o

Further References

[AS65]

Abramowitz, M. and I. A. Stegun: Handbook of Mathematical Functions. Dover, New York, 1965.

References

397

[Akr89]

Akritas, A. G.: Elements of Computer Algebra with Applications. Wiley, New York, 1989.

[BB79]

Blakley, G. R. and 1. Borosh: Rivest-Shamir-Adleman public key cryptosystems do not always conceal messages. Computers and Mathematics with Applications 5,169-178,1979.

[Bri74]

Brigham, E. 0.: The Fast Fourier Transform. Prentice-Hall, Englewood Cliffs, 1974.

[DST88]

Davenport, J. H., Y. Siret and E. Tournier: Computer Algebra, Systems and Algorithms for Algebraic Computation. Academic Press, London, 1988.

[EK94]

Estrada, R. and R. P. Kanwal: Asymptotic Analysis: A Distributional Approach. Birkhauser, Boston, 1994.

[Flii62]

Fliigge, W.: Handbook of Engineering Mechanics. McGraw-Hill, New York, 1962.

[Her78]

Herlestam, T.: Critical remarks on some public-key cryptosystems. BIT 18,493-496, 1978.

[KS78]

Kirchgraber, D. und E. Stiefel: Methoden der analytischen Storungsrechnung und ihre Anwendungen. Teubner, Stuttgart, 1978.

[Mau89]

Maurer, D.: Fast generation of secure RSA-moduli with almost maximal diversity. Advances in Cryptology, EUROCRYPT '89, Springer, 1989, pp. 636-647.

[Nay73]

Nayfeh, A.: Perturbation Methods. Wiley, New York, 1973.

[Nay81]

Nayfeh, A. H.: Introduction to Perturbation Techniques. Wiley, New York, 1981.

[RA87]

Rand, R. H. and D. Armbruster: Perturbation Methods, Bifurcation Theory and Computer Algebra. Springer, New York, 1987.

[Ris68]

Risch, R.: On the Integration of Elementary Functions which are built up using Algebraic Operations. Report SP-2801l002100, Sys. Dev. Corp., Santa Monica, 1968.

[RSA78]

Rivest, R. L., A. Shamir and L. Adleman: A method for obtaining digital signatures and public key cryptosystems. Communications of the ACM 21, 120-126, 1978.

[WB79]

Williams, H. C. and B. Schmid: Some remarks concerning the M.LT. public-key cryptosystem. BIT 19,525-538, 1979.

• Index Built-in Mathematica objects are printed bold (e.g., Abs). Functions, which are self-programmed or read from packages, are printed plain (e.g., S1). Italic page numbers point to the documentations of the built-in functions in the summary tables.

Symbols !,24 !!,32 ! =,60,64 ?,16 ??,16 @,322 @, 15-16,23,322 @@, 146-147 #, 144,147 %,19,23 %%,19,23

%n,23

",18,24 "=,262 &, 144,147 &&,64 -,23 ",322

",309-310

',298 ., 160,163 · .,246,248 · .. ,246,248 .m,26 · ma, 26 :,243,247 : :,327 : : usage,

302,307

:=,68,78,255,261,274,296 : >,253-254,274 ;,64,183 -,17,23 --,288 -=,288

->,46,50,52,253-254 +,17,23 ++,288 +=,288 =,42,78,255,261,274 = .,52 =! =,240-241 ==,54,60,64 ===,240-241 *,322 *,15-17,24,163,322 *=,288

/, 17,24,240,287

/@, 144,147 / .,50,52,251,254 /:, 196,198,262 /;,155,276-277 /=,288 / /,23 / /@, 147 / / . , 252, 254 Itmp,118 ,64 =,64

«,11,26,31,57,97,306,392 ,120,323 »,57,390,392 >>>,392 ( ... ),19,23 (* ... *),305,307,309-310 [ ... ], 19,23 [ [ ... ] ], 50,52, 149,156 { ... }, 23,50,52, 138

400 1,244,247 I I, 60, 64 _,233,236 _.,245,247 __ ,245,247 ___ ,245,248 _ Complex, 375 _Integer, 375 _Real, 375 \ 322 \,321-322 \@,322 \ "A, 322 \",322

\ .nn, 322 \:nnnn,322 \ *,322 \ \,322 \b,322 \n,322

\nnn,322 \r,322 \t,322 00,21,25

Global Variables $Context,297-299,303,307 $ContextPath, 299, 303,307 $DefaultFont, 83, Ill-1l2 $DisplayFunction, 83,104-105,111ll2,203 $ModuleNumber, 293 $Packages, 303, 307 $Path,31,221 $Recurs ionLimi t, 334--335 $SessionID,293

Numerics 3D ViewPoint Selector, 110

A abort,12 Abort Calculation, 12 Abs,24,195,197,213,348,354

AbsArg' , 354-355 AbsArg. m, 354 Absolute context names, 298 errors, 377-378 time, 224 values, 24, 197,353 AbsoluteDashing,177 AbsolutePointSize,177 AbsoluteThickness,177 AbsoluteTime,224 Accounting notation, 314 AccountingForm,313-314 Accuracy, 377-378 in built-in functions, 378 in numerical functions, 381 Accuracy, 378 AccuracyGoal,381 Action, 12, 14, 110 Adding attributes, 265 elements to lists, ISO, 156, 288 numbers, 17, 23 AiryAi, 194,213 AiryAiPrime,213 AiryBi,213 AiryBiPrime,213 Algebra' ReIrn' , 196, 198,353 SymbolicSurn' , 199,201 Algebraic equations, 54, 61 rules, corresponding to equations, 65 AlgebraicRules,65 Algebra, linear, 158,216--217 Algorithms iterative, 334 Newton's, see also: Newtons's method, 282 numerical, precision and accuracy, 379 Risch, 70, 250 Aliasing, in plots, 84 Alignment, in tables, 142 Alternatives, in patterns, 244, 247 AmbientLight, llO Analysis, statistical, 205-206 Analytic, 79 And, 64

401

Index Angle, bending, 84, 88 Animate Selected Graphics, 117, 182 Animation', 117, 182 animationGraphics, 189 Animations, 116 Apart, 49, 53 Append, 150, 155-156 Appending elements to lists, 156,288 expressions to files, 392 AppendTo, 288 Apply, 146--147 Applying functions to parts of expressions, 232 functions to the elements of lists, 147 transformation rules, 254 Approximations numerical, 378 of data by functions, 202, 205 of numbers, 18,24 of products, 200 of real numbers by rational numbers, 18, 24 of sums, 200 Arbitrary-precision numbers, 376 ArcCos, 24,213 ArcCosh, 24, 213 ArcCot, 24, 213 ArcCoth, 24,213 ArcCsc, 24, 213 ArcCsch, 24, 213 Arcs, 176 ArcSec, 24, 213 ArcSech, 24, 213 ArcSin, 24, 213 ArcSinh, 24, 213 ArcTan, 24, 213 ArcTanh, 24, 213 Arg, 195,197,213,348,354 Arguments, 353 complex, 197 keeping unevaluated, 266 of Mathematica functions, 20, 23 sequences of, 247 unevaluated form, 276 using elements of lists as, 147 variable number of, 245, 247

Arithmetic interval, 378 sequences, 138, 142 ArithmeticGeometricMean, 213 Array, 140,142 Arrays, 176 of graphics, 102, 105, 176 ASCII, 321, 323, 331, 357 AspectRatio, 82, 110, 112, 133,135 Assignments, 44, 256 Associated definitions, 198,260,262,341 messages, 327 Associative functions, 264, 266 Asterisk, 17 AtomQ, 239,242 Attributes, 263, 265 locking, 266 Needs is called, 266 pure functions with, 265-266 Attributes, 263-265 Attributes, 305 Automatic, 83 Axes, 82, 110, 112,129 AxesEdge, 110,120 AxesLabel, 82,88, 110, 112 AxesOrigin, 82, 112 AxesStyle, 82, 110, 112 Axes, labels for, 84, 88

B Background, 82,110,112 Background jobs, 389 Backspace, 322 Bar charts, 192 BarChart, 193 Bars, error, 192 Base of numbers, printing, 314 BaseForm,313-314 Batch jobs, 391 Beep, 14 Begin, 302-304,307 BeginPackage, 302-306 Bending angle, 84, 88 BernoulliB,213

402 Bessel functions, 16,88 derivatives of, 67 Bessell, 88,213 BesselJ, 88, 213 BesselK, 89, 213 BesselY, 89, 213 Beta, 213 Bifurcation, 117 Binary, saving Mathematica, 221-222 Binomial,213 Blanks, 68,233, 236 three, 245 two, 245 Block, 295-297 Blue, 177 Blue, 181, 183 Boundary layers, 366 Bounding box, 120, 129 ratio of edges, 120 Boxed, 110, 129 BoxRatios, 110,120 BoxStyle,110 Braces, 23, 50 Brackets, 23 double, 50 Break,289 Brightness, 112, 120 Browser, 14 Bugs, 58 Built-in functions, changing, 260 Byte, 136 ByteCount, 223, 225 Bytes in ReadList, 136 maximum number, 225

c C,51,268,311,368 format for, 312 C,74 Calculations numerical, 17, 368 symbolic, 44 Calculus, 66 Calculus' DSol ve ' , 76, 79

Ellipticlntegrate',79 FourierTransform', 209, 212 LaplaceTransform', 211-212, 337 Master', 190 PDSolvel ',77,79 Cancel, 48, 53 Cancelling, 53 Capital letters, 45 Carriage return, 322 Cases, 235,237 Catalan, 213 Catch,289 Ceiling, 213 Cells, 9 containing several lines, 9 in graphics arrays, 176 initialization, 349 CForm, 311-312 CGS, 28 Changing built-in functions, 260 Character, 136 Characters control, 322 from strings, 323 in ReadList, 136 lists of, 323 meta, 322 sequence of, in ReadList, 136 space, 17 special,321-322 wildcard, 15 zero or more, 16 Characters, 321,323 Charts bar, 192 pie, 192 ChebyshevT, 213 Chebyshevu,213 Check, 325-327 checkForError, 325 Checking for messages, 327 Chop, 378 Cipher text, 33 Circle, 173,176 Circles, 176 Clear, 44, 52, 262, 265,350 ClearAll,265

Index ClearAttributes, 264-265 Clearing attributes, 265 definitions, 45, 52, 262 ClebschGordan, 213 ClipFill, 110 Close, 388-389 Closing streams, 389 Codes, ASCII, 321, 323, 357 Coefficient, 215 CoefficientList, 214-215 Coefficients, in polynomials, 214-215 Collect, 46, 53 Collecting powers, 53 ColorFunction, 110, 112,120 ColorOutput, 82,110,112 Colors brightness, 112, 120 definitions for, 183 functions for, 112, 120 RGB, 120, 177 saturation, 112, 120 Colors', 179, 183, 186 ColumnForm, 312,315 Column, formatting as, 312 Combining lists, 105, 151, 156 parts of the output, 309 strings, 120 Commands, running external, 392 Comments, 307, 309-310 Common denominators, 49, 53 Communication, 391 Commutative functions, 264, 266 comp, 371 Compilation, 368 of numerical functions, 381 Compile, 369-371,375 Compiled, 82,110,112,381 Compiled functions, 375 CompiledFunction, 369,375 Compiler, 368, 375 Complement, 151,156 Complements of lists, 156 Complete Selection, 14 Complex arguments, 197

403 conjugates, 197 expressions, expanding, 52 numbers, 195, 197 numbers, heads of, 241 numbers, in compilation, 370 numbers, patterns for, 243, 247 symbols, 195, 197-198 Complex, 238, 241, 247 ComplexExpand, 49, 52, 195,197,208 Complicated patterns, 242 ComposeList, 286, 288 Composing functions, 286, 288 polynomials, 216 CompoundExpression, 183 Computational geometry, 137 Concatenating lists, 151, 156 strings, 120 Conditionals, 277, 287 with local variables, 292, 296 Conditions, 155,237 in patterns, 240 initial, 77, 332 Configuration custom, 219 space, 123 Conjugate, 195,197-198,213 Conjugates, complex, 197 Constant, 266 Constants Euler's, 21, 335 local,292 mathematical, 213 of integration, 70, 74, 78 ConstrainedMax, 217 ConstrainedMin,217 Constraint-propagation, 337 Context, 298-300,306 Contexts, 26, 297 absolute, 298 current, 307 currently open, 299 in packages, 303, 306 list of, 32 list of all, 306 mechanism, 303

404 of symbols, 306 path, 307 relative, 298 removing names from, 306 sub, 302 Contexts, 29,32,299,306 Continue, 289 cont i nue, 12 Continuous Fourier transforms, 209, 212 Contour graphics object, 175 Contour plots, 111, 119-120 of data, 135 ContourGraphics,175 ContourLines, 112 ContourPlot, 111-112,119 ContourPlot3D, 113 Contours, 112-113,120 ContourShading, 112 ContourSmoothing, 112-113,120 ContourStyle, 112 Control by messages, 327 characters, 322 over flow, 289 structures, 279, 288-289 structures, evaluation of, 275 variables, 288 Conventions, 2 Convergence in numerical products, 383 in numerical sums, 383 Convert, 27-28 Convert Clipboard, 87 Convert to, 87 Converting dates, 224 expressions to input form, 175 expressions to strings, 120,323 graphics, 116, 119 real into rational numbers, 18, 24 strings to expressions, 323 time, 224 units, 32 convertString,357 ConvertTernperature,28 Coordinates for the triple pendulum, 90

scaled, 177 strained, 365 Coprocessor, 369 Copy, 11

Copy Output from Above, 310 CopyDirectory,219 CopyFile,219 Copying directories, 219 files, 219 Cos, 24, 213 Cosh, 24,213 Cos Integral, 213 Cot, 24,213 Coth, 24, 213 Count, 235,237 Counting patterns, 237 Courier font, 90 CPU time, 42, 224 CreateDirectory,218 Creating directories, 218 lists, 138 Cross, 152, 154 cross, 238 Cross product, 152 CrossProduct',152 Cryptosystem public key, 33 RSA,34 csc, 24,213 Csch, 24,213 Cubes, 176 Cuboid, 173, 176 Current context, 307 directory, 218 Curves in space, 122, 127, 129 Custom formats, 318 messages, 327 output formats, 320 Cyclic permutations, 152, 157 Cyclotomic, 216 Cyclotomic polynomial, 216

405

Index

D D,66-70,78 Damping factors, 381 DampingFactor, 381 Dashing, 177 Dashing, 174,177,206 Data, 203 contour plots of, 135 density plots of, 135 discrete, 130 discrete, plots of, 135 external, 130 fits, 202, 205 nonlinear fits, 205 of type, reading from file, 136 reading external, 131, 136 surface plots of, 135 three-dimensional, general, plots of, 137 types, 340 Data Encryption Standard, 33 Database, key, 35 Date, 224 Dates, 224 converting, 224 modification, of files, 219 Debugging, 342, 344, 347 Decimal points, 18 DeclarePackage, 220, 301,306 Decoding with RSA, 36 Decompose, 215-216 Decompositions Jordan, 217 LV, 217 partial fraction, 49,53 QR,217 Schur,217 Decrement, 288 DefaultColor, 82, 110, 112 DefaultFont, 83,111-112 Defaults for optional arguments, 247 Definite integrals, 71, 78 Definition, 390,392 Definitions, 44, 52, 255 and ... Form commands, 140 associated, 198,260,262,341 clearing, 45, 52,262

delayed, 69, 78, 255, 261 evaluation of, 269, 274 for symbols, 392 immediate, 69, 78, 255, 261 of attributes, 265 of functions, 68, 78, 234 protecting, 266 saving to a file, 105 tracing the evaluation of, 343 with memory, 258 Degree, 21, 25,213 Degrees, 25 Centigrade, 28 Fahrenheit, 28 Delaunay triangulation, 137 Delayed definitions, 69, 78, 255, 261 transformation rules, 253 Delete, 150,156 DeleteCases, 236-237 DeleteContents, 218 DeleteDirectory, 218 DeleteFile, 218-219 Deleting according to patterns, 237 directories, 218 elements oflists, 149-150, 156 files, 219 Delimiters in ReadList, 137 Denominators common, 49, 53 expanding, 48, 52 patterns for, 243 Density graphics objects, 175 Density plots, 114, 119 of data, 135 DensityGraphics, 175 DensityPlot, 114,119 Depth,232 Depth of recursions, 335 Derivative, 316,318 Derivatives, 66, 78 full form of, 318 higher, 66, 78 partial, 70, 315, 319 partial, format, 316 total,67

406 zero, attribute for, 266 DES, 33 Det, 158,163 Determinants, 158, 163 Developing programs, 342 Diagonal matrices, 158, 163 DiagonalMatrix, 158,163, 168 Dialog, 342, 344, 346-347 Dialogs, 344, 347 Differential equations, 73, 359 numerical solutions of, 77, 79, 380 partial, 77, 79 partial, formats for, 316 series expansions, 359 solutions of, 79 systems of, 74, 79 Differentials, total, 67, 78 DigitBlock,314 DigitQ,239 Digits printed, 313 significant, 376, 378 Dimensions, sequence in tables, 142 Dirac function, 210 DiracDelta,21O Direction, 73, 79 Directives, 120, 173, 177 Directories, manipulation of, 217-218 Directory, 218 Discrete data, 130 data, plots of, 135 Fourier transforms, 207, 212 DiscreteMath' ComputationalGeometry', 135, 137 Disk, 173,176, 184 Disks, 176 Dispatch, 253-254 Dispatch tables, 253-254 DISPLAY, 104 Display, 87-88, 105,389 Display of graphics, 87 DisplayFunction, 83,103,105,111-112, 203 Division, 17, 24 Divisors, 213 DivisorSigma,213

Divisor, greatest common, 37, 42 Do, 155,275,279-280,288,331 Documentation, 14, 16,327 of functions, 307 of standard packages, 190 DOS, 26 Dots, 246 Double pendulum, I, 106 DownValues, 258, 262 Downvalues, 260, 262 evaluation of, 269 Drop, 149,156 Dropping characters of strings, 323 elements of lists, 156 DSolve, 74-77, 79 Dt,67,78 Dummy variables, 294 Dump, 221-222

E E, 21,25,213 e,25 EdgeForm, 122,130,177 Edges, 130, 177 Edit, 11 EditDefinition,lJ Editln,lJ Editing, 310 input, 11 EDITOR, 11 Editor, 11 Effective potential, 107 Efficiency of list manipulations, 155 Eigensystem, 164,171 Eigenvalues, 164, 170-171 Eigenvalues, 164, 169,171 Eigenvectors, 164, 170-171 Eigenvectors, 164,171 Electronic mail, 5 Elementary functions, 20 Elements of a list, 50, 52, 155 passing a test, 237 testing for, 241 Eliminate, 61, 64

Index Elimination of variables, 61, 64 Ellipses, 176 Elliptic integrals, 79 EllipticE,213 EllipticExp,213 EllipticF,213 EllipticK,213 EllipticLog,213 EllipticNomeQ,239 EllipticPi,213 EllipticTheta,2l3 Encoding with RSA, 36 End, 302-304,307 EndPackage, 302-305,307 Energy kinetic, 91, 107 potential, 90, 107 Enforcing evaluations, 273, 276 Engineering notation, 314 EngineeringForm, 313-314 Enter Dialog, 344 Enter Inspector Dialog, 344 Enter key, 9 epEff,108 Epilog, 82, 110, 112 EPS files, 87 Equal,64 Equal, 229, 340 Equations, 54, 64 algebraic, systems of, 60, 64 differential, 73, 79, 359 differential, constants in, 74 differential, numerical solutions of, 77, 79 differential, series expansions, 359 differential, systems of, 74, 79 elimination of variables, 61, 64 Euler-Lagrange, 90, 107, 125, 145 generation of a list of rules, 65 linear, 216-217 matrix, 217 numerical solutions of, 61, 65, 380 partial, differential, 77, 79,316 polynomial, 62, 65 polynomial, numerical solutions of, 381 solutions of, 54, 64 substitution of solutions into, 55 transcendental, 61, 339

407 transformation to algebraic rules, 65 Equilibrium positions, of a double pendulum, 107 position, of the oscillator, 184 stable, 108 unstable, 108 Erf,213 Erfc,213 Error bars, 192 Error messages, 309, 323 Errors, 58, 342 absolute, 377-378 relative, 377-378 roundoff, 377 Euler-Lagrange equations, 90, 107, 125, 145 EulerE,213 EulerGamma,213 EulerPhi,213 Euler's constant, 21, 335 theorem, 34 totient function, 34 Evaluate, 99, 105, 273, 276 Evaluate Selection, 9 Evaluation, 268 holding, 271, 276 immediate, 105, 273, 276 multiple, 252 non-standard, 275 of control structures, 275 of definitions, 274 of iteration functions, 275 of logical expressions, 275 ofloops, 275 of pure functions, 275 of transformation rules, 274 order, 257 preventing, 271, 276 special, 271, 275 standard, 268 stopping after maximum recursions, 335 tracing, 268, 270, 347 using rules, 52 Even numbers, testing for, 241 EvenQ, 239, 241 exi t, 12 Exit Dialog, 345

408 Exp, 24, 213 Expand, 46-47, 52 ExpandAll,52 ExpandDenominator, 49,52 Expanding all parts, 52 complex expressions, 52 denominators, 48, 52 numerators, 49, 52 polynomials, 45 products and powers, 52 trigonometric functions, 47,52 ExpandNumerator, 49,52 Expansions perturbation, 359 straight forward, 365 Taylor, 199-200 ExplntegralE,213 ExplntegralEi,213 Exponent, 314 Exponent, 214--215 ExponentFunction, 314 Exponential functions, 24 Exponentials of matrices, 158, 163 Exporting expressions to other programs, 311 graphics, 87-88 names, 302 Expression, 136 Expressions, 229 appending to files, 392 applying functions to parts of, 232 compiling, 368 complex, expanding, 52 converting to strings, 120, 323 corresponding to strings, 323 currently being evaluated, 347 depth of, 232 full form of, 230 heads of, 230 in ReadList, 136 levels in, 231-232 logical, evaluation of, 275 partial, 232 parts of, 231 patterns for given heads, 241 positions of parts of, 232

sequence of, 183 structure of, 232 tree form of, 230 writing to files, 392 ExtendedGCD,213 External data, 130 programs, 391-392 Extracting elements oflists, 149, 155-156 Extrapolation in numerical products, 383 in numerical sums, 383

F fac, 257 FaceForm, 177 FaceGrids, 110 Faces, 177 facFast, 259 Factor, 46-47, 53, 216 Factorial,213 Factorial function, 24, 252 Factoring, 53 integers, 42 numerical, 53 over integers, 46 polynomials, 46, 216 trigonometric functions, 47, 53 . Factorlnteger, 39,42,213 FactorList, 216 FactorSquareFree, 216 FactorSquareFreeList, 216 Factors, damping, 381 FactorTerms, 49,53,216 FactorTermsList, 216 False, 240-241 FFT,207 fibl,333 Fibonacci numbers, 259, 262, 333 Fields, vector, 190, 195 Figures, Lissajous, 130 File, 12,26 FileByteCount, 219 FileDate, 219 FileNames, 218-219

409

Index Files, 219 appending expressions to, 392 closing, 389 initialization, 220-221 loading, 306 manipulation of, 217, 219 opening for writing, 389 reading, 31 reading data from, 136 reading expressions from, 389 reading Mathematica commands from, 306 saving definitions in, 105 types, 219 writing expressions to, 392 FileType, 219 Find in Function Browser, 14 findColorOfPoint, 371 Finding patterns, 235 FindMinimum, 124,130,339,380 options for, 382 FindRoot, 61, 65, 284, 374, 380 options for, 381 First, 155 Fit, 202, 205 Fits, 202 nonlinear, 205 Fixed points, 287 FixedPoint, 284,287, 369 FixedPointList, 284,288 Flat,264,266,268 Flatten, 98, 105, 157 Flattening lists, 105, 157 Floor, 213 Flow control, 289, 331-332 by messages, 325, 327 Fold,285,288,357 Folding functions, 285, 288 FoldList, 285,288 FontForm, 174, 177 Fonts Courier, 90 used in this book, 3 For, 281,288,331 Formal parameters in pure functions, 147 Format custom, 318, 320 for C, 312

for columns, 312 for Fortran, 312 for input, 312 for matrices, 312 for numbers, 313 for output, 312 for partial derivatives, 315, 319 for tables, 312 for TeX, 312 full,312 of partial derivatives, 316 options for formatting functions, 314 output, 312 padded,314 text, 312 tree, 312 Format, 318-320, 340 Formatted text, 177 Formatting for input, 310 lists, 139, 142 packages, 305 strings, 174, 177 text, 174, 177 Forms, 310 Form, short, 57, 64 Fortran,51,268,311,331,368 format for, 312 FortranForm, 311-312 Fourier series, 209 transforms, continuous, 209, 212 transforms, discrete, 207, 212 Fourier, 207,212 FourierTransform, 210 FourierTransform', 209, 212 FourierTrigSeries, 210-211 Fractal, IV Fractions, partial, decomposition, 49, 53 Frame, 82, 102,105, 112 FrameLabel, 83, 112 FrameMaker,5 FrameStyle, 83, 112 Frames, around graphics, 102, 105 FrameTicks, 83, 112 FreeQ, 239, 241-242 FromCharacterCode, 321,323

410 FromDate, 224 Frontend,3 ftp,5 Full notation of derivatives, 318 FullDefinition, 390,392 FullForm, 229-230, 271, 312 FullGraphics, 175 FullOptions,88 Function, 144,147,265-266,369 Function browser, 14 Functional programming, 277, 335 Functions arguments of, 20, 23 associative, 264, 266 Bessel, 16,88 Bessel, derivatives of, 67 built-in, precision, 378 changing built-in, 260 color, 112, 120 commutative, 264, 266 compiled,375 composing, 286, 288 definitions of, 68, 78, 234 different notations of, 23 Dirac, 210 documentation of, 307, 327 elementary, 20 exponential, 24 exporting, 302 factorial, 24, 252 finding maxima of, 124 finding minima of, 124, 130 folding, 285, 288 for complex numbers, 197 for tests, 239, 241 gradient, 382 hyperbolic, 24 implicitly defined, 121 interpolating, 77, 204, 206 inverse hyperbolic, 24 inverse trigonometric, 24 iteration, evaluation of, 275 Lagrange, 107, 145 local,291 mathematical, 20, 213 names of, 20 nesting, 281-283, 287

numerical,380 numerical, compilation of, 381 numerical, controlling accuracy, 381 numerical, options for, 381 numerical, precision of, 381 plots of, 81, 87 pure, 75,144-145,147,282,368 pure, evaluation of, 275 pure, short notation for, 144 rational, 48 totient,34 trapdoor one-way, 34 trigonometric, 20, 24 trigonometric, expanding, 47, 52 trigonometric, factoring, 47, 53 with memory, 261 with optional arguments, 245, 247 with options, 246 with several variables, 69

G Gamma, 213 Gaussian integers, 46, 53 Gaussianlntegers, 46, 53,213 GaussPoints, 382 GCD,42,213 GegenbauerC,213 generateD,356 GenerateE,37 genera teE, 356 generateGraphics, 188 generatePrimes,388 generateTable,372 Generator, random, 37, 42 Generic solutions, 60 Geometry, computational, 137 Get, 26,31,97,306 Get Info, 118 Global maximum, 217 minimum, 217 symbols, 290 Global', 29,298-300 GoldenRatio,213 GoodRSAPrimeQ,384-386 gopher, 5

411

Index GoTo,289 Gradient, 382 Gradient functions, 382 Graph, 86, 113, 117, 122 Graphics, 9,81 animation, 116 arcs, 176 arrays, 105, 176 bounding box, 120 circles, 176 color definitions, 183 colors, 177 contour, 111, 119, 175 contours, 120 converting between different types of, 116, 119 dashing, 177 density, 114, 119, 175 directives, 120, 173, 177 disks, 176 display of, 87 edges, 130, 177 ellipses, 176 explicit options of, 175 exporting, 87-88 frames, 102, 105 from a remote host, 104 gray-levels, 177 hue, 177 lines, 176 objects, 175 options for, 173 output, 389 point size, 177 points, 176 polygon faces, 177 polygons, 176 primitives, 173, 176 printing, 86, 88 programming language, 172 rectangles, 176 rows of, 105 styles for points and lines, 206 surface, 108, 119 surface, objects, 176 text, 176 thickness of lines, 177

three-dimensional, 175 tools for, 195 two-dimensional, 81, 87,108,119,175 view point, 120 Graphics, 173,175 objects, 173 Graphics', 192, 195 Animation', 117, 182 Colors' , 179, 183, 186 ContourPlot3D', 113, 121 Graphics', 192, 195 Graphics3D', 135, 137,201 Impl ici tPlot' , 113, 121 PlotField', 190, 195 PlotField3D', 190, 195 Polyhedra', 178 Graphics3D, 122, 173,175 Graphics3D', 135, 137,201 GraphicsArray, 102,105,176 Gray-levels, 120, 177 GrayLevel, 120, 177 Greater, 64 Greatest common divisor, 37, 42 of polynomials, 216 Greek symbols, 90 Green, 177 Green, 181, 183 Grid, 84, 88 GridLines, 83,88 Grouping, 23

H Head, 230 Heads, 229-230 evaluation of, 269 inspecting, 346 of integers, 241 of numbers, 241 Height of plots, 135 HeldPart,276 Help, 14 Help, 14 HermiteH,213 HiddenSurface,11O Hold, 271, 276 HoldAll, 266, 271

412 HoldFirst, 266, 271 HoldForm, 272,276 Holding unevaluated, 266 HoldRest, 266,271 Home directory, 218 HomeDirectory,218 Hue, 177 Hue, 112,120,177 Hyper cube, 173 Hyperbolic functions, 24 inverse, 24 HypergeometricOF1,213 HypergeometriclFl,213 Hypergeometric2Fl,213 HypergeometricPFQ,239 HypergeometricU,213

I 1,88 I,21,25,213 Identity matrices, 158, 163 testing for, 241 Identity, 103,105 IdentityMatrix, 158,163 If, 275, 277-278,287, 331 Im,195,197-198,213 Image, binary, of Mathematica, 222 Imaginary parts, 197 parts, patterns for, 243 unit, 21, 25 Immediate definitions, 69, 78, 255, 261 evaluation, 105, 273, 276 transformation rules, 253-254 Implicitly defined functions, 121 surfaces, 121 ImplicitPlot,113 In,9 Increments, 288 Indefinite integrals, 78 Indices, 140, 142 Inequalities, 216--217 Infinite recursions, 51

Infinity, 21, 25 Infinity, 21,25,213 Infix, 317-318 Infix notation, 23, 317-318 Information, 14, 16 in it. m, 31, 220-221, 301 Initial conditions, 77, 332 Initialization cells, 349 file, 220-221 Initialization Cell, 305 Inner, 163 Inner products, 163 Input containing multiple lines, 10 editing, 11 formatting for, 310, 312 form, converting to, 175 from external programs, 392 InputForm, 172,175,310,312 Insert, 150,156 Inserting characters in strings, 323 elements in lists, 156 inspect, 12,344 Install, 392 Installing external programs, 392 Integer, 238,241 IntegerDigits,213 IntegerQ, 239, 241 Integers, 18 factoring, 42 Gaussian, 46, 53 heads of, 241 testing for, 241 Integrals, 70, 78 constants of integration, 70, 74, 78 definite; 71, 78 elliptic, 79 indefinite, 78 line, 381 multiple, 71 numerical evaluation of, 72, 78, 381 Integrate, 70-73, 78 Integrator, 248 Interpolating functions, 77

413

Index polynomials, 203, 205 Interpolat ingFunct ion, 204, 206 InterpolatingPolynomial,205 Interpolation, 132,204,206 forms of data in, 206 options for, 206 InterpolationOrder,204,206 Interpolations, 203-206 Interrupt Calculation, 12,344 Interrupting Mathematica, 12 Intersection, 151,156 Intersections of intervals, 378 of lists, 156 Interval, 378 IntervalIntersection,378 IntervalMemberQ, 239,378 Intervals, 378 intersections of, 378 unions of, 378 IntervalUnion,378 Inverse hyperbolic functions, 24 matrices, 158, 163 pseudoo, 217 series, 200 trigonometric functions, 24 Inverse, 158,163, 169 InverseFourier, 207,212 InverseFourierTransform,210 InverseJacobiSN,213 InverseLaplaceTransform,211 InverseSeries,200 Irrational numbers, 18 Iteration functions, evaluation of, 275 Iterations, 277 maximum number of, 382 Iterative algorithms, 334 Iterators, 119,280

J J,88 JacobiAmplitude,213 Jacobian, 157, 160-161,382 Jacobian, 382 JacobiP,213

JacobiSN,2l3 Jacobi Symbol, 213 JacobiZeta,213 Jobs background, 389 batch, 391 Join, 96, 98, 105, 151,156 Joining lists, 151, 156 points, l35 strings, 323 Jordan decomposition, 217 JordanDecomposition,217

K K,89 Kernel, 3 Key, 33 database, 35 Kinetic energy, 91, lO7 in a rotating system, 125

L Label, 289 Labels, 84, 88, 192 lagEquations,94, 146 Lagrange function, 90, lO7, 145 lagSolRule,98 LaguerreL, 213 laplace, 336 Laplace transforms, 211-212, 336 LaplaceTransform, 211, 337 LaplaceTransform',211-212 Large primes, 384 Largest number, 24 Last, 155 Last result, 23 Layers, boundary, 366 LCM, 42, 213 Leaf Count, 225 Least common multiple, 42 of polynomials, 216 Least-squares fit, 202 LegendreP,213 LegendreQ, 239

414 Length of lists, 157 of polynomials, 215 of strings, 323 Length, 153,157,214-215 LerchPhi,2l3 Less, 64 Let terQ, 239 Letters, capital, 45 Level, 232 Levels contour, 113 gray, 120 in expressions, 232 maximum number of, in tables, 142 of expressions, 231 Lighting, 110, 123,129 LightSources, 110 Limi t, 73, 79 Limiting execution time, 222, 224 memory use, 225 Limits, 73, 79 Line, 173,176, 179 Line integrals, 381 Linear algebra, 158,216-217 equations, 216-217 programming, 216-217 LinearAlgebra'CrossProduct',152 Linearization, 97 Linearization', 97, 355 Linearize, 97 LinearProgramming,217 LinearSolve,217 Lines, 176 contour, 113 style of, 206 thickness of, 177 zero, 113 LinkConnectedQ,240 LinkReadyQ, 240 linSolRule,98 Lissajous figures, 130 List, 238 Listable, 143,263,266,268 ListContourPlot,135,201

ListDensityPlot, 135, 201 ListPlot, 131-135, 159,201 options for, 135, 206 ListPlot3D, 135, 201 ListQ,239 Lists, 23, 50, 52,116,119,138,155-157 adding elements to, 150, 156 algebraic operations on, 143 appending elements to, 156, 288 applying functions, 147 combining, lSI, 156 complements of, 156 concatenating, 105, 151, 156 converting into parameters, 146-147 creating, l38 cyclic permutations of, 152, 157 deleting elements of, 149-150, 156 dropping elements of, 156 efficiency of manipulations, 155 elements of, 50, 52 extracting elements of, 149, 155-156 flattening, 105, 157 formatting of, see also: Tables, l39, 142 inserting elements, 156 intersections of, 156 joining, lSI, 156 length of, 157 manipulations of, 148, 155 manipulations of, efficiency, 155 multidimensional, 141 nested, 119, 150 of ASCII codes, 323 of characters, 323 of contexts, 306 of transformation rules, 251 partitions of, 157 plotting, 132, 135 prepending elements to, 288 replacing elements of, 150, 156 reversing, 151, 157 sorting, 151, 156 step size, 119 sublists, 149, 156 threading over, 162-163 unions of, 156 using as sets, 151 ListSurfacePlot3D, l35, 201

415

Index ListToString,40 listToString, 358 Literal, 274,276 Loading automatic, 301 packages, 26,31, 306 Local constants, 292 functions, 291 values, 295, 297 variables, 181, 183, 290, 296 variables in conditions, 292, 296 Localization, 290, 296 Locked,266 Locking attributes, 266 Log, 24, 213 Logarithmic plots, 192 Logarithms base of, 24 natural,24 Logical and,64 expressions, evaluation of, 275 expressions, simplification of, 64 or, 64 Loglntegral,213 Loops,277,279-280, 288 evaluation of, 275 Lowercase, 45 LowerCaseQ, 239 LU decomposition, 217 LUBackSubstitution, 217 LUDecomposition,217

M Machine-precision numbers, 376 MachineNumberQ,239 Macintosh, 1, 3 Mail, electronic, 5 Make Lines Thin, 113 Make Template, 14, 302 makeList, 358 makeListl,331 makeList2,332 Manipulations of directories, 217-218

offiles, 217, 219 of lists, 148, 155 of strings, 321, 323 Mantissa, 314 MantissaExponent, 314 Manual,l Map, 143,147 MapAll,147 MapAt, 232 MapThread,147 Mass matrix, 167 massDisks, 184 Master packages, 190 Master.m,301 Matched and composite solutions, 366 MatchedSolutionList, 366 Matching parts, testing for, 241 patterns, 237 testing for, 242 MatchLocalNameQ,239 MatchLocalNames, 347 MatchQ, 239,242 math,lO Mathematical functions, 20 mathgroup,5 MathLink,391-392 MathSource, 5 Matrices, 158 determinants of, 158, 163 diagonal, 158, 163 exponentials of, 158, 163 formatting, 142,312 identity, 158, 163 indexed, 140 inverse, 158, 163 Jacobian, 157, 160--161,382 Jordan decompositions of, 217 LU decompositions of, 217 mass, 167 multiplications of, 160 operations with, 163 powers of, 158, 163 products of, 160, 163 pseudoinverse, 217 QR decompositions of, 217 row-reduced,217

416 Schur decompositions of, 217 singular values, 217 sparse, 216 stiffness, 167 testing for, 241 transposition of, 158, 163 Matrix equations, 217 MatrixExp, 159,163 MatrixForm, 139,142,312 options for, 139,142 MatrixPower, 159,163 MatrixQ, 239, 241 Max, 24, 213 MaxBend, 83-84, 88 Maximum, 24 global, 217 number of bytes, 225 of a function, 124

Minimizing, linear programming, 217 Minimum, 24 global, 217 numerical, 380 of a function, 124, l30 MinRecursion,382

Minus, 17, 23 Miscellaneous' PhysicalConstants',32 Units', 26, 32 MKS,28 Mod, 38,42,213 Modes, normal, 168 Modula-2, 279, 331 Modular powers, 42 Module, 181,183,290-296,331 Modules, 183 MoebiusMu,213

Memory, 223 definitions with, 258 functions with, 261 limiting, 225 optimizing, 225

Movie, 117 MS-DOS, 26 Multidimensional tables, 141 Multinomial, 213 Multiple integrals, 71 least common, 42 Multiplications, 17, 24 of lists, 160 with scalars, 160, 163 mylntegrate, 249, 319

MemoryConstrained, 223,225 MemoryInUse, 223, 225

N

MaxIterations,382 MaxMemoryUsed, 223, 225 MaxRecursion, 379,382 MaxSteps, 126,130,382 MaxStepSize,382 MemberQ, 239,241

Mesh, 110 MeshStyle,110 Message, 324,327

Messages, 309, 323 associated, 327 checking for, 327 custom, 327 flow control with, 325, 327 place holders in, 324 printing, 327 suppressing, 327 Messages, 327 Metacharacters, 16, 322 Method, 382-383 Methods, 340 Min, 24, 213

N,

18,24,378

N[Solve [ ... ]],65

name, 340-341 Named patterns, 243 NameQ,239

Names declaring, 220 exporting, 302 in contexts, 306 in packages, 305 of files, 219 of Mathematica functions, 20 removing, 306 shadowing, 301 unique, 293, 296

417

Index nameSort,341 Naming, 45 Natural logarithm, 24 NDSolve, 77,79,98,126,130,191,380 options for, 382 Needs, 26, 32, 303,306 Negative, 240, 242,348 Negative numbers, testing for, 242 Nest, 287 Nested functions, 281-283, 287 lists, 119, 150 transformation rules, 251 Nesting, maximum, in tracing, 348 NestList,282-283,287 Newline, 322 newtonLines,283,289 Newton's method, 282, 297, 336, 368, 374, 381 NeXT, 3 NIntegrate, 72, 78, 379,381 options for, 382 Non-standard evaluation, 275 Nonlinear fits, 205 springs, 359 NonNegati ve, 240, 242, 348 Nonnegative numbers, testing for, 242 NonNega ti veQ, 348-353 NonNegativeO.m,349 Normal, 200 Normal modes, 168 Notation accounting, 314 engineering, 314 full, 230 full, of derivatives, 318 infix, 23, 317-318 of Mathematica functions, 23 postfix, 19,23,317-318 prefix, 23, 317-318 scientific, 313 standard, 23, 230 Notebook, 3--4 cells, 9 Notebook front end, 3 animation, 117

exporting graphics, 87 help, 14 interrupt commands, 13 printing graphics, 86 quitting Mathematica, 12 starting, 9 suppressing lines, 122 Notes, 327 NProduct, 199-200,381 options for, 383 NProductExtraTerms,383 NProductTerms,383 NSol ve, 62, 65,381 NSum, 199-200,381 options for, 383 NSumExtraTerms,383 NSumTerms,383 Null, 278 Null space, 217 NullRecords,136 NullSpace,217 NullWords,136 Number, 136 NumberForm, 313 NumberFormat,314 NumberPadding,314 NumberPoint,314 NumberQ, 239,241 Numbers arbitrary-precision, 376 base of, 314 complex, 195, 197 Fibonacci, 259, 262, 333 formatting, 313 heads of, 241 in ReadList, 136 integer, 18 irrational, 18 largest, 24 machine-precision, 376 precision of, 376 random, 42 rational, 18 real, 18 smallest, 24 substituting, 50 testing for, 241-242

418 NumberSeparator,314 Numbersigns,314 Numerators expanding, 49, 52 patterns for, 243 Numerical algorithms, precision and accuracy, 379 approximations, 18,24,378 calculations, 17, 368 factoring, 53 functions, 380 functions, compilation of, 381 functions, controlling accuracy, 381 functions, options for, 381 functions, precision of, 378, 381 integrals, 72, 78, 381 products, 199,381 search for minima, 380 solutions of differential equations, 77, 79, 380 solutions of equations, 61, 65, 380 sums, 199-200,381

o 0,200 Object-oriented programming, 340 Objects, 340 graphics, 173, 175 Odd numbers, testing for, 241 OddQ, 239, 241 Off, 324,327 On, 324,327 OneIdentity, 264, 266 Open, 26 Open Function Browser, 14 OpenAppend, 387, 389 Opening files, 389 OpenRead,389 OpenWri te, 388-389 Operate, 148 Operating system commands, running, 392 Operators, 145 overloading, 340 Optimizing memory use, 225 transformation rules, 253-254

Optional arguments, 245, 247 arguments, patterns for, 244, 247 OptionQ, 240, 246 Options, 46, 314 default values for, 82, 88 explicit, of graphics, 175 for contour plots, 120 for FindMinimum, 382 for FindRoot, 381 for graphics, 105, 173 for Interpolation, 206 for ListPlot, 135, 206 for MatrixForm and TableForm, 139, 142 forNDSolve, 130,382 for NIntegrate, 382 for NProduct, 383 for NSum, 383 for number formats, 314 for numerical functions, 381 for Plot, 88, 206 for plots, 82, 88 for ReadList, 136 for Show, 135 for surface plots, 120 for three-dimensional graphics, 129 for Trace, 347 functions with, 246 Options, 88, 246 Or, 64 Order of evaluation, 257 testing for, 241 OrderedQ,240-241 Orderless, 264, 266, 268-269 Ordinary differential equations, 73, 79 Oscillator, III, 164, 184 equilibrium position of, 184 oscPts,187 Out, 9 Outer, 160,163 Outer products, 160, 163 Output combining parts of, 309 custom formats for, 320 formats, 312

419

Index of graphics, 389 of text, 308 streams, 389 suppressing, 57, 64 to streams, 389 writing to files, 389 Output Form, 3lO, 312,319 OutputStream,389 Overloading, 340

p 1t,2l,25 Packages, 297 context commands, 306 contexts in, 303 declaring names, 220 documentation, 307 for animation, 117 for colors, 183 for complex symbols, 198 for cross products, 152 for elliptic integrals, 79 for Fourier transforms, 212 for graphics, 195 for implicitly defined functions, 121 for implicitly defined surfaces, 121 for Laplace transforms, 212 for nonlinear differential equations, 79 for partial differential equations, 79 for plots of three-dimensional data, 137 for polyhedra, 178 for statistics, 206 for symbolic sums and products, 201 for the conversion of units, 32 for vector fields, 195 formatting, 305 loading, 26, 301, 306 master, 190 names of functions in, 305 . protecting functions in, 304 reading, 26, 31 standard, 26 using other packages, 303 Pac k age s, 26 Padded formatting of numbers, 314 PaddedForm,313-314

Padding with binary zeros, 378 Parameters, 229 using elements oflists as, 14~147 Parametric curves, planar, 126, 129 plots, 122 surfaces, 129 ParametricPlot, 126-127,129, 191 ParametricPlot3D, 122-124, 127-129 Parent directory, 218 ParentDirectory,218 Parentheses, 23 Part, 156 Partial derivatives, 70, 315, 319 derivatives, format of, 316 differential equations, 77, 79, 316 fraction decompositions, 49, 53 Partition, 157, 183 Partitions, 213 Partitions of lists, 157 PartitionsQ, 213, 239 Parts imaginary, 197 of expressions, 232 of strings, 323 real, 197 Pascal, 51, 268, 279, 331 Paste, 11 Paste Template, 14 Path, 221 contexts, 307 Pattems,68,233,23~237

complicated, 242 counting, 237 deleting elements, matching, 237 finding, 235 for complex numbers, 243, 247 for given heads, 241 for optional arguments, 244, 247 for rational numbers, 243, 247 in compiled functions, 375 in strings, 322-323 in transformation rules, 252 matching, 235, 237, 278 named, 243 positions of, 237

420 repeated, 246, 248 restricting, 237-238, 240 unevaluated, 276 with alternatives, 244, 247 with conditions, 240 with tests, 238 Pause, 224 Pausing, 224 PC, 1,3 PDEForm, 319-320 pdeForm, 316, 319 Pendulum double, I, 106 triple, II, 89, 145, 178 pendulumLines, 180-182 Permutations, cyclic, 152, 157 Perturbation expansions, 359 Perturbation', 365 PhysicalConstants',32 pi, 25, 213 Pie charts, 192 piScale, 193 Place holders, 322 in messages, 324 in strings, 309-310 Planar parametric plots, 126, 129 Play, 194 Plot, 81-87,99-103,272-273,275 options for, 88, 206 Plot3D, 108-110,119,275 PlotDivision, 83-84,88 PlotField' , 190, 195 PlotField3D', 190,195 PlotJoined, 132,135 PlotLabel, 83,88, 110, 112 PlotPoints, 83-84, 88, 110, 112-113 PlotRange, 83, 86,88, 100, 110, 112 PlotRegion, 83, 110, 112 Plots, 81 aliasing in, 84 animation, 116 arrays, 102, 105 bar, 192 bending angle, 84, 88 bounding box, 120, 129 contour, 111, 119-120 contour, of data, 135

data, 135 data, with correct scales, 159 density, 114, 119 density, of data, 135 display of, 87 error bars, 192 exporting, 87-88 frames, 102, 105 from a remote host, 104 grids in, 84, 88 initial number of points, 84, 88 labels, 84, 88, 192 lighting, 129 lists, 132, 135 logarithmic, 192 maximum number of subdivisions, 84, 88 of general three-dimensional data, 137 of lists, 132, 135 of several functions, 81, 87 options for, 82, 88, 135 options for three-dimensional, 129 parametric, 122 pie, 192 planar parametric curves, 126, 129 printing, 86, 88 range, 85, 88 ratio of height to width, 135 rows of, 105 shading, 129 space curves, 122, 127, 129 suppressing display, 103, 105 surface, 108, 119 surface, of data, 135 three-dimensional, 106 titles of, 83, 88 tools for, 195 two-dimensional, 81, 87, 108, 119 view point, 120 Plot Style, 83, 202,206 PlotVectorField,190 Plus, 23, 146 Pochhammer,213 Pocket calculator, 17-18 Point, 173,176 Points, 176 decimal,18 joining, in plots, 135

421

Index sample, 88 size of, 177 style of, 206 view, 110, 120 PointSize,177 PolyGamma,213 Polygon, 173, 176 Polygons, 176 faces of three-dimensional, 177 without edges, 177 Polyhedra', 178 PolyLog,213 Polynomial equations, 62, 65 solutions of, 381 PolynomialGCD,216 PolynomialLCM,216 PolynomialMod,216 PolynomialQ, 239, 241 PolynomialQuotient,215-216 PolynomialRemainder, 215-216 Polynomials, 52 coefficients in, 214-215 composing, 216 cyclotomic, 216 equations with, 62, 65 equations with, numerical solutions of, 381 expanding, 45 factoring, 46, 216 greatest common divisor of, 216 interpolating, 203, 205 least common multiple of, 216 length of, 215 maximum power of, 215 modular reduction of, 216 quotient of, 216 remainder of division of, 216 resultant of, 216 structure of, 214-215 testing for, 241 variables of, 148,215 polyOrderList,360 polyOrderSolutionList,364 position, 231-232, 235,237 Positions according to patterns, 237 in expressions, 232 in strings, 323

of the triple pendulum, II positive, 240, 242,348 Positive numbers, testing for, 242 Postfix, 317-318 Postfix notation, 19,23,317-318 PostScript, 87 Potential effective, 107 energy, 90,107 in configuration space, 123 of a rotating double pendulum, I Wintner's,89 Power, 24 Power series, 359 PowerExpand, 49, 53 PowerMod, 38, 40,42,213,357 Powers, 18,24 collecting, 53 expanding, 52 maximum, in polynomials, 215 modular, 42 of matrices, 158, 163 Precision, 376, 378 arbitrary, 376 in b~ilt-in functions, 378 in numerical functions, 381 machine, 376 of calculations, 22 Precision, 376, 378 PrecisionGoal,382-383 prefix, 317-318 Prefix notation, 23, 317-318 Prepare Input, 14, 110 Prepend, 150, 155-156 Prepending elements to lists, 288 PrependTo, 288 Preventing the evaluation, 271, 276 Previous results, 19,23 Prime, 34, 36 factors, large, 384 mth,42

relatively, 34 test, 42 Prime, 36--37,42,213 PrimePi,213 PrimeQ,39,42,213,239,241

422 Primes large, 384 testing for, 42, 241 pri mes, 386 Primitives, 173, 176 Print, 270, 308, 342 Print, 86 Print Selection, 86 Print Form, 312 Printing, 270, 308 custom formats for, 320 graphics, 86, 88 messages, 327 p r i nt p s, 87-88 Problems, eigenvalue, 164, 170--171 Procedural programming, 277, 331 Product, 147-148, 198,200 Products, 148, 198,200 cross, 152 expanding, 52 inner, 163 matrix, 160, 163 numerical, 199,381 of the elements of lists, 146 outer, 160, 163 scalar, 160 symbolic, 199 with scalars, 160, 163 Programming functional, 277, 335 graphics, 172 linear, 216-217 methodologies, 331 object-oriented, 340 procedural, 277, 331 recursive, 332 rule-based, 336 with constraint-propagation, 337 Programs developing, 342 external,391-392 Prolog, 83, 110, 112 Protect, 261-262, 304 Protected, 262-263,266 Protecting attributes, 266 definitions, 266

functions, in packages, 304 symbols, 262 Pseudolnverse, 217 Pseudoinverse matrices, 217 ps fi x, 87-88 PSPrint, 86, 88 Public key cryptosystem, 33 Pure functions, 75,144-145,147,282,335, 368 evaluation of, 275 formal parameters in, 147 short notation for, 144 with attributes, 265-266 Put, 388, 390,392 PutAppend, 388,392

Q QR decompositions, 217 QRDecomposition, 217 Quit, 13 Quit, 12-13 qui t, 12 Quitting external programs, 392 Mathematica, 12 Quotient, 213 Quotients of polynomials, 216

R Radians, 21, 25 Random generator, 37, 42, 130 numbers, 42 Random, 37,42, 130,213 Range, 138-139,142 Ranges in Table, etc., 141 of plots, 85, 88 Raster, 173,176 RasterArray, 176, 372 ra sterps, 87-88 Ratio of height to width, of plots, 135 of the edges of the bounding box, 120

423

Index Rational functions, 48 numbers, 18 numbers, heads of, 241 numbers, patterns for, 243, 247 Rational, 241,243,247 Rationalize, 18,24 Re, 197-198, 213 Read, 389 Reading data, 131, 136 files, 31, 306 from files, 389 packages, 26, 31 ReadList, 131,136,159,201 ReadProtected,266 Real numbers, 18 parts, 197 parts, patterns for, 243 Real, 136, 238,241 Receiver, 33 Record, 136 RecordLists,136 Records empty, in ReadList, 136 in ReadList, 136 RecordSeparators,136 Rectangle, 173, 176 Rectangles, 176 Recursions infinite, 51 limiting, 335 Recursive programming, 332 Red, 177 Red, 181, 183 Red-green-blue color model, 120 Reduce, 60, 64 Reference manual, 1 ReIm', 196, 198,353 Relative context names, 298 errors, 377-378 Relatively prime, 34 ReleaseHold, 272,276 Remainders, 42 of the division of polynomials, 216

Remote host, 104 Remove, 31, 300,306 Removing names, 306 RenameDirectory,219 RenameFile,219 Renaming directories, 219 files, 219 Repeated patterns, 246, 248 Replace, 254 ReplaceAll,254 ReplaceHeldPart,276 ReplacePart, 150,156 ReplaceRepeated,254 Replacing characters in strings, 310, 323 elements of lists, 150, 156 without evaluation, 276 Representation, tree, 230 ResetDirectory,218 Residue, 79 Residues, 73, 79 Resources, 222 memory, 223 Rest, 149,156 Restricting patterns, 237-238, 240 Result last, 23 previous, 23 using previous, 19 Resultant, 216 Resultant, 216 Return, 279, 289-290, 347 Return,322 key, 9 Reverse, 151,157 Reversing lists, 151, 157 strings, 323 RGB,I77 RGBColor, 120, 177 RiemannSiegelTheta,213 RiemannSiegelZ,213 Risch algorithm, 70, 250 rl ogi n, 104 Roots, 24 Newton's method, 282

424 Roots, 65 rot2D,291 RotateLabel, 83, 112 RotateLeft, 152-153,157 RotateRight, 152-153,157 rot Do U b 1 e Pen d . m, 117 Round, 24, 213 Rounding, 24 Roundoff errors, 377 Row-reduced matrices, 217 RowReduce,217 Rows of graphics, 105 RSA, 331, 355, 384 cryptosystem, 34 decoding, 36 encoding, 36 RSA', 37, 359, 384, 386 r s a - p rime s - 100. co n t ro 1,390-391 rsa-primes-100.log,391 RSADecode, 40, 359 rSADecode,358 RSAEncode, 40, 359 rSAEncode, 358 rSAEncodeNumber,357 RSAPrime,385-386 Rule, 162,254 Rule-based programming, 336 RuleDelayed,254 Rules, see also: Transformation rules, 50, 52, 65 generation from equations, 65 transformation, 251, 254 using in evaluation, 52 Run, 392 Running external programs, 392 RunThrough,392

s SameQ, 239-241 SameTest,287 Sample points in numerical integrations, 382 in plots, 88 Saturation, 112, 120 Save, 97, 105,131 Save As Other, 305

Saving definitions, 105 Mathematica binary, 221-222 Scalar multiplication with, 160, 163 products, 160 Scaled coordinates, 177 data plots, 159 plots, 159 Scaled, 177 ScatterPlot3D, 135,201 Schur decomposition, 217 SchurDecomposition,217 sci. math. symbol ie, 5 Scientific notation, 313 ScientificForm,313 Scoping, 331 Search path, 221 Sec, 24, 213 Sech, 24, 213 SeedRandom,213 Select, 236-237, 339 Selecting with tests, 237 Semicolons, 57, 64, 279-280 Sender, 33 Separators in ReadList, 136 SequenceForm, 309-310, 315 Sequences arithmetic, 138, 142 of arguments, 247 of expressions, 183 Series, 200 expansions for the solutions of differential equations, 359 Fourier, 209 power, 359 truncating, 200 Series, 199-200 Session, 2 SessionTime,224 Set, 261 SetAccuracy, 22, 377-378 SetAttributes, 263, 265, 269 Set Delayed, 261 SetDirectory,218 setenv,104

Index SetFileDate, 219 SetPrecision, 22, 377-378 Sets, see also: Lists, 151 complements of, 156 intersections of, 156 unions of, 156 Shading, 110 Shading of surfaces, 129 Shadowing of names, 301 Shallow, 57, 64 Share, 224-225 Shell variable, 11 Short form, 57, 64 notation for pure functions, 144 Short, 57, 64 Show, 83, 87, 119 options for, 135 show,12 Show Lines, 122 ShowAnimation, 117, 182, 189 showFractal,373 Sr,28 Sign, 213 Signature, 213 Significant digits, 376, 378 SignPadding, 314 SiliconGraphics, 11 0 Simplification, 46, 53 of equations, 64 Simplify, 46-48, 53 Simulation, 126 Sin, 24,213 Singular values, 217 Singularities in integrals, 71 SingularityDepth,382 Singularvalues,217 Sinh, 24, 213 Sinlntegral,213 SixJSymbol,213 Size of points, 177 of steps, 119 SKP ac ka ge s, 349 SKPackages' AbsArg' , 354--355 Linearization', 97, 355

425 NonNegativeQ', 349 Perturbation',365 RSA' , 37, 359, 384, 386 Smallest number, 24 smallLagSolRule, 103 smallLinSolRule,103 Software, 5 Solutions generic, 60 matched and composite, 366 numerical, of algebraic equations, 61, 65, 381 numerical, of differential equations, 380381 numerical, of polynomial equations, 381 of algebraic equations, 54, 64 of differential equations, 79 Solve, 54-55,64,216,338 solveOrder, 361 Sort, 151,156,341 Sorting, 341 lists, 151, 156 Sound,9,194 Space characters, 17 configuration, 123 curves, 122, 127, 129 in tables, 142 Sparse matrices, 216 Special characters, 321-322 evaluation, 271 SphericalHarmonicY, 213 SphericalRegion,110 springLines, 185 Spring, nonlinear, 359 Sqrt,24 Square roots, 24 Stable equilibrium, 108 Stack,347 Stack,346-347 Standard evaluation, 268 notation, 23, 230 packages, 26 Starting external programs, 392

426 Starting Mathematica, 9 from text-based interface, 10 notebook front end, 9 StartingStepSize, 382 Statistical analysis, 205 Statistics, 206 Statistics', 205-206 Step size, 119 Stiffness matrix, 167 StirlingSl,2l3 StirlingS2,213 Straight forward expansions, 365 Strained coordinates, 365 StrainedSolutionList, 365 Streams, 389 String, 136, 321 StringDrop, 323 StringForm, 309-310 Stringlnsert, 321,323 StringJoin, 120, 323 StringLength,323 StringMatchQ, 239, 322-323 StringPosition, 323 StringQ,239 StringReplace, 323 StringReverse,323 Strings, 309-310, 321, 323 concatenating, 120 converting to expressions, 323 converting to lists of characters, 323 corresponding to expressions, 120,323 dropping characters of, 323 formatting, l74, 177 inserting characters, 323 joining, 323 metacharacters in, 322 parts of, 323 patterns in, 322-323 place holders in, 309-310 positions in, 323 replacing characters, 323 reversing, 323 special characters in, 322 StringTake, 323 StringToList,40 stringToList,357

Structure of expressions, 229, 232 of polynomials, 214-215 Stub, 266, 301 Style, 305 Style for points and lines, 206 Subcontexts, 302 Subdivisions in numerical integrations, 382 in plots, maximum number of, 84, 88 Subexpressions, 231 testing for, 242 Sublists, 149, 156 in ReadList, l36 Subscript, 315-316,318 Subscripted, 315,317 Subscripts, 315, 317 Subsessions, 344 Substitutions, 50 of solutions into equations, 55 Subtractions, l7, 23 Sum, 147-148, 198,200,275 Sums, 148, 198 numerical, 199-200, 381 of the elements of lists, 146 symbolic, 199,201 Sun, 5 Superscript, 315,318 Superscripts, 315, 318 Suppressing lines, 122 messages, 327 output, 57, 64 plots, 103, 105 Surface graphics objects, 176 implicitly defined, 121 parametric, 129 plots, 108, 119 plots of data, 135 shading, 129 SurfaceGraphics, 176 Switch, 275, 278-279, 287, 331 Symbol,238 Symbolic calculations, 44 Fourier transforms, 212

427

Index Laplace transforms, 212 products, 199 sums, 199,201 SymbolicSum', 199,201 Symbols complex, 195, 197-198 contexts of, 306 definitions for, 392 exporting, 302 global,290 Greek,90 protecting, 262 removing, 306 with associated definitions, 260 SyntaxQ, 239 System', 29, 299 Systems of algebraic equations, 60, 64 of algebraic equations, numerical solutions of, 62, 65 of differential equations, 74, 79

T Table, 116,119, 130, 138,141,275 TableAlignments, 142 TableDepth, 142 TableDirections, 142 TableForm, 139,142,312 options for, 139,142 TableHeadings, 139,142 Tables, 116, 119, 141 alignment in, 142 dispatch, 253-254 formatting, 142,312 levels of, 142 multidimensional, 141 sequence of dimensions in, 142 spaces in, 142 titles in, 142 TableSpacing, 142 Tabs, 322 Take, 149,156 Tan,24,213 Tanh, 24, 213 TargetFunctions, 196,198 Taylor expansions, 199-200

Template, 14 Temporary, 266 Tensors, 158 indexed, 140 inner products of, 163 outer products of, 160, 163 Tests, 236, 241, 278 for elements, 237 for primes, 42 for vectors, 157 functions for, 239 in patterns, 238 TeX, 311, 319 format for, 312 TeXForm, 311-312, 319 Text, 9, 176, 309 cipher, 33 converting, 323 format, 312 formatted, 177 output, 308 sending to external programs, 392 subscripts in, 315, 317 superscripts in, 315, 318 Text, 173, 176 Text-based interface animation in, 117 exporting graphics from, 87 printing graphics in, 86 quitting Mathematica, 12 starting Mathematica, 10 suppressing lines in, 122 Text Form, 312 Thickness, 174,177,180 Thickness of lines, 177 Thread,148, 162-163, 184 Threading automatic, attribute for, 266 overlists, 162-163 Three-dimensional data, general plots of, 137 graphics, 175 plots, 106 ThreeJSymbol,213 Through, 145,148 Throw,289 Ticks, 83, 111-112

428 Time, 224 absolute, 224 converting, 224 limiting, 224 resources, 222 TimeConstrained, 222, 224 Times, 23-24, 147 TimeUsed,224 Timing, 5, 38,42,224 Timings, 42 Titles, 9 in tables, 142 of plots, 83, 88 tmp, 118 ToCharacterCode, 321,323 ToDate, 224 ToExpression, 321-323 Together, 49,53 Token words, in ReadList, 137 TokenWords, 137 Tools for graphics, 195 ToRules,65 Torus, 121 torus, 123 ToString, 116,120,321,323 Total derivatives, 67 differentials, 67, 78 Trace,268,270,325,342-344,347 evaluation of, 275 options for, 347 TraceAbove, 347 TraceBackward,348 TraceDepth, 348 TraceDialog, 344-345,347 TraceForward, 348 TraceOff,348 TraceOn, 348 TraceOriginal, 348 Tracing, 268, 270 Transcendental equations, 61, 339 Transformation rules, 251, 254 applying, 254 delayed, 253 evaluation of, 274 immediate, 253-254 multiple evaluation of, 252

nested,251 optimizing, 253-254 patterns in, 252 Transforms Fourier, 207, 212 Fourier, continuous, 209, 212 Laplace, 211-212, 336 Transpose, 158-159,163, 169 Transposition, 158, 163 Trapdoor one-way functions, 34 Tree representation, 230 TreeForm, 229-230, 311-312 Triangulation, 137 Trig, 47,52-53 Trigonometric functions, 20, 24 expanding, 47,52 factoring, 47, 53 inverse, 24 Triple pendulum, 89,145,178 positions of, II triplePendulum.m,97,182 True, 240-241 True I False, 375 TrueQ, 239-240 Truncating series, 200 Two-dimensional graphics, 175 plots, 81, 87, 108, 119 Types data, 340 file, 219

u Unequal,64 Unevaluated, 271, 276 form of arguments, 276 keeping arguments, 266 patterns, 276 Unevaluated,276 Uninstall,392 Union, 151,156 Unions of intervals, 378 of lists, 156 Unique, 293, 296 Unique names, 293, 296

Index Uni ts' , 26, 32 Units, converting, 32 Unit, imaginary, 21, 25 UNIX, 1,26,118 Unknowns, 44 Unprotect, 261-262, 304 Unprotecting symbols, 262 UnsameQ,239-241 Unstable equilibrium, 108 Uppercase, 45 UpperCaseQ, 239 Upvalues,262 Upvalues, 260, 262 evaluation of, 269 Usenet,5

v ValueQ, 240,242 Values absolute, 24, 197 local, 295, 297 testing for, 242 Variables control, 288 dummy, 294 elimination of, 61, 64 global, 290 in compiled functions, 375 loca~ 181, 183,290,296 local, evaluation of, 275 of polynomials, 148,215 optional, 245, 247 shell, 11 Variables, 143,148,215 Vector fields, 190, 195 vectorQ, 153,157,240-241 Vectors, 158 cross product of, 152 indexed, 140, 142 inner products of, 163 multiplications of, 160 outer products of, 160, 163 scalar products of, 160 testing for, 157,241 VerifyConvergence,383 Version, 5

429 View point, 120 ViewCenter, 111 ViewPoint, 110--111,120 ViewVertical,l11 VMS, 1

w Warnings, 323 Which, 275, 278, 287,331 While, 280,288, 331-332 Why the Beep?, 14 Width of plots, 135 Wildcard characters, 15-16 Windows, 3 Wintner's potential, 89 with, 292-293,296 Wolfram, Stephen, 14 Word, 136 Word separators in ReadList, 136 Words empty, in ReadList, 136 token, in ReadList, 137 wordSeparators,136-137 WorkingPrecision, 379, 381 Write, 388-389 WriteString,388-389 WynnDegree, 383

x X, 104 XlI,3 xhost,104

y Y,89 Yellow, 183

z Zero lines, 113 Newton's method, 282 Zeta, 213