Docsity

Roman Maeder - Computer science with Mathematica, Appunti di Elementi di Informatica

Anteprima parziale del testo

Scarica Roman Maeder - Computer science with Mathematica e più Appunti in PDF di Elementi di Informatica solo su Docsity!

Pt:BLISHED BY THE PRESS SYNDICATE OF THE UNIVERSITY OF CAMBRIDGE The Pitt Building, Trumpington Street, Cambridge, United Kingdom

CAMBRIDGE l:N!VERS!TY PRF.SS The Edinburgh Building, Cambridge CB2 2RU, UK http://www.cup.cam.ac.uk 40 West 20th Street, New York, NY 10011-4211. USA http://www.cup.org 10 Stamford Road, OakJeigh, Melbourne 3166, Australia Ruiz de Alarc6n 13. 28014 Madrid, Spain

© Roman E. Maeder 2000

Till.� book is in copyright. Subject to stattltory exception and to the provisions of relevant collective licensing agreements. no reproduction of any part may take place without the written permission of Cambridge University Press.

First published 2000

Printed in the United States of America

Typeset by the author using Mathematica 4.0 and the TEX typesetting language on a Sun ULTRAsparc ll computer.

A catalox recordfor this book is available from the British Library'

Library· of Congress Catalog inK in Publication Data Maeder, Roman. Computer science with Mathematica : theory and practice for science, mathematics, and engineering I Roman E. Maeder. p. em. Includes index. ISBN 0-521-63172-6.- ISBN 0-521-66395-4 (pbk.) I. Mathematica (Computer file) 2. Mathematics- Data processing.

  1. Mathematica (Computer programming language) I. Title. QA76.95.M34 1999 510'.285'5369-dc21 99- CIP

The author and Cambridge University Press, Inc., make no representations, expressed or implied, with respect to this documentation or the software it describes, including, without limitations, any implied warranties of merchantability or fitn for a particular purpose, all of which are expressly disclaimed. The author, or Cambridge University Press, their licensees, distributors, and dealers shall in no event be liable for any indirect, incidental, or consequential damages.

