This book is an example-based introduction to techniques, from elementary toadvanced, of using Mathematica, a revolutionary tool for mathematical computation and exploration.. By integra
Trang 2Mathematica in Action
Trang 5Springer New York Dordrecht Heidelberg London
All rights reserved This work may not be translated or copied in whole or in part without the written permission of the publisher (Springer Science+Business Media, LLC, 233 Spring Street, New York, NY 10013, USA), except for brief excerpts in connection with reviews or scholarly analysis software, or by similar or dissimilar methodology now known or hereafter developed is forbidden The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights
Printed on acid-free paper
Springer is part of Springer Science+Business Media (www.springer.com)
© Springer Science+Business Media, LLC 2010
Use in connection with any form of information storage and retrieval, electronic adaptation, computer
Wolfram Mathematica is a registered trademark of Wolfram Research, Inc ®
Library of Congress Control Number: 2010928640
Trang 62.1 Basic Number Theory Functions 54
77
3.4 The Cycloid’s Intimate Relationship with Gravity 90
Contents
3.5 Bicycles, Square Wheels, and Square-Hole Drills 98
1 Plotting
3 Rolling Circles
Trang 76 The Cantor Set, Real and Complex 169
7.4 Measuring Instability: The Lyapunov Exponent 199
9 Parametric Plotting of Surfaces 235
4.6 A New View of Pascal s Triangle’
4 Three-Dimensional Graphs
Trang 811.3 Escape Time Algorithms and the Mandelbrot Set 292
13.4 Case Study: Interval Methods for a SIAM Challenge 346
Contents vii
10 Penrose Tiles
Mandelbrot set (by Mark McClure)
11 Complex Dynamics: Julia Sets and the
Trang 916 Check Digits and the Pentagon 423
491
505
20.2 The Influence of the Zeros of Ζ on the Distribution of Primes 512
21.2 Making the Alternating Harmonic Series Disappear 525
19 The Banach-Tarski Paradox
20 The Riemann Zeta Function
Trang 10This book is an example-based introduction to techniques, from elementary to
advanced, of using Mathematica, a revolutionary tool for mathematical computation
and exploration By integrating the basic functions of mathematics with a powerful
and easy-to-use programming language, Mathematica allows us to carry out projects
that would be extremely laborious in traditional programming environments Andthe new developments that began with version 6 — allowing the user to dynami-cally manipulate output using sliders or other controls — add amazing power to the
interface Animations have always been part of Mathematica, but the new design
allows the manipulation of any number of variables, an important enhancement
Mathematica in Action illustrates this power by using demonstrations and
anima-tions, three-dimensional graphics, high-precision number theory computaanima-tions, andsophisticated geometric and symbolic programming to attack a diverse collection ofproblems
It is my hope that this book will serve a mathematical purpose as well, and I haveinterspersed several unusual or complicated examples among others that will bemore familiar Thus the reader may have to deal simultaneously with new mathe-
matics and new Mathematica techniques Rarely is more than undergraduate
mathematics required, however
An underlying theme of the book is that a computational way of looking at amathematical problem or result yields many benefits For example:
Well-chosen computations can shed light on familiar relations and reveal newpatterns
One is forced to think very precisely; gaps in understanding must be eliminated if
Trang 11 One can examine historically important ideas from the varied perspectives
provided by Mathematica, often obtaining new insights.
The reader will find examples of these points throughout the book Here are twospecific cases: Chapter 17 contains a discussion of the four-color theorem that seeks
to turn Kempe's false proof of 1879 into a viable algorithm for four-coloring planargraphs And Chapter 15 shows how a certain published construction in computa-tional geometry — the construction of a three-dimensional room that contains apoint invisible to guards placed at every vertex — must be changed if it is to becorrect
Another point worth mentioning is that a detailed knowledge of some of
Mathemati-ca's internal workings can lead to novel solutions to programming problems As an
example, Chapter 12 shows how an understanding of the data computed byContourPlot can lead to a simple and effective routine for finding all solutions in
a rectangle to a pair of simultaneous transcendental equations
The chapters are written so that browsing is possible, but there is certainly a sion from elementary to advanced techniques, and the novice is encouraged to readthe chapters in order Even advanced users will benefit from a careful reading ofthe first few chapters Chapter 5 is devoted to the Manipulate command, which isused throughout the book The output cannot be appreciated very well on theprinted page and the reader is encouraged to load the files in the electronic supple-ment and work through the demonstrations in an interactive way
progres-From its beginning, twenty years ago, the pleasure and power of using Mathematica
arose from the two somewhat separate features: the kernel and the front end Thekernel does the underlying computations and the front end is the device throughwhich the user communicates with the kernel There has always been some commu-nication between the two, especially after version 3 with its many front end enhance-ments, but the two interfaces had the feel of separate entities With version 6 theconnection between the two became much stronger, as one can create Manipulateoutput that runs on its own All the code in this book has been designed to work inboth versions 6 and 7, with some small exceptions where use has been made offunctions that are new in version 7 All the timings in the book are from a Macin-tosh laptop running a 2.16 gigaHertz Intel chip
There have been important enhancements to the kernel as well Some are minor, buttogether they contribute to making programming smoother, faster, and just morefun A brief sampling: Table and Do commands now accept iterators that vary over
a list, as in Do@this, 8x, 8a, b, c<<D, where x takes on the values a, b, and c;RandomChoice@sD generates a random choice from the list s; Total@sD sums the
Trang 12elements of s; Tally@sD gives the elements of s with their frequencies;ZetaZero@iD gives the ith zero of the Riemann Ζ function Another nifty enhance-
ment is the inclusion of comprehensive databases, some requiring a web connection
to access Thus one can get stock prices, currency exchange rates, and data aboutmany structures in mathematics, physics, chemistry, geography, and even gram-
mar The data can then be integrated into Mathematica programs, thus allowing the user to conveniently analyze or present the data using all of Mathematica's tools This book includes a CD with Mathematica files containing all the code that appears
in the book, and much code that is not in the book In some of the chapters oneneeds to load code from the disk to enable various sophisticated functions
From a personal point view I have to emphasize the huge impact that Mathematica
has had on my teaching and research I have been using the program for almost 20years and it has led to many new ideas at the forefront of research, in a wide variety
of fields Math and science are much more fun when one can visualize concrete
examples of the objects being studied; Mathematica gives us the chance to see even
very abstract constructions, and thus to understand them more deeply
Acknowledgments I am grateful to the many people who have shared with me
their expertise in mathematics and Mathematica Of particular help with this edition
have been several members of the Wolfram Research staff, including: Rob Knapp,Danny Lichtblau, Brett Champion, Ulises Cervantes, Lou D'Andria, Adam Strzebon-ski, Jeff Bryant, and Oleksandr Pavlyk For helpful consultation on technical andstyle issues, I thank Joan Hutchinson, Ellen Gethner, Mark McClure, and Rob Pratt.Mark also contributed Chapter 11 on Julia sets Michael Rogers shared his consider-able knowledge of the subtleties of Manipulate I am grateful to Wayne Hayes(shadowing), Rachel Fewster (Benford's Law), and Matthias Weber (three-dimen-sional surfaces) for sharing their expertise on various points And finally I thank Ed
Packel, with whom I have for fifteen years taught a summer course about
Mathemat-ica in the mountains of Colorado.
Stan Wagon, Macalester College, St Paul, Minnesota
December 2009
Preface xi
Trang 14The image shown is a view of the torus knot known as 83; data for this image, and
physics, chemistry, astronomy, finance, geography, mathematics, and other areas
0 A Brief Introduction
other aspects of the knot, are available through the KnotData command
Mathemat-ica includes many data sets containing useful and easy-to-use information from
Trang 15This chapter contains a brief introduction to the syntax of Mathematica, as well as
diverse front-end techniques Most of the items here are discussed in much moredetail in the main text, but there are a few front-end tips that are mentioned inthis chapter only The last section is an introduction to some of the data sets
available in Mathematica, which allow the user access to data in diverse fields.
The Mathematica kernel accepts input cells and returns output cells During a
session these cells are labeled In[1], Out[1], In[1], and so on In this book we willsuppress these labels, but the input cells are printed in boldface On most front
ends, input cells are evaluated by either the enter key or the shift-return key Note that on Windows computers the enter key on the numeric keypad evaluates while the other enter key does not
Built-in Mathematica objects always begin with capital letters It is good practice for
users to use lowercase letters for their own objects, but one might wish to usecapital letters for functions when writing a comprehensive package
Function arguments are always enclosed by square brackets, @ D Parentheses, HL,are used to group objects together, thus establishing priority of operations Thestandard arithmetic operations are +, -, *, , and ^ A space is interpreted asmultiplication Sometimes even a space is unnecessary: 2a and 2Sin[x] work asexpected, but xy is not the same as x * y Variable names cannot begin with num-bers, but otherwise numbers can occur and there is no restriction on the length of aname One can use typeset input and alternate alphabets Thus one can enter anduse Dx as a single variable
Lists are enclosed by braces, 8< List elements are accessed via double squarebrackets Thus, if x is the list 8a, b, c<, then xP3T (same as x@@3DD) is c Matri-ces are lists of lists (rows) Matrix multiplication and dot products are via the dot:
881, 2<, 83, 4<<.85, 0< is 85, 15< Some of the built-in matrix commands areMatrixPower, Inverse, Transpose, IdentityMatrix, Eigenvalues, andDet
Comments are delimited by H* *L
One can refer to output later on in a Mathematica session by Out@nD or by % n, both
of which refer to the nth output cell The symbol % refers to the previous output
produced; %% refers to the second-previous output, and so on
0.1 Notational Conventions
Trang 16n++ abbreviates n = n + 1; similarly n abbreviates n = n - 1 n += i denotes
n = n + i; similarly for n -= i, n *= i, and n= i
can serve as an abbreviation for @ D Sin Π and Print x abbreviate Sin@ΠDand Print@xD, respectively However, this notation should be used sparingly, as
f x is much less precise than f@xD in terms of scope I use it sometimes whenadding, say, Print x temporarily for debugging a program
Postfix notation is sometimes useful expr f is the same as f@exprD and ismost useful in something like expr Timing or expr Simplify
Iterators occur often, especially in Do loops or when lists are built using the Tablecommand An iterator has the form 8i, n0, n, step< The default step size is 1,and an iterator of the form 8i, 200< abbreviates 8i, 1, 200, 1< One can uselists in iterators, such as Table@Prime@iD, 8i, 810, 100, 1000<<D, which
causes i to run through the list of three numbers.
There are three usages of the equal sign An ordinary assignment of one value to avariable is done via, for example, a = 3; one can also use 8a, b< = 83, 7<, forexample, to handle two or more assignments A delayed assignment is identified by:=; f := x2 means that whenever f is called it will be replaced by x2 for the value
of x at the time of the call This is most often used in the definition of functions viadummy variables, as in f@t_D := t2; the underscore (blank) indicates that t is anobject that should take on the value of expr whenever f@exprD is encountered, so
f@exprD will always turn into expr2 for any value of expr; in short, t can bethought of as a dummy variable Finally, equality is denoted by in an equationsuch as SolveAx5+x 7, xE or If@n 100, …D)
The front end has hundreds of features, and we will not go into all of them here.But the ability to use typeset mathematics for input and output is very important, sohere is a brief introduction For more on other aspects of the front end, such asbuttons and palettes, see [GG]
There are three main forms for mathematical expressions: InputForm, Form, and TraditionalForm InputForm is the character-based, single-lineformat that is familiar to users of early versions For example, an integral would begiven as Integrate@Sin@Sqrt@xDD Cos@xD, 8x, 0, 1<D StandardForm
Standard-is a typeset form that differs from traditional mathematics typesetting in that thereare no ambiguities
0.2 Typesetting 3
0.2 Typesetting
Trang 17An integral would look like Ù01 SinB x F
Cos@xD âx TraditionalForm is an attempt tomatch traditional mathematical notation, and an integral would look like
follow-output are both in StandardForm The following table shows how certain sions look in all three formats
Product@x + i, 8i, 1, 4<D Ûi=14 Hx + iL Ûi=41Hi + xL
LogIntegral@Log@xD Sqrt@xDD LogIntegralBLog@xD
Trang 18Pi (Π), I (ä ), Infinity (¥), E (ã), EulerGamma, and GoldenRatio are built-inconstants To turn a symbolic value into a numeric one, use N@D For example, N@ΠDreturns 3.141592653589793 (though only six digits are displayed) N@x, dD returns
d significant digits Degree, the radian value of 1°, is also built-in Thus N@i °Dreturns the value of i°in radians Note that typeset forms may be used here too Forexample, Sin@41.3 °D works where the degree symbol can be entered by
! has several uses (e.g., logical negation), but immediately following an integer it
refers to the factorial of that number (and following any number z it gives G@z + 1D).
Some of the two-dimensional plotting commands are Plot, ListPlot, LinePlot, LogPlot, ParametricPlot, ContourPlot, and DensityPlot Inthree dimensions we have Plot3D, ParametricPlot3D, and ListPlot3D
List-0.3 Basic Mathematical Functions 5
0.3 Basic Mathematical Functions
Trang 19This logical connectives are && (And, ß), ÈÈ (Or, Þ), ! (Not, Ø), and Xor (exclusiveor) Logical constants are True and False.
And there are hundreds of built-in mathematical functions Here is a sampling
Trang 20This section briefly presents some advanced techniques for using functions that will
be useful to anyone writing programs in Mathematica Although we sometimes fail
to make the distinctions, there are several ways in which functions are traditionallyused in mathematics We can apply a function to one or more arguments in the
traditional way [ f(x) or f(x, y)] We can map a function of, say, one variable onto each element of a set to form {f(x) : x Î X} We can also apply a function of, say, two
variables to a single set consisting of a two-element list, where the elements of the
list are to be treated as arguments; that is, we can interpret f({x, y}) as f(x, y).
Mathematica has the means to perform all these types of transformations, as well as
several higher-level forms
The following all return f(x): f@xD, f x, x f The first form is the traditional
notation, the second avoids the buildup of brackets, and the third is useful for quicktyping, as in expr Simplify Another way to reduce brackets is to use ~f~ for
a function of two variables, as follows
The set-image {f(x) : x Î X< is called mapping in Mathematica: Map@f, XD returns
the set consisting of the f-values applied to the elements of X
Map@f, 81, 2, 3<D
8f@1D, f@2D, f@3D<
This usage is very common and has the abbreviation f x
Built-in functions that work on numbers have an attribute called Listable Thismeans that, when applied to a list, they automatically move inside the list ThusSqrt@89, 16, 25<D is the same as Map@Sqrt, 89, 16, 25<D
89, 16, 25<
83, 4, 5<
0.4 Using Functions 7
0.4 Using Functions
Trang 21The Listable attribute can be added to a user-defined function as follows In theexample that follows, the attribute makes a big difference The SmallestDivisorfunction picks out the smallest nontrivial divisor of an integer.
Attributes@DivisorsD = 8Listable, Protected<
Options @DivisorsD = 8GaussianIntegers ® False<
Using ?Divisors gets the usage message only
To apply a function to a list so that the list elements are arguments, one uses Apply.Apply@Plus, 8x, y<D returns Plus@x, yD, which is just x + y An abbreviationfor Apply@f, XD is f X
Trang 22Apply typically applies the function to the 0th level, in the sense that it replaces thehead of the expression with the function being applied In the next example, weapply to the first level.
Outer@f, 8a, b, c, d<, 8e, f<D
88f@a, eD, f@a, fD<, 8f@b, eD, f@b, fD<,
Trang 23880, 0, 0<, 80, 0, 1<, 80, 1, 0<, 80, 1, 1<,
81, 0, 0<, 81, 0, 1<, 81, 1, 0<, 81, 1, 1<<
Distribute is much the same as Outer but often a little faster Its default mode is
to distribute a function over occurrences of Plus
Since the full form of 8x, y< is List@x, yD, we can use the following bit of code
to get all sequences of 0s and 1s
translit-Outer@StringJoin, 8"Ceb", "Tscheb", "Tcheb", "Cheb"<,
8"y", "i"<, 8"schef", "cev", "cheff", "scheff", "shev"<D
888Cebyschef, Cebycev, Cebycheff, Cebyscheff, Cebyshev<,
8Cebischef, Cebicev, Cebicheff, Cebischeff, Cebishev<<,
88Tschebyschef, Tschebycev, Tschebycheff, Tschebyscheff,
Tschebyshev<, 8Tschebischef, Tschebicev,
Tschebicheff, Tschebischeff, Tschebishev<<,
88Tchebyschef, Tchebycev, Tchebycheff, Tchebyscheff, Tchebyshev<,8Tchebischef, Tchebicev, Tchebicheff, Tchebischeff, Tchebishev<<,88Chebyschef, Chebycev, Chebycheff, Chebyscheff, Chebyshev<,
8Chebischef, Chebicev, Chebicheff, Chebischeff, Chebishev<<<
Another important way of using a function is to iterate it Traditional programlanguages use Do-loops, as follows
y = x;
y
Trang 24result of iterating the infamous Collatz function, also known as the 3 x + 1 function.
Because the fixed point occurs when we look at every third entry, we defineCollatz3 to iterate three times, and then find a fixed point of that
One can use these ideas to implement Newton's method to find 2 ; one needs to
iterate the function x # 12Jx + 2xN, which can be done as follows
But it is much more efficient to use what is called a pure function In Mathematica the
pound symbol, ð, is used as the generic variable in such a construction, with anampersand, &, indicating that the object is to be viewed as a function One can justapply such a function to an argument as follows
0.4 Using Functions 11
Trang 25used to define a polynomial, it will not work Mathematica allows us to give x
specific values without a permanent assignment by using replacement rules The
in the following line stands for Replace, and the rule that follows it has the effect
of replacing x by 2
10
When one solves an equation, including differential equations, the result is given as
a set of replacement rules
0.5 Replacements
Trang 26most common way to generate a list is by using the Table command.
TableAx i , 8i, 1, 8<E
9x, x2, x3, x4, x5, x6, x7, x8=
When one wishes to create an array of function values, Array can be used
Array@Sin, 5D
8Sin@1D, Sin@2D, Sin@3D, Sin@4D, Sin@5D<
If the function accepts two variables, then a doubly indexed array can be generated
Trang 28Function names in Mathematica are very descriptive and therefore easy to
remem-ber But long names can be bothersome to type Typing, and possible typing errors,can be avoided by the very useful command completion feature (Edit >> CompleteSelection menu item) Typing Plot followed by í-K (on a Macintosh; use â-K on
a PC) causes a list of all the commands beginning with Plot to pop up TypingPlotJ and then í-K causes PlotJoined to be typed at the insertion point User-defined symbols also show up in these lists Another very useful shortcut is í-L (orâ-L), which causes the input cell preceding the cursor to be duplicated at thecursor, thus allowing convenient editing of code without losing the previousversion Note also the useful spell-checker in the Edit >> Check Spelling menu item
A usage message is a brief explanation of how a built-in function works One cansee such a message by simply typing, for example, ? ParametricPlot
?ParametricPlot
A9 f x f y = 8u u min u max<E
A99 f x f y = 9g x g y = …= 8u u min u max<E
A9 f x f y = 8u u min u max < 8v v min v max<E
A99 f x f y = 9g x g y = …= 8u u min u max < 8v v min v max<E
Clicking on the >> at the end of the message brings up the Documentation Centerwindow that contains much more information about the function
Users should occasionally use FullForm to find out Mathematica's internal
repre-sentation of various expressions The following yields no surprises
Power@a, Rational@-1, 2DD
The standard packages that come with Mathematica (a list can be found by using the
0.7 Getting Information 15
0.7 Getting Information
Trang 29link in the lower right of the main Documentation Center window) contain dreds of useful functions Their usage messages will show up only after the package
hun-is loaded Here hun-is an example involving the convex hull of a set of points in theplane
One can load a package by calling for the context appropriate for that package
Mathematica then translates the context into a file name appropriate for the
operat-ing system and loads that file Contexts are stroperat-ings endoperat-ing in ` that refer to the fullnames given to variables within a package; for example, the full name ofConvexHull is ComputationalGeometry`ConvexHull
inter-Some evaluation points: one can evaluate an expression in place within a text orinput cell by selecting it and hitting í-return (â-shift-enter on a PC); this is theEvaluation >> Evaluate in Place menu item This menu list also has the sometimesnecessary Abort Evaluation command
Trang 30The documentation includes many tutorials that contain a wealth of information onhow to use some advanced features Some that I have found useful are:
• ConstrainedOptimizationOverview, for its discussion of NMinimize and bal optimization;
glo-• GraphDrawing, for its discussion of GraphPlot, which generates drawings
of graphs and trees, in two and three dimensions;
• LinearAlgebraMatrixComputations, for the discussion of the Krylov method
to iteratively solve a large sparse linear system;
• IntroductionToManipulate, IntroductionToDynamic, and cFunctionality for an appreciation of the subtleties of dynamic evaluation
AdvancedDynami-Links to such tutorials are given at the end of the documentation of the relevantfunctions, or one can just enter the tutorial name in the documentation search box
Of course, one often wishes to destroy information, such as when a value isassigned to a symbol that is to be used as a pure symbol, or redefined in some way.One can always quit the kernel, but usually Clear@xD or Remove@fD will suffice.Throughout this book variables are set to values that might have to be cleared asone moves to a new topic
Here is a sampling of some functions available for algebraic manipulation
Trang 32>> Initialization Cell menu item), then at the time of first evaluation of any input, adialog box will appear asking the user if he or she wishes the initialization cells to
be evaluated Since it is reasonable to have the initialization cells evaluate withoutthe warning, I set this as a global default by changing, at the global level, theInitializationCellEvaluation option to True and set Initialization-CellWarning to False
The preceding discussion concerns the front end and its defaults One can also setkernel defaults by placing some code in a file called init.m, which can be placed inthe kernel folder within the path given by the output of $BaseDirectory Thecode in this file should be in an initialization cell If one uses a certain package a lot,one might place a command to load that package in such a file Another approach is
to place something like the following in the init.m file
DeclarePackage@"ComputationalGeometry`", "ConvexHull"D;
This means that whenever the function ConvexHull is called, the package will beloaded first; but unlike code that loads the package directly, this approach does notload the package unless the function is used, saving time and memory
Versions 6 and 7 of Mathematica includes an impressive number of data sets, some
of which are described in later chapters The documentation on these is quite good,
so we will refer the reader to that to see how to use these varied sets But it isremarkable that a single piece of software allows one to get current stock prices orexchange rates, the length of paved roads in India, the population of any of over one
0.9 Customizing Mathematica 19
Trang 33hundred thousand cities, various pieces of information about knots, graphs, lattices,
or polyhedra, the collection of English words beginning with "sw", and much, muchmore Some of these data sets do require Internet access as the kernel must communi-cate with various data servers maintained by Wolfram Research
Here is a list of the data sets:
• Science: AstronomicalData, ChemicalData, ElementData,
IsotopeData, ParticleData, ProteinData, GenomeData,
WeatherData
• Mathematics: GraphData, KnotData, LatticeData, PolyhedronData, FiniteGroupData
• Geography: CountryData, CityData, GeodesyData
• Miscellaneous: ColorData, FinancialData, WordData
The amount of data in these collections is gigantic To learn more, evaluate ? *Dataand click on the desired data set Here is how to see the shape of the electricaloutlets in India
Trang 34The definition of mathematics:
WordData@"mathematics", "Definitions"D
88mathematics, Noun< ®
the logic of quantity and shape and arrangement<
The 10 most popular city-names in the world
Take@SortBy@Tally@First CityData@DD, LastD, -10D
88Georgetown, 27<, 8SanAntonio, 27<, 8SanFrancisco, 27<,
8Washington, 27<, 8Clinton, 28<, 8Franklin, 28<,
8Salem, 28<, 8SanJose, 28<, 8SanMiguel, 28<, 8SantaCruz, 28<<
Here are all the city names that appear in both France and Italy This example isinspired by the graph in the Neat Examples section of the documentation forCityData that connects countries if they share more than 50 city names Franceand Italy are connected, though I could not think of even one city name common toboth Here is a list of all 57 of them
HFirst CityData@8All, "France"<DL Ý
HFirst CityData@8All, "Italy"<DL
8Albi, Ales, Arbus, Arre, Arzano, Bard, Bono, Boves, Brusson, Calvi,Campana, Castellar, Chatillon, Cologne, Corbara, Denice, Dolo, Don,Ferrere, Force, Gavignano, Laives, LaMagdeleine, LaSalle, LaThuile,Magenta, Male, Marcon, Melle, Mello, Montagne, Pau, Penne, Pigna,PontSaintMartin, Pray, Racines, Rogliano, Roure, SaintChristophe,SaintDenis, SaintMarcel, SaintNicolas, SaintOyen, SaintPierre,
SaintVincent, Saliceto, SanLorenzo, Solaro, Solferino, Stazzona,Traves, Treville, Vescovato, Viggianello, Villeneuve, Villette<
Here are more details for one of them
CityData @"Magenta"D
88Magenta, Lombardy, Italy<, 8Magenta, ChampagneArdenne, France<<
Mathematica can provide web links to maps for these two cities.
CityData@8"Magenta", "Lombardy", "Italy"<, "LocationLink"D
CityData@8"Magenta", "ChampagneArdenne", "France"<, "LocationLink"D
http:maps.google.commaps?q=+45.47+8.87&z=12&t=h
http:maps.google.commaps?q=+49.05+3.97&z=12&t=h
0.10 Comprehensive Data Sets in Mathematica 21
Trang 35There is also much useful data in the standard packages
8Blue, Specularity@Green, 70D, KnotData@88, 3<, "ImageData"D<,
And its Alexander polynomial
9 - 4
x-4 x
Trang 36Placing wheels on wheels on wheels and giving them different rates of spin leads tosome interesting parametric plots The images show four examples They arise fromthe values below, clockwise from upper left, as explained in §1.7.
Trang 37This chapter provides an introduction to the fundamental two-dimensional
plotting functions of Mathematica As often happens, even these simple functions
can lead to interesting observations about familiar mathematical constructions.Animations can be enlightening and the chapter includes an introduction to thegeneration of animations using Manipulate
The basic plotting command, Plot, is simple to use
Plot@3 Cos@xD + 2 Cos@2 xD + Cos@3 xD, 8x, -3 Π, 3 Π<D
As with all Mathematica commands, the output can be highly customized by using
options The great benefit of the option method is that the order in which theoptions are placed does not matter There are many options to Plot; here are theirnames The output below uses boldface for the ones that I feel every user shouldlearn about
Options@PlotDPAll, 1T
8AlignmentPoint, AspectRatio, Axes, AxesLabel, AxesOrigin,
AxesStyle, Background, BaselinePosition, BaseStyle,
ClippingStyle, ColorFunction, ColorFunctionScaling, ColorOutput,ContentSelectable, DefaultAxesStyle, DefaultBaseStyle,
DefaultFrameStyle, DefaultLabelStyle, DisplayFunction, Epilog, Evaluated, EvaluationMonitor, Exclusions, ExclusionsStyle,
Filling, FillingStyle, FormatType, Frame, FrameLabel, FrameStyle, FrameTicks, FrameTicksStyle, GridLines, GridLinesStyle,
ImageMargins, ImagePadding, ImageSize, LabelStyle,
MaxRecursion, Mesh, MeshFunctions, MeshShading, MeshStyle,
Method, PerformanceGoal, PlotLabel, PlotPoints, PlotRange,
PlotRangeClipping, PlotRangePadding, PlotRegion, PlotStyle, Prolog,
RegionFunction, RotateLabel, Ticks, TicksStyle, WorkingPrecision<Several of these will be discussed here, but for more information on any of them,start with the usage message, as follows
?PlotRange
_2
2 4 61.1 Plot
Trang 38Plot uses several internal algorithms that one should become familiar with First ofall, Plot tries to determine the region of visual interest and restrict the plottingrange to that region This can be overridden by setting PlotRange to All or to aspecific interval for the vertical range (and also the horizontal range if desired).One can also control the location of the axes origin, label the axes, and so on When
a Thickness setting is used, the parameter refers to the proportion of the tal span, and so it changes when the image is expanded
The default aspect ratio is the reciprocal of the golden ratio Often one wants anaspect ratio that yields visual equality in the scales on the two axes That is done asfollows; without the last option the graph would appear to be an ellipse Note that
in this example we plot two functions
1.0
Trang 39The axes often interfere with a clear view of the graph While one can move them
by using the AxesOrigin option, it is usually better to remove the axes entirelyand add a frame In the example that follows we do this, and we also use the Πcharacter to get the Greek letter in the tick marks To get the Π on screen, type å p
å (or click on Π in the BasicMathInput palette) Note that Thick can be used as
a style, but it is an absolute setting, and does not change as the graphic is resized.The syntax of FrameTicks was changed in version 6 from {bottom, left, top, right}
to 88left, right<, 8bottom, top<<; both work
8x, -3 Π, 3 Π<, PlotRange ® 8-4, 7<, Frame ® True,
Frames are so nice that we now make them the default for all the plotting functions
we will discuss in the rest of this chapter, and also change some styles
SetOptions@8Plot, ListPlot, ParametricPlot, PolarPlot, ListLinePlot<, Frame ® True, Axes ® None,
It is often convenient to define the function one is interested in, and that is donesimply as follows
f@x_D := Sin@xD + ArcSin@xD
The syntax here is as follows: x_ means that f can apply to anything, which will begiven the temporary name x The := means that this is a delayed assignment, andthe right side is not to be looked at until f is actually called It is natural to wonderwhether something like f@x_D = x + 3 would work
Trang 40Sometimes it would, but if x had a prior assignment to, say, 17, then f would return
20 for all values of its argument The reason is that the = takes effect immediately, so
the rule becomes, essentially, f@anythingD = 20. So always use delayedassignments when defining functions (and don't use them when a simpleassignment, such as a = 5, will do)
Now here is a very simple plot: the sum of sine and arcsine
Plot@f@xD, 8x, -0.8, 0.8<,
This is surely too simple! Is it correct? Can the graph of this function really be just astraight line? Of course not, as a plot from -1 to 1 will show But it is remarkablehow straight the graph is between -0.8 and 0.8 This example, which was pointedout to me by John Schue, becomes much clearer if we examine the Taylor series ofthe function being graphed The next graph shows the full domain; Epilog andText have been used to add text in a specific size
Plot@f@xD, 8x, -1, 1<,
Epilog ® Text@Style@"Curvy!", FontSize ® 16D, 80.6, 2.<DD
And here is the Taylor series about 0 The 0 indicates that the series is centeredabout 0 (such series are often called Maclaurin series) and the 14 specifies thehighest power sought