Mathematica Cookbook
Sal Mangano
Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
Mathematica Cookbook
by Sal Mangano
Copyright © 2010 Salvatore Mangano. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information,
contact our corporate/institutional sales department: (800) 998-9938 or
[email protected].
Editor:
Mike Loukides
Production Editor:
Adam Witwer
Production Services: Precision Graphics
Cover Designer:
Karen Montgomery
Interior Designer:
David Futato
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Mathematica Cookbook, the image of a solarium seashell, and
related trade dress are trademarks of O’Reilly Media, Inc.
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 O’Reilly Media, Inc.,
was aware of a trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author
assume no responsibility for errors or omissions, or for damages resulting from the use of the
information contained herein.
Wolfram Mathematica ® is a registered trademark of Wolfram Research, Inc. The Mathematica
Spikey logo is a registered trademark of Wolfram Research, Inc. The Mathematica software design,
“" look and feel",” display, and other graphic elements are copyright of Wolfram Research, Inc.
ISBN: 978-0-596-52099-1
To Wanda, Leonardo and Salvatore:
My life would not compute without you.
Included with this book is a free 30 day trial of the Wolfram Mathematica ® software.
To access your free download, simply go to http://www.wolfram.com/books/resources
and enter license number L3294-005. You will be guided to download and install the
latest version of Mathematica.
Table of Contents
1
4
9
12
13
16
18
20
23
43
48
51
62
v
66
73
77
79
85
97
100
102
103
105
110
112
114
119
121
125
145
vi | Table of Contents
155
157
168
169
170
171
177
178
181
187
192
196
198
201
202
209
213
227
237
238
247
249
252
255
258
260
263
269
270
275
283
285
290
Table of Contents | vii
292
295
296
298
302
306
309
313
317
320
329
332
361
viii | Table of Contents
373
374
375
376
377
378
379
380
384
386
389
390
392
393
394
397
403
405
408
413
414
415
416
419
422
425
426
427
429
431
435
438
441
443
447
450
452
455
456
461
464
Table of Contents | ix
466
468
471
472
475
477
479
483
486
492
496
499
505
507
510
513
516
519
522
524
533
537
549
x | Table of Contents
557
559
561
563
565
574
578
583
585
593
594
598
600
607
609
613
615
619
622
624
625
627
630
633
Table of Contents | xi
641
643
646
656
658
661
662
663
665
669
678
686
689
692
694
700
707
xii | Table of Contents
711
714
715
719
720
721
723
725
727
728
733
736
737
739
741
743
746
747
753
756
758
769
Index � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �777
Table of Contents | xiii
Preface
Introduction
If you were stranded on a desert island with only your laptop (and presumably a large
solar panel), what software would you want to have with you? For me the answer
definitely includes the latest version of Wolfram Mathematica. Whether you are a
scientist, engineer, or mathematician, a Wall Street quant, a statistician or programmer, or even an artist or musician, you will be a better one if you have this tool at your
disposal. Of course, having a tool and knowing how to use it well are quite different
things. That is why I wrote the Mathematica Cookbook.
I am a big fan of O’Reilly cookbooks, as these books are designed to help you solve
real-world problems. Mathematica is an ideal candidate for a cookbook because it
is so vast, deep, and full of traps for the novice. I was ecstatic to learn that O’Reilly
was looking to publish a Mathematica cookbook and even more excited when I was
chosen to be its author. I have been a user of Mathematica since version 3.0. Although
that was over 13 years ago, I still remember the frustration of trying to solve problems in this system. I don’t mean this in a derogatory way. The frustration a newbie
experiences when trying to learn Mathematica comes from the knowledge that you
are sitting in front of a highly advanced computational platform that eventually will
magnify your productivity tenfold—if you can only wrap your mind around its unfamiliar idioms. If you are a new (or even not-so-new) user of Mathematica today, you
are simultaneously in a better and a much worse position than I was with version 3.0.
You are in a better position because Mathematica 7.0 is vastly more powerful than 3.0
was back then. Not only has the number of available functions doubled, but Mathematica has fundamental new capabilities including dynamic interactivity, curated
data sources, parallel processing, image processing, and much more. You are in a
worse position because there is much more to learn!
As Mathematica grows, it remains largely unchanged in its core principles. This book
is designed to help you master those core principles by presenting Mathematica in
xv
the context of real-world problems. However, my goal is not just to show you how to
solve problems in Mathematica, but to show you how to do so in a way that plays to
Mathematica’s strengths. This means there is an emphasis on symbolic, functional,
and pattern-based styles of programming. Mathematica is a multi-paradigm programming language; you can easily write code in it that a Fortran or C programmer
would have little trouble following. However, the procedural style that this entails is
not likely to give you good performance. More importantly, it will often cause you to
write more code than necessary and spend more time adapting that code to future
problems. Stephen Wolfram has said that a correct Mathematica program is often a
short Mathematica program. There is much truth to this. The truth comes from the
idea that good Mathematica programs leverage the capabilities of the vast built-in
library of both general-purpose and highly specialized functions. Programming in
Mathematica is a search for the right combination of primitives. My hope is that this
cookbook will play a role as your guide.
MathematicaCookbook.com
One risk of authoring a cookbook is that it is almost inevitable that something someone finds important will be left out. With Mathematica, this risk is a certainty because even as I wrote the book, Mathematica’s capabilities grew. However, even if you
drew a line at, say, version 6.0, you would find that there are still many topics that I
do not cover in the book, for various reasons. To remedy this and to create a living
resource that I hope the Mathematica community will help nourish, I am launching
http://mathematicacookbook.com. Here you will find recipes that did not make it into
this book, and more importantly, you will be able rate recipes, contribute your own,
or provide alternative implementations to those found in the book or on the site.
Structure of This Book
The Mathematica Cookbook is not necessarily meant to be read from start to finish
like a conventional book (although you are certainly welcome to do so!). Having said
that, the chapters are organized in a purposeful way. Chapters 1 through 8 present
general techniques that all users of Mathematica should know. These chapters are
largely self-contained, but sometimes it is necessary to use features in one chapter
that are covered more deeply in another. Cross-references within each recipe should
prevent you from getting stuck. However, keep in mind that a cookbook is not the
same as a tutorial, and you should also make frequent use of the Mathematica reference, tutorials, and guides that are integrated into Mathematica’s help system. Chapters 9 through 14 cover specific domains of Mathematica application. If you are the
xvi | Preface
type of person who learns best by examples from your area of expertise, you will benefit from seeing the techniques of the first chapters leveraged in problems related to
physics, engineering, calculus, statistics, music, finance, and more. Finally, Chapters
15 through 19 cover important techniques, extensions, and tools that make Mathematica unrivaled as a technical software development tool.
Chapter 1 covers numerics. For the most part, Mathematica simply does the right
thing when computing numeric results, as you would expect. In pure mathematics,
numbers are formal objects that are well behaved, but when you represent numbers
in a finite discrete device like a computer, often you will need to understand issues of
precision and accuracy in order to get reasonable results on certain classes of problems. Further, numbers have different representations in Mathematica (Integers, Rationals, Complex, and some exotic types like Intervals). Then there is an issue of input
and presentation: Mathematica supports different base representations and different
display formats. This chapter has recipes that cover all these issues, and it is wise to
have some familiarity with them before using any of the numeric algorithms.
Functional programming is a style of Mathematica development that most seasoned
users prefer. Chapter 2 dives deeply into functional programming, Mathematica style.
Because Mathematica was designed to support multiple development paradigms, its
functional programming abilities are not as pure as languages like Haskell. This is actually a big plus, because if you are using Mathematica chances are you are solving a
problem, and it’s the solution rather than the aesthetics that is foremost in your mind.
Mathematica programmers prefer the functional style because it leads to efficient
programs. It also leads to elegant programs. In the context of programming, elegant
means the combination of brevity, power, and clarity. There is an amazing sense of
intellectual satisfaction that comes from finding a concise functional solution, and
this feeling creates the positive feedback that will draw you into Mathematica. However, this style is often mysterious to people who come to Mathematica from other
languages like Fortran, C, Mathlab, or Microsoft Excel. I think this chapter will help
you discover the rewards of the functional style.
Chapter 3 presents Mathematica data structures, which are largely built on the foundation of lists. From lists, Mathematica derives matrices and higher order tensors,
sparse matrices, and more. Knowing how to manipulate these structures is essential
for almost any application of Mathematica. This is obvious if you are doing linear
algebra, but list processing is integral to almost every facet of use. This chapter also
shows how to implement other types of data structures, such as a dictionary that
leverages the fast associative look-up that is part of Mathematica’s evaluation engine.
Pattern-based programming revolves around pattern matching and transformation.
Chapter 4 introduces Mathematica’s rich pattern-based techniques. Patterns are not
Preface | xvii
leverages the fast associative look-up that is part of Mathematica's evaluation engine.
Pattern-based programming revolves around pattern matching and transformation.
Chapter 4 introduces the Mathematica's rich Pattern based techniques. Patterns are
not a feature must mainstream languages but is tremendously powerful and a must
know
technique
you hope to languages,
accomplishbut
anything
non-trivial
in Mathematica.
Of
a feature
of mostif mainstream
they are
tremendously
powerful and
all
the
techniques
at
your
disposal,
pattern-matching
and
replacement
is
the
one
essential if you hope to accomplish anything nontrivial in Mathematica. Of all the
that
is the most
likely
to yield
the "wow"
reaction
get whenisyou
seemingly
techniques
at your
disposal,
pattern
matching
and you
replacement
the see
oneamost
likely
simple
looking
piece
of
code
do
something
not
so
simple.
To
whet
your
to yield the “wow” reaction you get when you see a seemingly simple lookingappetite,
piece of
here
of my favorites.
code isdoone
something
not so simple. To whet your appetite, here is one of my favorites.
In[190]:= runEncode@l_ListD := Map@8Ò, 1< & , lD êê.
8head___, 8x_, n_<, 8x_, m_<, tail___< ß 8head, 8x, n + m<, tail<
In this little
by Frank
Frank Zizza
Zizza (which
(which won
won aa programming
programming contest
contest at
at the
the 1990
little diddy
ditty by
a list
andand
return
the the
list in
encoded
Wolfram conference),
conference) the
the goal
goalisistototake
take
a list
return
listrun
in length
run length
enform.
Don’t
worry
if
this
code
seems
cryptic;
it
won’t
after
you
have
recipes
from
coded form. Don't worry if this code seems cryptic; it won't after you have recipes from chapters 2 and 4
Chapters
2 and
4 under
yourinput
belt.{1,
For 1,
example,
1, 3, produce
3, 3, 3}
under
your belt.
For
example,
2, 2, input
2, 1,{1,
3, 1,3,2,3,2,3}2,should
{{1,
2},
{2, 3},
{1,2},1},
should
produce
{{1,
{2,{3,
3}, 4}}
{1, 1}, {3, 4}}.
In[191]:= runEncode@81, 1, 2, 2, 2, 1, 3, 3, 3, 3
- Xem thêm -