ISBN (1 521 63172 6 hardback ISBN 0 521 66395 4 paperback

Contents

Preface ix

About This Book xili

1 Computers and Science

1.1 From Problems to Programs (^3) 1.2 Computers 14 1.3 Programming Languages 18 1.4 Computer Science 23

2 Mathematica's Programming Language

2.1 Arithmetic and Logic (^27) 2.2 Definitions (^30) 2.3 Simple Program Structures (^34) 2.4 Structure of Expressions 44 2.5 Help with Problems. 49 2.6 Exercises (^52)

3 Iteration and Recursion

3.1 The Greatest Common Divisor 57 3.2 The 3x + l Problem. 60 3.3^ Advanced Topic: Loop Invariants 64 3.4 Application: Differential Equations 69 3.5 Exercises (^76)

4 Structure of Programs

4.1 Complex Parametric Lines 81 4.2 The First Package 8 5 4.3 Optional Arguments 90 4.4^ A Template Package 94 4.5 Exercises (^96)

5 Abstract Data Types

5.1 Definition of Abstract Data Types (^99) 5.2 Example: Modular Numbers (^102) 5.3 Design of Abstract Data 'JYpes 106 5.4 Exercises. (^110)

v

Contents

13 Databases

13.1 Database Design 13.2 Relational Databases. 13.3 Data Entry and Queries 13.4 Commercial Databases 13.5 Exercises......

14 Object-Oriented Programming

14.1 Introduction..... 14.2 Example: Bank Accounts....... 14.3 Principles of Object-Oriented Programming 14.4 Application: Collections. 14.5 Exercises.......

Appendix A Further Reading

A.l A Guide to the Literature A.2 References......

Appendix B More Information About Mathematica

B.l Computations You Can Do with Mathematica
B.2 The Code for the Illustrations in this Book.
B.3 Mathematica's Evaluation Method

B.4 Syntax of Operators

Index.

vii

303 308 314 319 321

325 327 330 332 341

345 347

353 364 368 374 377

Preface

This book provides an introduction to computer science, and shows how modern computer
based tools can be used in science, mathematics, and engineering. Computer-aided math
ematics has reached a level where it can support effectively many computations in science
and engineering. In addition to treating traditional computer-science topics, an introductory
book should show scientists and engineers how these computer-based tools can be used to
do scientific computations. Students must get to know these possibilities, and they must gain
practical experience. Learning a traditional programming language becomes less important,
just as learning arithmetic is not a main topic of mathematics education. In an introductory
book, it is clearly necessary to limit ourselves to a small part of the huge field of computer
science. We emphasize topics that are related to possible applications in mathematics and the
sciences. Technical and practical computer science have therefore been neglected.
It is certainly worthwhile to combine an introductory computer-science course with exer

cises. In the same way as we learn a foreign language by speaking the language and by studying

literature in that language, we should apply algorithmi c knowledge by studying programs and
writing our own. If we can solve an interesting problem from mathematics or the sciences at
the same time, all the better! Traditionally, such introductory courses use languages such as
Pascal, C, or FORTRAN. These languages have in common that the effort to develop even a
small program (one that adds two numbers, for example) is considerable. One has to write
a main program that deals with input and output, and to compile the program. Furthermore,
these languages cannot be used easily to solve nonnumerical problems. Leaving aside these
practical difficulties gives us room to look at other topics in computer science, an extension that
is not offered in traditional programming courses. In this way, we gain insight into computer
science, which consists of much more than writing small programs.
Another disadvantage of traditional languages is that they support only procedural pro
gramming. T his style is an important one, but it is not the only option and it is not always the
best approach. I prefer a language that does not force this programming style on programmers.
The programming style should be chosen to fit the problem to be solved, rather than vice
versa. The language should be interactive, to encourage experimentation and to allow us to
call individual functions without having to write a whole program.
Mathematica was first released in 1988, and it is being used with increasing frequency
in teaching, research, and industry. A by-product of the symbolic computation system, it
is a programming language that differs from traditional languages in many important ways.

ix

Preface xi

  • The programming language supports all traditional programming styles, including proce
dural programming. The language can therefore be used for traditional computer-science
classes (algorithms and data structures) as well.
  • (^) The rule-based programming system allows a natural expression of scientific facts.
  • Graphics allows the meaningful presentation of results and experimental data. It is also
useful for showing how algorithms work.
  • We can call external programs and exchange results, so we can use external software
libraries and even control laboratory experiments.
This book grew out of class notes for a course given at the Department of Mathematics and
Physics at the Swiss Federal Institute of Technology, Zurich. It was originally published in
my native German language [4 8], and I am glad to present now my own English translation
and adaptation.
I am thankful to Erwin Engeler, John Gray, and Stephen Wolfram for their inspiration and
many interesting discussions. Helpful suggestions on particular topics came from R. Marti
and H. Mossenbock. Lyn Dupre proofread an early version of the manuscript, and Karen
Tongish copyedited the final version. The publishers of the German and English editions,
Ekkehard Hundt and Alan Harvey, helped me to keep going. Many thanks to the anonymous
reviewer whose favorable comments and useful suggestions motivated me to finish this project.
R.E.M.

Wollerau, March 1 999

About This Book

The emphasis of this introduction to computer science is algorithmics - that is, the study

of algorithms. We do not want this activity to become a dry exercise, so we shall try out
all algorithms as soon as possible. Our programs will often consist of only a few lines of
code. Such simplicity allows us to concentrate on the essentials and to ignore peripheral
matters such as input, output, and driver programs. Often, however, we shall develop whole
packages, collections of various procedures grouped around a topic. The methods for writing
such packages will be explained in Chapter 4. After all, computer science is not about writing
small, throwaway programs but rather developing larger applications. In addition to finding
suitable algorithms, this entails techniques of documentation and maintenance of software.
We shall present some of these techniques.

Mathematica does have a major advantage over traditional programming languages: It

is interactive. lnteractivity encourages experimentation and allows us to test each function
separately and to study its behavior. In the first section we shall study recursively defined
functions, a topic often considered difficult and therefore treated with caution. We also have
at our disposal a symbolic, numerical, and graphic computation system- an added benefit that
we shall use in many ways.

Overview of Contents

Each chapter after the first two introductory ones presents a topic from computer science
together with its applications and examples in mathematics, the sciences, and engineering. You
can choose from the many applications presented those that correspond to your background.
Because only one system (Mathematica) is used for all programs and all calculations, the
extra work of learning about practical matters such as editing or working with the application
is minimized. My experiences have shown that Mathematica is rather easy to learn; you
will be able to work with it quite soon, after overcoming any initial difficulties you might
encounter.
Chapter I is not a prerequisite for the rest of the text, if you already know something about
computers. It shows how computers can be used in the sciences, explains the history and
current state of computers, and discusses what computer science is all about.
The quick introduction to Mathematica's syntax in Chapter 2 should be studied with a
computer at hand, so you can try out the calculations for yourself and get a feeling for what it

xiii

About This Book ----------------- XV
co11ections of data provides the tools for their easy manipulation. We treat these concepts in

Chapter 1 3.

Chapter 14 introduces a n important programming style: object-oriented programming. It

is especially useful for larger applications and for the design of reusable software.
Appendix A is an annotated bibliography on the topics programming methods, teaching
with Ma thematica , and literature about Mathematica ; it includes a section with references for
the topics treated in this book, followed by the bibliographical data.
The more detailed explanations about the structure of Mathematica given in Appendix B
are useful for self-study and are also meant as a reference. For a complete reference to

Mathematica, you should consult The Mathematica Book 174]. The appendix of that manual

