An introduction to programming with Mathematica 3rd Edition Paul R. Wellin 2024 scribd download
An introduction to programming with Mathematica 3rd Edition Paul R. Wellin 2024 scribd download
https://ebookfinal.com/download/programming-with-mathematica-4th-
revised-edition-edition-paul-wellin/
https://ebookfinal.com/download/an-introduction-to-network-
programming-with-java-1st-edition-jan-graba/
https://ebookfinal.com/download/an-introduction-to-bootstrap-methods-
with-applications-to-r-1st-edition-michael-r-chernick/
https://ebookfinal.com/download/practical-programming-an-introduction-
to-computer-science-using-python-3-second-edition-paul-gries/
Introduction to the mathematics of operations research
with Mathematica 2. ed Edition Hastings
https://ebookfinal.com/download/introduction-to-the-mathematics-of-
operations-research-with-mathematica-2-ed-edition-hastings/
https://ebookfinal.com/download/observation-and-experiment-an-
introduction-to-causal-inference-1st-edition-paul-r-rosenbaum/
https://ebookfinal.com/download/simply-java-an-introduction-to-java-
programming-programming-series-1st-edition-james-levenick/
https://ebookfinal.com/download/matlab-an-introduction-with-
applications-3rd-edition-amos-gilat/
https://ebookfinal.com/download/an-introduction-to-stata-
programming-2nd-edition-christopher-f-baum/
An introduction to programming with Mathematica 3rd
Edition Paul R. Wellin Digital Instant Download
Author(s): Paul R. Wellin, Richard J. Gaylord, Samuel N. Kamin
ISBN(s): 9780521846783, 0521846781
Edition: 3
File Details: PDF, 6.48 MB
Year: 2005
Language: english
This page intentionally left blank
An Introduction to Programming with Mathematica
r
Wolfram Research is the holder of the copyright to the Mathematica software system
described in this document, including without limitation such aspects of the system as
its code, structure, sequence, organization, “look and feel”, programming language, and
compilation of command names. Use of the system unless pursuant to the terms of a
license granted by Wolfram Research or an otherwise authorized by law is an
infringement of the copyright.
1 An introduction to Mathematica
Numerical computations
Mathematica has been aptly described as a sophisticated calculator. With it you can enter
mathematical expressions and compute their values.
12
.08
In[1]:= Sin .86 Log 1
12
Out[1]= 0.481899
In[4]:= heat 83
Out[4]= 83
2 An Introduction to Programming with Mathematica
Yet Mathematica differs from calculators and simple computer programs in its ability to
calculate exact results and to compute to an arbitrary degree of precision.
1 1 1
In[6]:=
15 35 63
1
Out[6]=
9
In[7]:= 2500
Out[7]= 3273390607896141870013189696827599152216642046043064789483291
368096133796404674554883270092325904157150886684127560071009
217256545885393053328527589376
In[8]:= N , 500
Out[8]= 3.14159265358979323846264338327950288419716939937510582097494
459230781640628620899862803482534211706798214808651328230664
709384460955058223172535940812848111745028410270193852110555
964462294895493038196442881097566593344612847564823378678316
527120190914564856692346034861045432664821339360726024914127
372458700660631558817488152092096282925409171536436789259036
001133053054882046652138414695194151160943305727036575959195
309218611738193261179310511854807446237996274956735188575272
48912279381830119491
Symbolic computations
One of the more powerful features of Mathematica is its ability to manipulate and compute
with symbolic expressions. For example, you can factor polynomials and simplify trigono-
metric expressions.
In[9]:= Factor x5 1
Out[9]= 1 x 1 x x2 x3 x4
3
In[10]:= TrigReduce Sin
1
Out[10]= 3 Sin Sin 3
4
1 An introduction to Mathematica 3
You can simplify expressions using assumptions about variables contained in those expres-
sions. For example, if k is assumed to be an integer, sin 2 k x simplifies to sin x .
In[11]:= Simplify Sin 2 k x ,k Integers
Out[11]= Sin x
This computes the conditions for which a general quadratic polynomial will have both
roots equal to each other.
In[12]:= Reduce x,a x2 b x c 0 y,a y2 b y c 0 x y , a, b, c
b2
Out[12]= a 0 && b 0 a 0 && b c 0 a 0 && c
4a
The knowledge base of Mathematica includes algorithms for solving polynomial equations,
and computing integrals.
In[14]:= Solve x3 ax 1 0, x
1 3 1 3
2
3
a 9 3 27 4 a3
Out[14]= x 1 3
,
9 3 27 4 a3 21 3 32 3
1 3 a
x 1 3
22 3 31 3 9 3 27 4 a3
1 3
1 3 9 3 27 4 a3
,
2 21 3 32 3
1 3 a
x 1 3
22 3 31 3 9 3 27 4 a3
1 3
1 3 9 3 27 4 a3
2 21 3 32 3
1
In[15]:= x
1 x4
1
Out[15]= 2 ArcTan 1 2 x 2 ArcTan 1 2 x
4 2
Log 1 2 x x2 Log 1 2 x x2
4 An Introduction to Programming with Mathematica
Graphics
The ability to visualize functions or sets of data often allows us greater insight into their
structure and properties. Mathematica provides a wide range of graphing capabilities.
These include two- and three-dimensional plots of functions or data sets, contour and
density plots of functions of two variables, bar charts, histograms and pie charts of data
sets, and many packages designed for specific graphical purposes. In addition, the Mathemat-
ica programming language allows you to construct graphical images “from the ground up”
using primitive elements, as we will see in Chapter 9.
Here is a simple two-dimensional plot of the function sin x 2 sin x2 .
0.5
3 2 1 1 2 3
0.5
Out[16]= Graphics
You can combine two or more plots in a single graphic by enclosing them inside curly
braces.
In[17]:= Plot Sin x , Sin 2 x , x, 0, 2 ;
1
0.5
1 2 3 4 5 6
0.5
1
1 An introduction to Mathematica 5
0.8
0.6
0.4
0.2
6 4 2 2 4 6
0.2
You can immediately plot the data using the ListPlot function.
In[25]:= ListPlot data, PlotStyle PointSize .02 ;
17500
15000
12500
10000
7500
5000
2500
2 2 4 6 8
You can then fit a straight line to the log-data by performing a linear least squares fit. In
this example, we are fitting to the model a m x, where a and m are the parameters to be
determined in the model with variable x.
In[27]:= f FindFit Log data , a m x, a, m , x
Out[27]= a 4.15437, m 0.761465
10
2 2 4 6 8
8 An Introduction to Programming with Mathematica
Finally, you can see how well the fitted function approximates the log plot by combining
these last two graphics.
In[29]:= Show fplot, logplot ;
10
2 2 4 6 8
Programming
With a copy of The Mathematica Book (Wolfram 2003) or one of the many tutorial books
(see, for example, Glynn and Gray 1999) describing the vast array of computational tasks
that can be performed with Mathematica, it would seem you can compute just about
anything you might want. But that impression is mistaken. There are simply more kinds of
calculations than could possibly be included in a single program. Whether you are inter-
ested in computing bowling scores or finding the mean square distance of a random walk
on a torus, Mathematica does not have a built-in function to do everything that a user could
possibly want. What it does have – and what really makes it the amazingly useful tool it is –
is the capability for users to define their own functions. This is called programming, and it
is what this book is all about.
Sometimes, the programs you create will be succinct and focused on a very specific
task. Mathematica possesses a rich set of tools that enable you to quickly and naturally
translate the statement of a problem into a program. For example, the following program
defines a test for perfect numbers, numbers that are equal to the sum of their proper
divisors.
In[30]:= PerfectQ n_ : Apply Plus, Divisors n 2n
We then define another function that selects those numbers from a range of integers that
pass this PerfectQ test.
In[31]:= PerfectSearch n_ : Select Range n , PerfectQ
1 An introduction to Mathematica 9
Here are two functions for representing regular polygons. The first defines the
vertices of a regular n-gon, while the second uses those vertices to create a polygon graph-
ics object that can then be displayed with the built-in Show function.
In[33]:= vertices n_Integer, r_: 1 :
2 2
Table r Cos , r Sin , , 0, n 1
n n
In[34]:= RegularPolygon n_ :
Graphics Line vertices n . a_, b__ a, b, a ,
AspectRatio Automatic
Out[35]= Graphics
In[37]:= g x_ : x3 2 x2 1
Of course, sometimes the task at hand requires a more involved program, stretching
across several lines (or even pages) of code. For example, here is a slightly longer program
to compute the score of a game of bowling, given a list of the number of pins scored by
each ball.
10 An Introduction to Programming with Mathematica
Out[42]= Graphics3D
Here is a short program that creates a button containing the above two expressions.
Cell[BoxData[
ButtonBox[
RowBox[{"Stellate", " ", "Icosahedron"}],
ButtonFunction:>CompoundExpression[
Needs[ "Graphics`Polyhedra`"],
Show[Stellate[Polyhedron[Icosahedron]]]
],
ButtonEvaluator->Automatic],
"Input",
Active->True]
The formatted version of the above cell can be displayed by choosing Show Expression
from the Format menu. When you do that, it will look like the following:
Stellate Icosahedron
Clicking the button will cause the Mathematica code in the ButtonFunction to be
immediately evaluated and the following graphics will then be displayed in your notebook.
Functions are available to jump around to different parts of a Mathematica notebook
and perform various actions. Here is a short piece of code that creates a button which,
upon being clicked, moves the selection to the next cell and then evaluates that cell.
12 An Introduction to Programming with Mathematica
Cell[TextData[{
Cell[BoxData[
ButtonBox["EVALUATE",
ButtonFunction:>FrontEndExecute[ {
FrontEnd`SelectionMove[
ButtonNotebook[ ], All, ButtonCell],
FrontEnd`SelectionMove[
ButtonNotebook[ ], Next, Cell],
FrontEnd`SelectionEvaluate[
ButtonNotebook[ ]]}],
Active->True]]],
StyleBox[" MATHEMATICA INPUT"]
}], "Text"]
The formatted version of the above cell can be displayed by choosing Show Expression
from the Format menu. When you do that, it will look somewhat like the following
(although we have removed some of the text formatting above to improve readability of the
code). Clicking the EVALUATE button will cause the input cell immediately following to
be selected and then evaluated.
In[43]:= 3 4 5
Out[43]= 27
The following example demonstrates how you can use Mathematica functions to
perform some of the user interface actions that you would normally associate with key-
board and mouse events. By using such techniques, you can create a specific set of actions
that will follow certain evaluations. For example, if you were creating an electronic quiz for
your students, you could include “hint” buttons within your class notebooks that would
open a new notebook with hints and suggestions upon clicking.
This creates a new notebook that contains three cells – a Section cell, a Text cell,
and an Input cell. Upon evaluation, the NotebookPut command below will cause a new
notebook to appear, containing the three specified cells. The screen shots below show
what appears in the user interface after evaluating each of the preceding inputs.
1 An introduction to Mathematica 13
In[44]:= nb NotebookPut
Notebook
Cell "Symbolic and Interactive Documents", "Section" ,
Cell "Cells and notebooks are Mathematica expressions.",
"Text" ,
Cell "Integrate Sin x Cos x ,x ", "Input"
This moves the selection bar past the last cell in the above notebook.
In[45]:= SelectionMove nb, Next, Cell, 4
14 An Introduction to Programming with Mathematica
In Chapter 10 we will give a detailed discussion of how to modify and manipulate the
user interface through the use of the symbolic programming techniques that are discussed
throughout this book.
1 An introduction to Mathematica 15
The computer will then load parts of Mathematica into its memory and soon a blank
window will appear on the screen. This window is the visual interface to a Mathematica
notebook and it has many features that are useful to the user.
Notebooks allow you to write text, perform computations, write and run programs,
and create graphics all in one document. Notebooks also have many of the features of
common word processors, so those familiar with word processing will find the notebook
interface easy to learn. In addition, the notebook provides features for outlining material
which you may find useful for giving talks and demonstrations.
16 An Introduction to Programming with Mathematica
When a blank notebook first appears on the screen (either from just starting Mathe-
matica or from selecting New in the File menu), you can start typing immediately. For
example, if you type N[Pi,200] press (hold down the Shift key while pressing
the Enter key) to evaluate an expression. Mathematica will evaluate the result and print the
200-decimal digit approximation to on the screen.
Notice that when you evaluate an expression in a notebook, Mathematica adds input
and output prompts. In the example notebook above, these are denoted In[1]:= and
Out[1]=. These prompts can be thought of as markers (or labels) that you can refer to
during your Mathematica session.
1 An introduction to Mathematica 17
You should also note that when you started typing Mathematica placed a bracket on
the far right side of the window that enclosed the cell that you were working in. These cell
brackets are helpful for organizational purposes within the notebook. Double-clicking on
cell brackets will open any collapsed cells, or close any open cells as can be seen in the
previous screen shot.
Double-clicking on the cell bracket containing the 1.1 A Brief Overview of Mathe-
matica cell will open the cell to display its contents:
Using cell brackets in this manner allows you to organize your work in an orderly
manner, as well as to outline material. For a complete description of cell brackets and
many other interface features, you should consult the documentation that came with your
version of Mathematica.
For information on other features such as saving, printing, and editing notebooks,
consult the manuals that came with your version of Mathematica.
Entering input
New input can be entered whenever there is a horizontal line that runs across the width of
the notebook. If one is not present where you wish to place an input cell, move the cursor
up and down until it changes to a horizontal bar and then click the mouse once. A horizon-
tal line should now appear across the width of the window. You can immediately start
typing and an input cell will be created.
18 An Introduction to Programming with Mathematica
Input can be entered exactly as it appears in this book. To get Mathematica to evalu-
ate an expression that you have entered, press - ; that is, hold down the Shift key
and then press the Enter key.
You can enter mathematical expressions in a traditional looking two-dimensional
format using either palettes for quick entry of template expressions, or keyboard equiva-
lents. For example, the following expression can be entered by using the Basic Input
palette, or through a series of keystrokes. For details of inputting mathematical expres-
sions, read your user documentation or read the section on 2D Expression Input in the
Help Browser.
1
In[1]:= x
1 x3
1 2x
ArcTan 1 1
3
Out[1]= Log 1 x Log 1 x x2
3 3 6
As noted previously, Mathematica enters the In and Out prompts for you. You do
not type these prompts. You will see them after you evaluate your input.
You can refer to the result of the previous calculation using the symbol %.
In[2]:= 264
Out[2]= 18446744073709551616
In[3]:= % 1
Out[3]= 18446744073709551617
You can also refer to the result of any earlier calculation using its Out[i] label or,
equivalently, %i.
In[4]:= Out 1
1 2x
ArcTan 1 1
3
Out[4]= Log 1 x Log 1 x x2
3 3 6
In[5]:= %2
Out[5]= 18446744073709551616
• Macintosh: type . (the Command key and the period) and then type a
These attempts to stop the computation will sometimes fail. If after waiting a reason-
able amount of time (say, a few minutes), Mathematica still seems to be stuck, you will have
to “kill the kernel.” (Before attempting to kill the kernel, try to convince yourself that the
computation is really in a loop from which it will not return and that it is not just an
intensive computation that requires a lot of time.) Killing the kernel is accomplished by
selecting Quit Kernel from the Kernel menu. The kernel can then be restarted without
killing the front end by first selecting Start Kernel Local under the Kernel menu, or you
can simply evaluate a command in a notebook and a new kernel should start up
automatically.
Alternately, you can enter this expression in the traditional form by typing 39, / , then
13.
39
In[7]:=
13
Out[7]= 3
You can enter this expression in a more traditional typeset form by typing 2, ^ , and
then 5.
In[9]:= 25
Out[9]= 32
x SqrtBox x 2, x
x y GreaterEqual x, y x ,y
You can indicate multiplication by simply putting a space between the two factors, as
in mathematics. You can also use the asterisk (*) for that purpose, as is traditional in most
computer languages.
In[10]:= 25
Out[10]= 10
In[11]:= 2 5
Out[11]= 10
Functions are also written as they are in mathematics books, except that function
names are capitalized and their arguments are enclosed in square brackets.
In[13]:= Factor x5 1
Out[13]= 1 x 1 x x2 x3 x4
Almost all of the built-in functions are spelled out in full, as in the above example.
The exceptions to this rule are well-known abbreviations such as D for differentiation,
Sqrt for square roots, Log for logarithms, and Det for the determinant of a matrix.
Spelling out the name of a function in full is quite useful when you are not sure whether a
function exists to perform a particular task. For example, if we wanted to compute the
conjugate of a complex number, an educated guess would be:
In[14]:= Conjugate 3 4
Out[14]= 3 4
Whereas square brackets [ and ] are used to enclose the arguments to functions,
curly braces { and } are used to indicate a list or range of values. Lists are a basic data type
in Mathematica and are used to represent vectors and matrices (and tensors of any dimen-
sion), as well as additional arguments to functions such as in Plot and Integrate.
In[15]:= a, b, c . x, y, z
Out[15]= ax by cz
0.5
6 4 2 2 4 6
0.5
In the Plot example, the list {x,-2 ,2 } indicates that the function
sin x 2 sin x is to be plotted over an interval as x takes on values from 2 to 2 .
The Integrate expression above is equivalent to the mathematical expression
b
a
cos x x.
22 An Introduction to Programming with Mathematica
%
In[20]:=
Length nums
10001
Out[20]=
2
An expression can be entered on multiple lines, but only if Mathematica can tell that
it is not finished after the first line. For example, you can enter 3* on one line and 4 on the
next.
In[21]:= 3 *
4
Out[21]= 12
But you cannot enter 3 on the first line and *4 on the second.
In[22]:= 3
*4
Out[22]= 3
With the notebook interface, you can input as many lines as you like within an input
cell; Mathematica will evaluate them all when you enter still obeying the rules
stated above for any incomplete lines.
1 An introduction to Mathematica 23
Finally, you can enter a comment – some words that are not evaluated – by entering
the words between (* and *).
In[24]:= D[Sin[x], (* differentiate Sin[x] *)
{x, 1}] (* with respect to x once *)
Out[24]= Cos x
For functions with two arguments, you can use an infix notation. The following
expression is identical to N[ ,30].
In[28]:= N 30
Out[28]= 3.14159265358979323846264338328
Finally, many people prefer to use a more traditional syntax when entering and
working with mathematical expressions. You can compute an integral using standard
Mathematica syntax.
In[29]:= Integrate 1 Sin x , x
x x
Out[29]= Log Cos Log Sin
2 2
24 An Introduction to Programming with Mathematica
The same integral, represented in a more traditional manner, can be entered from palettes
or keyboard shortcuts.
1
In[30]:= x
Sin x
x x
Out[30]= Log Cos Log Sin
2 2
Many mathematical functions have traditional symbols associated with their opera-
tions and when available these can be used instead of the fully spelled-out names. For
example, you can compute the intersection of two sets using the Intersection function.
In[31]:= Intersection a, b, c, d, e , b, f, a, z
Out[31]= a, b
To learn how to enter these and other notations quickly, either from palettes or
directly from the keyboard using shortcuts, refer to the 2D Expression Input section in the
Front End category of the Help Browser.
• kernel does the computation and sends it back to the front end (kernel)
There is one remaining piece that we have not yet mentioned; that is MathLink.
Since the kernel and front end are two separate programs, a means of communication is
1 An introduction to Mathematica 25
necessary for these two programs to “talk” to each other. That communication protocol is
called MathLink and it comes bundled with Mathematica. It operates behind the scenes,
completely transparent to the user.
MathLink is a very general communications protocol that is not limited to communi-
cation between the front end and the kernel, but can also be used to set up communication
between the front end and other programs on your computer, programs like compiled C
and Fortran code. It can also be used to connect a kernel to a word processor or spread-
sheet or many other programs.
MathLink programming is beyond the scope of this book, but if you are interested,
there are several books and articles that discuss it (see the References at the end of this
book).
Errors
In the course of using and programming in Mathematica, you will encounter various sorts
of errors, some obvious, some very subtle, some easily rectified, and others not. We have
already mentioned that it is possible to send Mathematica into an infinite loop from which
it cannot return. In this section, we discuss those situations where Mathematica does finish
the computation, but without giving you the answer you expected.
Perhaps the most frequent error you will make is misspelling the name of a function.
Here is an illustration of the kind of thing that will usually happen in this case.
In[33]:= Sine 1.5
General::spell :
Possible spelling error: new symbol name "Sine" is
similar to existing symbols Line, Sin, Sinh . More…
Whenever you type a name that is close to an existing name, Mathematica will print a
warning message like the one above. You may often use such names intentionally, in which
case these messages can be annoying. In that case, it is best to turn off the warnings.
In[34]:= Off General::spell
Now, Mathematica will not report that function names might be misspelled; and,
when it cannot find a definition associated with a misspelled function, it returns your input
unevaluated.
In[35]:= Intergate x2 , x
Out[35]= Intergate x2 , x
26 An Introduction to Programming with Mathematica
Of course, some kinds of inputs cause genuine error messages. Syntax errors, as
shown above, are one example. The built-in functions are designed to usually warn you of
such errors in input. In the first example below, we have supplied the Log function with an
incorrect number of arguments (it expects one or two arguments only). In the second
example, FactorInteger operates on integers only and so the real number argument
causes the error condition.
In[38]:= Log 2, 16, 3
Log::argt : Log called with 3
arguments; 1 or 2 arguments are expected. More…
Getting help
Mathematica contains a vast array of documentation that you can access in a variety of
ways. It is also designed so that you can create new documentation for your own functions
and program in such a way that users of your programs can get help in exactly the same
way as they would for Mathematica’s built-in functions.
If you are aware of the name of a function but are unsure of its syntax or what it does,
the easiest way to find out about it is to evaluate ?function. For example, here is the
usage message for ParametricPlot.
1 An introduction to Mathematica 27
In[40]:= ?ParametricPlot
ParametricPlot fx, fy , u, umin, umax produces a parametric
plot of a curve with x and y coordinates fx and fy generated
as a function of t. ParametricPlot fx, fy , gx, gy , ... ,
u, umin, umax plots several parametric curves. More…
Also, if you were not sure of the spelling of a command (Integrate, for example),
you could type the following to display all built-in functions that start with Integ.
In[41]:= ?Integ*
System`
Integer IntegerExponent IntegerQ Integrate
IntegerDigits IntegerPart Integers
Clicking on one of these links will produce a short usage statement about that
function. For example, if you were to click on the Integrate link, here is what would be
displayed in your notebook.
Integrate f, x gives the indefinite integral of f with respect
to x. Integrate f, x, xmin, xmax gives the definite
integral of f with respect to x from xmin to xmax. Integrate
f, x, xmin, xmax , y, ymin, ymax gives a multiple
definite integral of f with respect to x and y. More…
Clicking the More… hyperlink would take you directly to the Help Browser where a
much more detailed explanation of this function can be found.
You can also get help by highlighting any Mathematica function and pressing the F1
key on your keyboard. This will take you directly into the documentation for that function
in the Help Browser.
Notice the eight category tabs near the top of the Help Browser window. Choosing
the Add-ons & Links tab will give you access to all of the packages that come with each
implementation of Mathematica. Similarly, choosing The Mathematica Book tab will give
you access to the entire Mathematica book that ships with each professional version of
Mathematica.
Suppose you were looking for information about three-dimensional parametric
graphics. First click the Built-in Functions tab, then select Graphics and Sound on the left,
then 3D Plots and finally ParametricPlot3D. The Help Browser should look like this:
Notice that in the main window, the Help Browser has displayed information about
the ParametricPlot3D function. This is identical to the usage message you would get
if you entered ?ParametricPlot3D.
1 An introduction to Mathematica 29
Alternatively, you could have clicked the Master Index tab and searched for “Paramet-
ricPlot3D” or even simply “parametric” and then browsed through the index to find what
you were looking for.
Many additional features are available in the Help Browser and you are advised to
consult your documentation for a complete list and description.
2 The Mathematica language
Expressions are the basic building blocks from which everything is built. Their
structure, internal representation, and how they are evaluated are essential to under-
standing Mathematica. In this chapter we focus on the Mathematica language with
particular emphasis on the structure and syntax of expressions. We will also look at
how to define and name new expressions, how to combine them using logical opera-
tors, and how to control properties of your expressions through the use of attributes.
2.1 Expressions
Introduction
Although it may appear different at first, everything that you will work with in Mathematica
has a similar underlying structure. This means things like a simple computation, a data
object, a graphic, the cells in your Mathematica notebook, even your notebook itself, all
have a similar structure – they are all expressions, and an understanding of expressions is
essential to mastering Mathematica.
The Head function can be used to identify types of objects. For numbers, it will
report whether the number is an integer, a rational number, a real number, or a complex
number.
1
In[1]:= Head 7 , Head , Head 7.0 , Head 7 2
7
Out[1]= Integer, Rational, Real, Complex
In fact, every Mathematica expression has a Head that gives some information about
that type of expression.
In[2]:= Head a b
Out[2]= Plus
In[3]:= Head 1, 2, 3, 4, 5
Out[3]= List
Atoms
The three basic building blocks of Mathematica – the atoms – from which every expression
is ultimately constructed are, symbols, numbers, and strings.
A symbol consists of a letter followed without interruption by letters and numbers.
For example, both f and the built-in Integrate are symbols.
In[4]:= Head f
Out[4]= Symbol
Symbols can consist of one or more concatenated characters so long as they do not begin
with a number.
In[7]:= Head myfunc
Out[7]= Symbol
2 The Mathematica language 33
The four kinds of numbers – integers, real numbers, complex numbers and rational
numbers – are shown in the list below.
5
In[8]:= Head 4 , Head , Head 5.201 , Head 3 4
7
Out[8]= Integer, Rational, Real, Complex
h e1 , e2 , …, en
Although we indicated that you can use Head to determine the type of atomic
expressions, this is entirely general. For normal expressions, Head simply gives the head of
that expression.
In[10]:= Head a b c
Out[10]= Plus
In[12]:= FullForm a, b, c
Out[12]//FullForm=
List a, b, c
The important thing to notice is that both of these objects (the sum and the list) have
very similar internal representations. Each is made up of a function (Plus and List,
34 An Introduction to Programming with Mathematica
respectively), each encloses its arguments in square brackets, and each separates its argu-
ments with commas.
Regardless of how an atomic or normal expression may appear in your notebook, its
structure is uniquely determined by its head and parts as seen using FullForm. This is
important for understanding the Mathematica evaluation mechanism which depends on the
matching of patterns based on their FullForm representation, a subject we will turn to in
detail in Chapter 6.
The number of elements in any expression is given by its length.
In[13]:= Length a b c
Out[13]= 3
Out[14]= c bx a x2 Sin x
Its head is Times because it is composed of the product of Sin[x] and the quadratic
polynomial.
In[15]:= Head expr
Out[15]= Times
Although the FullForm of this expression is a little harder to decipher, if you look
carefully you should see that it is composed of the product of Plus[c,Times[b,x],
Times[a,Power[x,2]]] and Sin[x].
In[17]:= FullForm expr
Out[17]//FullForm=
Times Plus c, Times b, x , Times a, Power x, 2 , Sin x
There are several important differences between atomic expressions and nonatomic
expressions. While the heads of all expressions are extracted in the same way – using the
Head function – the head of an atom provides different information than the head of other
expressions. For example, the head of a symbol or string is the kind of atom that it is.
In[18]:= Head Integrate
Out[18]= Symbol
Exploring the Variety of Random
Documents with Different Content
into his blood. At the same instant he was conscious of a stab of
shame. It was the flesh, the draperies, the trappings to which his
pulses responded; it was not the magical secret which was contained
in the miniatures upon the walls, in the passionate delicacy of the
cadences which sobbed themselves out liquidly under the siren’s
touch of this beautiful woman.
He stood in front of the cosy fire, glass in hand. A soft warmth
overspread his being. His eyes glanced from the white shoulders of
the enchantress to the thousand and one hues which were blended
so cunningly in the carpets and tapestries. The subtle playings of
light and shadow, the mellow effects of the atmosphere, the
softness of the music, began to assail his senses with indescribable
pangs. He feasted his eyes, his ears, his nostrils; they rewarded him
with gladness. His heart beat violently.
“These rare kinds of genius, are they not barbarous?” he said, when
the siren had ceased to cast her fingers.
“It is like children lisping,” she said, half-turning her head, with a
smile that curved her mouth entrancingly.
“Yes,” said the young man, “poetry, romance, imagination are
primitive; they belong to the childhood of nations, to the dawn of
new worlds. What a divine inspiration these sweet-voiced children of
nature who are bought out of due time, these unhappy Poles,
Germans, and Frenchmen bring to their despair. Instead of sitting
down in black coats to make their music into beef and mutton, they
should be tripping through the glades piping to the birds, the trees,
the bright air.”
“This is a mad fellow, my angel,” said Mr. Whitcomb indulgently, “but
if you are gentle with him you may find him amusing.”
“Mr. Northcote will amuse me enormously,” said the lady, with a
demure glance.
“Is it thus you rebuke his madness?” the young man asked.
“On the contrary, I don’t think I have ever seen a sanity that is quite
so perfect.”
“Drop it,” said the solicitor, roguishly pinching her ear. “Beware of
dangerous turnings, my son. She is quite prepared to play George
Sand to anybody’s Alfred de Musset. She even does it to the
greengrocer when he comes round with his barrow. I understand
they discourse divinely together upon the subject of cabbages.”
“But Witty is too much the man of the world to be jealous about it,”
she purred.
“If Pussy hasn’t the opportunity to sharpen her claws on a sofa or an
ottoman, she doesn’t mind a wicker-work chair.”
“Witty, darling,” said the lady, “I hate to find rudeness keeping
company with real distinction of mind.”
“Upon my word,” expostulated Northcote, seeking to measure her
depth, “I consider that rebuke to be much prettier than the one
bestowed upon me.”
“When, Mr. Northcote, did I rebuke you?”
“Did you not say I should amuse you enormously?”
“Is not that the only compliment a woman has the power to pay
nowadays?”
“Yes, Noodle,” said Mr. Whitcomb, laughing; “but don’t you see how
young he is, and therefore how serious? Who would call ‘enormously
amusing’ a fitting compliment for one of the seven champions of
Christendom? This is a devil of a fellow.”
“I can roar you like any sucking dove,” said the young man.
“How it would thrill one to hear you do it!” said the lady, enfolding
him with large eyes.
“He is a man of destiny,” said Mr. Whitcomb; “he carries a genie in
his pocket.”
“Oh!” said the lady, with clasped hands.
“One of these fine mornings he will stand the world on its head.”
“O-o-o-o-h!” said the lady.
“And having done that,” said Northcote, “this amazing fellow will dig
a hole in the universe for to bury the moon.”
“I would that all men had ambition,” said the lady, looking down at
her shoe. “If Witty had only a little of that precious salt which forms
a sediment at the bottom of every fine action he would be one’s
beau-ideal of a hero, a Christian, and a philosopher.”
“Minx!” exclaimed the solicitor. “If it were not for my ambition I
should never rise from my bed.”
“So this wonderful Mr. Whitcomb has no ambition!” said Northcote.
“You see I have found his character so complex, that in my capacity
of an amateur of the human mind I am picking it out, here a little,
there a little, piece by piece.”
“You must give him no marks for ambition,” said the lady. “But since
when did you become acquainted with him not to have found out
that?”
“Since this evening at ten.”
“Ah, then, you are absolved. He will certainly baffle you at first.”
“He is wholly incomprehensible to me. He is a man of moods who
oughtn’t to have any.”
The lady clapped her hands in a little ripple of glee.
“How right,” she cried. “In a dozen little words you have shown me
the nothingness of my own knowledge.”
“Of course he has, Vapid One,” said Mr. Whitcomb. “Have I not told
you he carries a genie in his pocket?”
“Then that is why his eyes are so deep and bright,” said the lady,
turning to peruse Northcote again with an unfathomable coquetry;
“and would you not say, Witty, that the genie is in some sort
responsible for his mouth?”
“Is this public laying of one another upon the dissecting-table a new
parlor-game that has been brought into vogue by the long winter
evenings, may I ask?” said Mr. Whitcomb, concealing a yawn.
“Pray do not be insolent, Witty. The proper study of mankind is
Man.”
“In the words of Pope,” said the solicitor, turning to replenish his
glass.
“You can see how Mr. Whitcomb baffles me,” said Northcote, who did
not propose to lose the opportunity of following up his clue.
“Is it his attitude to hansom cabmen that makes him so dark?”
“That is contributory. But it is mainly because he has come before
me in the guise of a waverer that I stand so much at fault. If one
knows anything about anything one would be prepared to affirm that
nature had designed Samuel Whitcomb to know his own mind.”
“He does as a rule. I have never known him waver in anything; but
then, of course, it is only quite recently that he has begun to
associate with dangerous persons who keep a genie.”
“Do you suggest that he is susceptible to such a thing as a genie?
Would it have a malign influence upon him, do you suppose?”
“I would suggest it to be likely in the highest degree.”
“Now, look here, my young friends,” interposed the solicitor at this
point, with a broad good humor, “Samuel Whitcomb does not
propose to play the part of the corpse at the lecture on anatomy.”
“You will help yourself to another drink like a good boy,” said the
lady severely; “and you will please to say nothing until we have dealt
with your ‘case.’ Your character need not fear the lancet and bistoury
of true science. Tell me, Mr. Northcote, wherein he is a waverer.”
“I am rejoiced to hear you put that question,” said the young man,
with a gesture of triumph he did not try to conceal, “for now it is
that I unfold my tale.”
XII
THE FAITH OF A SIREN
“At about ten o’clock this evening,” Northcote began, “as I was
kneeling in front of the fire—there was not any fire, by the way, as it
costs too much to afford one sometimes—in my miserable dwelling
at the top of Shepherd’s Inn, the oldest and most moribund of all the
buildings in Fleet Street, who should come climbing up to the
topmost story of the rickety and unwholesome stairs, under which
the rats have made their home for many generations, but Mr.
Whitcomb. And what do you suppose was his business?”
“He wished to buy one of your pictures.”
“Ah, no, I am not a painter.”
“I thought there was a chance of it, since they say all very good
painters are so poor. But perhaps you are a little too fierce, although
I am told these impressionists are terrible men.”
“The painting of pictures is one of the few things I have not
attempted,” said the young man, consenting to this interruption that
he might sit for his own portrait.
“Well, I should not say you are a writer of fiction. They are so tame.
Besides they are all nearly as rich as solicitors.”
“Why not a poet?”
“Why not? although your fierceness would make you a dramatic, not
a lyric one. Still it is impossible for you to be a poet, because I am
sure that Witty would never have climbed up all those stairs to your
miserable garret—I feel sure it is a garret with a sloping roof with a
hole in it—”
“There is a pool under the hole which has been caused by the
percolation of water—”
“On to the atrocious bare boards, its occupant being much too poor
to afford a carpet. Yes, Witty would never have climbed up to your
garret if you had been a poet. Or stay, he might, had you been Mrs.
Felicia Hemans. As you are a seeker of documentary evidence, he
has been known to recite her poems, at the request of the rector of
this parish, to a Sunday-school party.”
“Base woman,” said the solicitor, with an air of injury; “I claim to be
an admirer of the poet Longfellow.”
“Never, Witty, in your heart; it is merely your fatal craving to be
respectable in all things. But in the matter of poetry you must be
content to remain outside. You would never have climbed those
rickety stairs to that cold garret to see John Keats.”
“Well, now, Featherhead, did I not tell you at the first that our young
friend was England’s future Lord Chancellor?”
“I will never believe that; I will never believe that his destiny is the
law. His eye has amazing flashes; and is there not a beautiful
eloquence burning in his mouth? I cannot think of him as rich Witty,
and successful Witty, and smug Witty, like you atrocious lawyers. He
is one who would be an overthrower of dynasties, a saviour of
societies.”
“You are letting your tongue wag, Noodle. If you talk so much it will
take the young man until daybreak to unfold his story.”
“I am an advocate,” said Northcote.
“An advocate,” said the lady softly; “yes, I think you may be that.
One no more associates an advocate with the law than one
associates a poet with a publisher.”
“You would say,” said Northcote, “that it is the function of an
advocate to draw his sword for the truth, for progress, for justice,
for every human amenity?”
“I would, indeed. Why, if one thinks about it, surely it is nobler to be
an advocate than to be a poet or a soldier. One might say it was the
highest calling in the world.”
“Then let us say it,” said the young man, “for I verily believe it to be
so.”
“And what, pray, was Witty’s business with this advocate?”
“They are going to hang a woman; and Mr. Whitcomb, who to his
infinite complexities and many-sidedness as a citizen of the world
adds a leaven of the finest humanitarian principles, has undertaken
to save the poor creature from a fate so pitiful.”
“To hang a woman!” said the lady, drawing in her breath with a
sharp sound. “Is it still possible to hang a woman at this time of
day?”
“Perfectly,” said the young man. “They do it in every Christian
country.”
“Then the world has need for an advocate,” said the lady, with
horror in her eyes. “It is necessary that we should have yet another
champion for our sex in Christendom. Yes, this was he whom Witty
came to seek in that garret at the top of all those rickety stairs.”
“He came to seek, and found no less a person,” said Northcote. “And
having found this authentic champion of your sex, he gave him a
mandate to plead on behalf of this unfortunate creature, the least
happy of all its members.”
“What a moment of high inspiration for us and for him,” said the
lady, with a glance of tenderness.
“It was even as you say. But I would have you mark what follows.
Scarcely has he bestowed these high plenary powers upon one
whom he has ventured to select from among all the great multitude
to champion your sex in the name of humanity, than for a whim he
withdraws his mandate.”
“Impossible; it would be an outrage upon us.”
“Yes; unconditionally and peremptorily he withdraws his mandate.”
“Impossible; they will do the poor creature to death.”
“Yes, they will do her to death. He who has been called to the office
of averting her doom has decreed that she must walk to embrace it
without a friend to plead her cause before humanity.”
“Surely this cannot be; society itself must protest.”
“One expects it; yet things are as they are.”
The beautiful creature turned to the solicitor with an almost royal air.
“What, sir, can you find to say in your defence?”
Mr. Whitcomb gave a short laugh.
“I yield,” said he.
“You restore the mandate?”
“Yes, yes, yes! My blood be on my own head, but so it must be. It is
beyond flesh and blood to withstand such a pair. You, madam, are a
sorceress; and this fellow is the devil.”
“I am content to be a sorceress in the cause of my unfortunate sex,”
cried the lady; and turning to Northcote added gravely: “And is it not
high time that we acquired a devil for our advocate?”
Northcote, who from the moment of her first appearance had
foreseen a victory, took her hand to his lips impulsively, with an
expression of gratitude.
“I hope this will be all right,” said the solicitor, viewing his surrender
with a rueful smile. “You see it is the first time in my life that a
foreboding has overtaken me in the midst of action. Whether it is
the importance of the case, the obscurity of the advocate, or a
certain flamboyancy in his bearing which is so repugnant to an
English common lawyer, I cannot tell; but let me confess that I have
already a premonition that I have been guilty of a mistake. And I will
go farther,” said Mr. Whitcomb, with a wry laugh; “I even see ruin,
blue ruin for all concerned, hidden in this irresolute act. Sharp little
shivers go down my spine.”
“It is no more than the reaction,” said Northcote, “which attends our
highest resolves. Is it not in such moments that a man truly
measures himself? It must have been at the fall of the barometer
that Samson was shorn of his locks.”
“Is there not always a woman in these cases?” said the lady. “This
unfortunate creature whom our advocate is to deliver from the
gallows, may she not be a Delilah of some kind?”
XIII
BE BOLD, WARY, FEAR NOT
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookfinal.com