contains an alphabetical listing of all built-in functions, commands, and other objects. This
listing, as well as the complete manual, is available on-line in Mathematica (in the Help
Browser). Looking up an item there is much easier than is looking it up in a heavy book.
Studying the Mathematica manual is not a prerequisite for reading this book.
Appendix B also contains a section that demonstrates Mathematica 's more advanced
capabilities. Finally, we give the programs used to generate the chapter-opener pictures.
Certain sections are labeled "Advanced Topic." They presume that the reader has a more
complete mathematical background than is required for the rest of the book; they are optional.
Sections marked "Special Topic" are independent from the rest of the book. Sections
marked "Example" or "Application" develop a topic using a larger example that is of interest
in its own right.
At the end of most sections, there is a review list, entitled "Key Concepts," of new concepts
that have been introduced. At the end of the chapters, you will find numerous exercises.
The verso page following a chapter title contains a brief overview of the sections in the
chapter, and an explanation of the graphic illustration on the title page. The programs for
generating these pictures are in the package Pictures.m; see Section B.2.
Comments on Exercises
We assume that you already know how to work with your computer. T he installation of Math
ematica on your machine is explained in the documentation that comes with the software. This
documentation includes a manual that explains the machine-specific features of Mathematica.
The best way to learn Mathematica is to do practical exercises at the machine. In the beginning,
you may want to look at one of the included demonstration documents before moving on to your
own small examples. You can also find simple examples in the section titled "A Tour of Math
ematica " in The Mathematica Book. We recommend that you work through such examples.
There are two ways to use Mathematica on a computer: the Notebook frontend and a
simple dialog with the kernel of Mathematica (the kernel is the part that does the actual
computations; the frontend serves as a user interface to the kernel). The Notebook frontend
is more comfortable to use, but is not required for the examples in this book, which have

xvi --- About This Book

all been computed by direct interaction with the kernel. All examples have been tested with

Version 4.0 of Mathematica.

If you use the Notebook frontend, your interaction with Mathematica will look a bit

different from the way it is presented in the book, but the results will be the same. Numbering
of your inputs happens only after they have been sent to kernel for evaluation (with SHIFT

RETURN or ENTER), because the number is given out by the kernel, rather than by the frontend.

An example Notebook is reproduced on page 95.

Please note that each example has been computed in a fresh Mathematica session. We

recommend that you begin new sessions to avoid any influences from previous computations

whenever the numbering of the input lines restarts at 1. Under the Notebook frontend, you

can choose the menu command Quit Kernel to start a fresh kernel.
The frontend allows you to store your programs and your sample computations in the same
document (the Notebook) and to open them again in the future. We recommend, however,

that you store packages in separate files, and read them into Mathematica using <<file '. This

command to read in a package is often not shown in the dialogs in this book. If you want to

reproduce the examples, you must read the appropriate programs into Mathematica first.

Electronic Resources
All programs mentioned in this book are available in machine-readable form

from the book's Web site, located at http : I /www. mathconsult. ch/CSM/.

There, you will find compressed archives of all files ready to download. Pack
ages have the extension .m; Notebooks have the extension .nb. Both kinds of
files can be opened with the frontend. Packages can be read into the kernel

directly (using «CSM' file ' ) and can also be opened with any text editor (in ASCII mode).

The archive should be extracted into the AddOns/Applications subdirectory of your Mathe

matica installation directory. Extraction will create a subdirectory CSM inside the Applications

directory.
Mathematica can display its own installation
directory. The value of $TopDirectory
will reflect the actual place where you in
stalled Mathematica on your computer.
If you installed the files correctly, this simple
test should give the result shown here. Note
the use of the backquote ' as a machine
independent way to specify directories and

flies.

All packages mentioned in this book can be
loaded by prefixing their name with the di
rectory, CSM.
In[ 1 ] : 2 $TopDirectory

Out[l]� /usr/local/Mathematica

In[2 ] : � << CSM'Test'

The CSM packages are correctly installed in /usr/loca1/Mathematica/Add0ns/Applications/CSM

In[3] : = << CSM'ComplexParametricP1ot'

xviii

In[1] : = Factor [ XA34 - 1 ]
Out [ 1 ] = (- 1 + x) (1 + x)

----^ About This Book

Here is an example of such a dialog. You
would enter only the input set in boldface.
The prompt In[ 1 ] : = is printed by Math
ematica. If you work with the Notebook
frontend, this prompt will appear after you
evaluate your input with ENTER.
(1 - X + X - X + X - X + X - X + X - X +
X - X + X - X + X - X + X )
(1 + X + X + X + X + X + X + X + X + X +
X + X + X + X + X + X + X )

In most programming languages, you can define procedures, functions, or subroutines. Mathe

matica uses only one mechanism, called definitions, which look like f [x_] : = def. Chapter 2

provides a short explanation of the elements of Mathematica's programming language. A more

in-depth presentation is given in Appendix B.
The table on page xx lists the mathematical notations that we use. Equations, figures,

program listings, and tables are numbered by section. For example, Equation 3.1-1 is the first

equation in Section 3. 1.

Colophon

Mathematica dialogs were computed on a Sun ULTRAsparc II with Version 4.0 of Mathematica

using the initialization file init.m reproduced here.
Format [Continuation( _ ] ] '2 ""

SeedRandom(10000]

Off ( General : : spell , General : : spell 1 ]

Unprotect [Short] Short ( e _ ] : = Short (e , 2 ] Protect [Short]

(* lines are very short * )

SetOptions ( Plot3D, AspectRat io -> Automat ic , PlotPoints - > 3 5 ] SetOpt ions [ Graph ics3D , AspectRat io -> Automatic ] SetOptions [ ParametricPlot , AspectRat io -> Automatic SetDption s [ ParametricPlot3D , Axes -> None ] Needs ( "Programm ing!nMathematica' Options ' " ] SetAllDpt ions( ColorOutput -> GrayLevel ] $DefaultFont = {"Times-Roman" , 9.0} (* font in graphics ) SetOptions ( " stdout", PageWidth->56] ( line width *)

init.m: Matlzematica initialization for this book.

The manuscript is written in Ib.Tpc [40] (with many custom macros). It contains only the input

of the sample computations. The results were computed by Mathematica and were inserted

About This Book xix

automatically into the file. The bibliography was produced with BmT_EX [59], and the index was sorted with makeindex [41]. Those figures not produced with Mathematica were designed with FrameMaker and included in PostScript form. The reproductions of Notebooks and help screens were taken from the computer's screen. Finally, the output of M.Tp. was converted into PostScript and phototypeset.

Chapter 1

Computers and Science

In the first section of this chapter we show how typical scientific problems can be solved with the help of a computer. We also discuss methods to develop programs to solve these problems. Section 1.2 covers computers and operating systems. We describe the historic development and operating principles of a modem workstation. Programming languages have developed along with hardware. In Section 1.3, we look at a program in several forms - from machine language to a higher-level programming language. An overview over the branches of computer science (Section 1.4) concludes the chapter.

About the illustration overleaf:

The illustration shows one of the simplest functions leading to chaotic behavior. We iterated the map f: x 1---t 4x( l - (^) x). The first nine iterations with three nearby starting values are displayed. These values separate more and more, and show quite different behavior after only eight iterations. The picture was produced with the command (see Pictures.m):

Animate [ Functionlterat ion [4# ( 1-#) & , {0. 099 , 0. 1 , 0.101} , 0 , n , { 0 , 1} ,

Frame->True , FrameTi cks->None] ,

{n , 1 , 9 , 1} ] ;.

With the Mathematica frontend you can produce a genuine animation; here, on paper, we have to put the frames next to each other.